在之前我们都使用xml文件为Mapper配置SQL映射器,还有一种方法,通过注解的方式。
虽然现在大部分开发还是会采用xml文件配置SQL映射器,但注解的方式也要了解一下:
基本映射语句
基本映射语句就是指:简单的增删改查:
1,@Insert 2,@Update 3,@Delete 4,@Select
@Insert("insert into t_student values(null,#{name},#{age},#{address.id},#{grade.id})")
public int add(Student student);
@Update("update t_student set name=#{name},age=#{age},addressId=#{address.id},gradeId=#{grade.id} where id=#{id}")
public int update(Student student);
@Delete("delete from t_student where id=#{id}")
public int delete(Integer id);
@Select("select * from t_student")
@Results(
{
@Result(id=true,column="id",property="id"),
@Result(column="name",property="name"),
@Result(column="age",property="age"),
}
)
public List<Student> find();
在定义的接口前,加注解,在注解里面写SQL语句。
关系映射的实现
还是之前的例子:
一个学生对应一个班级,一个地址。
一个班级对应多个学生。
实现查询学生时候,把班级,地址信息查出来。
查班级信息时,把学生信息查出来。
一对一关系:
@Select("select * from t_student where id=#{id}")
@Results(
{
@Result(id=true,column="id",property="id"),
@Result(column="name",property="name"),
@Result(column="age",property="age"),
@Result(column="addressId",property="address",one=@One(select="com.java.mappers.AddressMapper.findById")),
@Result(column="gradeId",property="grade",one=@One(select="com.java.mappers.GradeMapper.findById"))
}
)
public Student findById(Integer id);
@Select("select * from t_student")
@Results(
{
@Result(id=true,column="id",property="id"),
@Result(column="name",property="name"),
@Result(column="age",property="age"),
@Result(column="addressId",property="address",one=@One(select="com.java.mappers.AddressMapper.findById")),
@Result(column="gradeId",property="grade",one=@One(select="com.java.mappers.GradeMapper.findById"))
}
)
public List<Student> find();
@Select("select * from t_address where id=#{id}")
public Address findById(Integer id);
@Select("select * from t_grade where id=#{id}")
public Grade findById(Integer id);
一对多关系
@Select("select * from t_grade where id=#{id}")
@Results(
{
@Result(id=true, column="id",property="id"),
@Result(column="gradeName",property="gradeName"),
@Result(column="id",property="students",many=@Many(select="com.java.mappers.StudentMapper.findByGradeId"))
}
)
public Grade findById(Integer id);
@Select("select * from t_student where gradeId=#{gradeId}")
@Results(
{
@Result(id=true,column="id",property="id"),
@Result(column="name",property="name"),
@Result(column="age",property="age"),
@Result(column="addressId",property="address",one=@One(select="com.java.mappers.AddressMapper.findById")),
@Result(column="gradeId",property="grade",one=@One(select="com.java.mappers.GradeMapper.findById"))
}
)
public Student findByGradeId(Integer gradeId);