博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
小峰mybatis(4)mybatis使用注解配置sql映射器
阅读量:6516 次
发布时间:2019-06-24

本文共 11684 字,大约阅读时间需要 38 分钟。

主流开发还是使用xml来配置;使用注解配置比较快,但是不支持所有功能;有些功能还是得用配置文件;

一、基本映射语句:                                

@Inert

@Update

@Delete

@Select

二、结果集映射语句                                

项目结够:

Student.java model实体类:

package com.cy.model;public class Student{    private Integer id;    private String name;    private Integer age;        public Student(){            }        public Student(String name, Integer age){        this.name = name;        this.age = age;    }        public Integer getId() {        return id;    }    public void setId(Integer id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public Integer getAge() {        return age;    }    public void setAge(Integer age) {        this.age = age;    }    @Override    public String toString() {        return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";    }            }
View Code

mybatis-config.xml:

View Code

StudentMapper.java 接口:

package com.cy.mapper;import java.util.List;import org.apache.ibatis.annotations.Delete;import org.apache.ibatis.annotations.Insert;import org.apache.ibatis.annotations.Result;import org.apache.ibatis.annotations.Results;import org.apache.ibatis.annotations.Update;import org.apache.ibatis.annotations.Select;import com.cy.model.Student;public interface StudentMapper {        //插入    @Insert("insert into t_student values(null, #{name}, #{age})")    public int inertStudent(Student student);        //更新    @Update("update t_student set name=#{name}, age=#{age} where id = #{id}")    public int updateStudent(Student stu);        //删除    @Delete("delete from t_student where id=#{id}")    public int deleteStudent(int id);        //根据id查找学生    @Select("select * from t_student where id=#{id}")    public Student getStudentById(Integer id);        //查询所有学生  结果集映射  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
findStudents();}

测试代码StudentTest.java:

package com.cy.service;import java.util.List;import org.apache.ibatis.session.SqlSession;import org.apache.log4j.Logger;import org.junit.After;import org.junit.Before;import org.junit.Test;import com.cy.mapper.StudentMapper;import com.cy.model.Student;import com.cy.util.SqlSessionFactoryUtil;public class StudentTest {    private static Logger logger = Logger.getLogger(StudentTest.class);        private SqlSession sqlSession=null;    private StudentMapper studentMapper=null;        @Before    public void setUp() throws Exception {        sqlSession=SqlSessionFactoryUtil.openSession();        studentMapper=sqlSession.getMapper(StudentMapper.class);    }        @After    public void tearDown() throws Exception {        sqlSession.close();    }        @Test    public void testInsertStudent() {        logger.info("测试insertStudent");        Student stu = new Student("cpp", 12);        int count = studentMapper.inertStudent(stu);        sqlSession.commit();    }        @Test    public void testUpdateStudent() {        logger.info("测试updateStudent");        Student stu = new Student("cppp", 13);        stu.setId(14);        int count = studentMapper.updateStudent(stu);        sqlSession.commit();    }        @Test    public void testDeleteStudent() {        logger.info("测试删除学生");        int count = studentMapper.deleteStudent(14);        sqlSession.commit();    }        @Test    public void testGetById(){        logger.info("根据id查找学生");        Student stu = studentMapper.getStudentById(1);        System.out.println(stu);    }        @Test    public void testFindStudent() {        logger.info("测试查询所有学生");        List
students = studentMapper.findStudents(); for(Student student : students){ System.out.println(student); } }}

 

三、使用注解 一对一映射:                                    

每个学生都有一个地址,一对一;
数据库中t_student和t_address:
t_address:
Student.java 实体:
package com.cy.model;public class Student{    private Integer id;    private String name;    private Integer age;    private Address address;        public Student(){            }        public Student(String name, Integer age){        this.name = name;        this.age = age;    }        public Integer getId() {        return id;    }    public void setId(Integer id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public Integer getAge() {        return age;    }    public void setAge(Integer age) {        this.age = age;    }            public Address getAddress() {        return address;    }    public void setAddress(Address address) {        this.address = address;    }    @Override    public String toString() {        return "Student [id=" + id + ", name=" + name + ", age=" + age                + ", address=" + address + "]";    }        }
View Code

Address.java 实体:

package com.cy.model;public class Address {    private Integer id;    private String sheng;    private String shi;    private String qu;        public Integer getId() {        return id;    }    public void setId(Integer id) {        this.id = id;    }    public String getSheng() {        return sheng;    }    public void setSheng(String sheng) {        this.sheng = sheng;    }    public String getShi() {        return shi;    }    public void setShi(String shi) {        this.shi = shi;    }    public String getQu() {        return qu;    }    public void setQu(String qu) {        this.qu = qu;    }    @Override    public String toString() {        return "Address [id=" + id + ", sheng=" + sheng + ", shi=" + shi                + ", qu=" + qu + "]";    }        }
View Code

StudentMapper.java接口:

//查询学生,带地址    @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"))            }    )    public Student findStudentWithAddress(int id);

AddressMapper.java接口:

public interface AddressMapper {    @Select("select * from t_address where id=#{id}")    public Address findById(Integer id);}

mybatis的实现是:在查找学生的时候,将addressId,传到AddressMapper.findById方法,根据这个addressId查找address;

测试代码:

@Test    public void testFindStudentWithAddress() {        logger.info("测试学生,带地址");        Student student = studentMapper.findStudentWithAddress(15);        System.out.println(student);    }

console打印:

 

四、使用注解,一对多映射                                  

一个年级下有多个学生,多个学生属于一个年级,年级和学生是一对多;
Student.java:
package com.cy.model;public class Student{    private Integer id;    private String name;    private Integer age;    private Address address;    private Grade grade;        public Student(){            }        public Student(String name, Integer age){        this.name = name;        this.age = age;    }        public Integer getId() {        return id;    }    public void setId(Integer id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public Integer getAge() {        return age;    }    public void setAge(Integer age) {        this.age = age;    }            public Address getAddress() {        return address;    }    public void setAddress(Address address) {        this.address = address;    }        public Grade getGrade() {        return grade;    }    public void setGrade(Grade grade) {        this.grade = grade;    }    @Override    public String toString() {        return "Student [id=" + id + ", name=" + name + ", age=" + age                + ", address=" + address + ", grade=" + grade + "]";    }            }
View Code

Grade.java:

package com.cy.model;import java.util.List;public class Grade {    private Integer id;    private String gradeName;    private List
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
getStudents() { return students; } public void setStudents(List
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
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);    }

打印结果:

 

 

 

 

 

 

 

 

 

转载于:https://www.cnblogs.com/tenWood/p/6697198.html

你可能感兴趣的文章
MyBatis原理简介和小试牛刀
查看>>
js部分基础
查看>>
Docker 常用基础命令
查看>>
脏读,幻读,不可重复读解释和例子
查看>>
Day02 数值运算&条件判断
查看>>
Tomcat指定(JDK路径)JAVA_HOME而不用环境变量
查看>>
Bluemix专属版本落地中国 开放物联网和认知计算能力
查看>>
汤姆大叔的6道javascript编程题题解
查看>>
【世界知名量子科学家加盟阿里】施尧耘出任阿里云量子技术首席科学家
查看>>
DataCore对外出售其虚拟化软件产品
查看>>
说说云计算与移动管理
查看>>
T-Mobile美国使用28GHz频段测试5G
查看>>
如何缓解影子云服务安全风险?
查看>>
Bossies 2016:最佳开源大数据工具
查看>>
银行卡信息安全事件频发 互联网站成数据泄露"重灾区"
查看>>
云服务器 ECS 使用OpenAPI管理ECS:使用OpenAPI弹性创建ECS实例
查看>>
象云2.0产品发布暨国产操作系统首次入驻公有云
查看>>
一个完美DCIM应该具备的功能与价值
查看>>
《SEO的艺术(原书第2版)》——1.5 人们如何搜索
查看>>
经验贴 | 电梯监控的布线技巧
查看>>