MyBatis的基本注解

做~自己de王妃 提交于 2019-12-01 19:35:17

 MyBatis的基本注解:

增删改查

@Select("select * from teacher")

 public List<Teacher> selAll();

 

 //增删改返回值都是int

 @Insert("insert into teacher values(default,#{name})")

 public int add(Teacher teacher);

 

 @Update("update teacher set name=#{name} where id=#{id}")

 public int update(Teacher teacher);

 

 @Delete("delete from teacher where id=#{id}")

 public int delete(int id);

  

注解映射:

1.普通映射

 

  1.  
    @Select("select * from mybatis_Student where id=#{id}")
  2.  
    public Student getStudent(int id);
  3.  
    @Insert("insert into mybatis_Student (name, age, remark, pic,grade_id,address_id) values (#{name},#{age},#{remark}, #{pic},#{grade.id},#{address.id})")
  4.  
    public int insert(Student student);
  5.  
    @Update("update mybatis_Student set name=#{name},age=#{age} where id=#{id}")
  6.  
    public int update(Student student);
  7.  
    @Delete("delete from mybatis_Student where id=#{id}")
  8.  
    public int delete(int id);

2.结果集映射

 

 

  1.  
    @Select("select * from mybatis_Student")
  2.  
    @Results({
  3.  
    @Result(id=true,property="id",column="id"),
  4.  
    @Result(property="name",column="name"),
  5.  
    @Result(property="age",column="age")
  6.  
    })
  7.  
    public List<Student> getAllStudents();

3.关系映射

 

3.1一对一

 

  1.  
    @Select("select * from mybatis_Student")
  2.  
    @Results({
  3.  
    @Result(id=true,property="id",column="id"),
  4.  
    @Result(property="name",column="name"),
  5.  
    @Result(property="age",column="age"),
  6.  
    @Result(property="address",column="address_id",one=@One(select="com.skymr.mybatis.mappers.AddressMapper.getAddress"))
  7.  
    })
  8.  
    public List<Student> getAllStudents();

3.2一对多

 

 

  1.  
    @Select("select * from mybatis_grade where id=#{id}")
  2.  
    @Results({
  3.  
    @Result(id=true,column="id",property="id"),
  4.  
    @Result(column="grade_name",property="gradeName"),
  5.  
    @Result(property="students",column="id",many=@Many(select="com.skymr.mybatis.mappers.Student2Mapper.getStudentsByGradeId"))
  6.  
    })
  7.  
    public Grade getGrade(int id);
  8.  

 

注解的使用

一. 查询@Select

 

.自动关联@Results

 

.引用@Results映射(@ResultMap

 

.关联映射:@One

 

 

 

五. 关联映射:@Many

 

 

 

.添加(@Insert)并且返回主键

 

 

 

.修改@Update

 

 

.删除@Delete

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!