Mybatis使用注解实现主键自增长:
oracle:
@SelectKey(statement="select my_seq.nextval from dual",resultType=int.class,keyProperty="id",before=true)
statement是生成id语句,resultType是语句返回类型,keyProperty是填入id列,before是先写入对象,再写入表
mysql:
@Options(useGeneratedKeys=true,keyProperty="id",keyColumn="id")
@Results:结果映射
@Results注解和映射器XML配置文件元素<resultMap> 对应。
@Select("select id as pid,name,age from person") @Results({ @Result(id=true,property="id",column="pid"), @Result(property="name",column="name"), @Result(property="age",column="age") }) public List<Person> selectAllPerson_ResultMap();
resultMap可以重用,@Results不可以重用。
解决方法:
创建一个映射器Mapper配置文件,然后配置<resultMap>元素,然后使用 @ResultMap注解引用此<resultMap>
@ResultMap(【命名空间名】.【ResultMap_id】)
@One注解:
一对一关联查询
@Select("select addr_id as addrId, street, city, state, zip, country from addresses where addr_id=#{id}") Address findAddressById(int id); @Select("select * from students where stud_id=#{studId} ") @Results( { @Result(id = true, column = "stud_id", property = "studId"), @Result(column = "name", property = "name"), @Result(column = "email", property = "email"), @Result(property = "address", column = "addr_id", one = @One(select = "com.briup.mapper.StudentMapper.findAddressById")) }) Student selectStudentWithAddress(int studId);
@Many注解:
一对多关联查询
@Select("select addr_id as addrId, street, city, state, zip, country from addresses where addr_id=#{id}") Address findAddressById(int id); @Select("select * from courses where tutor_id=#{tutorId}") @Results( { @Result(id = true, column = "course_id", property = "courseId"), @Result(column = "name", property = "name"), @Result(column = "description", property = "description"), @Result(column = "start_date" property = "startDate"), @Result(column = "end_date" property = "endDate") }) List<Course> findCoursesByTutorId(int tutorId); @Select("SELECT tutor_id, name as tutor_name, email, addr_id FROM tutors where tutor_id=#{tutorId}") @Results( { @Result(id = true, column = "tutor_id", property = "tutorId"), @Result(column = "tutor_name", property = "name"), @Result(column = "email", property = "email"), @Result(property = "address", column = "addr_id", one = @One(select = "com.briup.mappers.Tutor Mapper.findAddressById")), @Result(property = "courses", column = "tutor_id", many = @Many(select = "com.briup.mappers.Tutor Mapper.findCoursesByTutorId")) }) Tutor findTutorById(int tutorId);
@mapper注解:
把mapper这个DAO交给spring去管理
不在写mapper的映射文件