您的位置:首页 > 数据库

小峰mybatis(4)mybatis使用注解配置sql映射器

2017-04-12 01:46 375 查看
主流开发还是使用xml来配置;使用注解配置比较快,但是不支持所有功能;有些功能还是得用配置文件;
一、基本映射语句:                                

@Inert

@Update

@Delete

@Select

二、结果集映射语句                                

项目结够:

package com.cy.model;

import java.util.List;

public class Grade {

private Integer id;
private String gradeName;
private List<Student> students;

public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getGradeName() {
return gradeName;
}
public void setGradeName(String gradeName) {
this.gradeName = gradeName;
}
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
@Override
public String toString() {
return "Grade [id=" + id + ", gradeName=" + gradeName +"]";
}

}


View Code
数据库中表,t_student:



t_grade:



1)根据id查找年级,将年级下的学生也查出来:

GradeMapper.java:

public interface GradeMapper {

//根据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.cy.mapper.StudentMapper.findStudentByGradeId"))
}
)
public Grade findById(Integer id);
}


StudentMapper.java:

//根据年级查找学生
@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.cy.mapper.AddressMapper.findById"))
}
)
public Student findStudentByGradeId(int gradeId);


测试代码:

//根据id查找年级,将年级下的学生也查出来
@Test
public void testFindGradeWithStudents() {
logger.info("根据id查询年级(带学生)");
Grade grade=gradeMapper.findById(1);
System.out.println(grade);
List<Student> studentList=grade.getStudents();
for(Student student:studentList){
System.out.println(student);
}
}


结果:



2)根据id查询学生,将年级信息也查出来:

StudentMapper.java:

//根据id查询学生带地址   和 年级
@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.cy.mapper.AddressMapper.findById")),
@Result(column="gradeId",property="grade",one=@One(select="com.cy.mapper.GradeMapper.findById"))
}
)
public Student findStudentWithAddressAndGrade(int id);


GradeMapper.java中的findById和上面1)中一样;

测试代码:

//根据id查询学生,带地址和年级
@Test
public void testSelectStudentWithAddressAndGrade() {
logger.info("根据id查询学生(带地址、年级)");
Student student=studentMapper.findStudentWithAddressAndGrade(1);
System.out.println(student);
}


打印结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: