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


    主流开发还是使用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:

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE configuration
    PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
        <properties resource="jdbc.properties"/>
        <!-- 别名 -->
        <typeAliases>
            <package name="com.cy.model"/>
        </typeAliases>
        
        <environments default="development">
            <environment id="development">
                <transactionManager type="JDBC" />
                    <dataSource type="POOLED">
                        <property name="driver" value="${jdbc.driverClassName}" />
                        <property name="url" value="${jdbc.url}" />
                        <property name="username" value="${jdbc.username}" />
                        <property name="password" value="${jdbc.password}" />
                    </dataSource>
            </environment>
            <environment id="test">
                <transactionManager type="JDBC" />
                <dataSource type="POOLED">
                    <property name="driver" value="${jdbc.driverClassName}" />
                    <property name="url" value="${jdbc.url}" />
                    <property name="username" value="${jdbc.username}" />
                    <property name="password" value="${jdbc.password}" />
                </dataSource>
            </environment>
        </environments>
        
        <mappers>
            <package name="com.cy.mapper"/>
        </mappers>
    </configuration>
    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<Student> 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<Student> 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<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);
        }

    打印结果:

  • 相关阅读:
    Android Bitmap 常见的几个操作:缩放,裁剪,旋转,偏移
    vue.js 本地解决跨域
    VUE添加网站favicon.ico图标
    在mpvue引入flyio
    页面中加入地图map
    360校招——最后赢家(C++)
    奇安信校招——买口罩(c++)
    携程校招——携程海洋馆的海豚小宝宝(C++)
    阿里云Web应用托管服务,低成本建个人博客(wordpress和wiki.js)
    (嵌入式)工程模板的创建和MDK下配置开发STM32F103ZE
  • 原文地址:https://www.cnblogs.com/tenWood/p/6697198.html
Copyright © 2020-2023  润新知