Mybatis学习之注解注解方式关系映射(十)

Mybatis注解注解方式关系映射
一对一关系
一对多关系

1.编写log4j.properties,jdbc.properties,mybatis-config.xml文件

log4j.rootLogger=info,appender1,appender2

log4j.appender.appender1=org.apache.log4j.ConsoleAppender 

log4j.appender.appender2=org.apache.log4j.FileAppender 
log4j.appender.appender2.File=C:/logFile.txt

log4j.appender.appender1.layout=org.apache.log4j.TTCCLayout
log4j.appender.appender2.layout=org.apache.log4j.TTCCLayout  
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db_mybatis
jdbc.username=root
jdbc.password=123456
<?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.newbeedaly.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.newbeedaly.mappers"/>
    </mappers>
</configuration>

2.编写SqlSessionFactoryUtil工具类

package com.newbeedaly.util;

import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class SqlSessionFactoryUtil {

    private static SqlSessionFactory sqlSessionFactory;

    public static SqlSessionFactory getSqlSessionFactory(){
        if(sqlSessionFactory==null){
            InputStream inputStream=null;
            try{
                inputStream=Resources.getResourceAsStream("mybatis-config.xml");
                sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        return sqlSessionFactory;
    }

    public static SqlSession openSession(){
        return getSqlSessionFactory().openSession();
    }
}

3.编写类Student,Grade,Address

package com.newbeedaly.model;

public class Student {

    private Integer id;
    private String name;
    private Integer age;
    private Address address;
    private Grade grade;


    public Student() {
        super();
        // TODO Auto-generated constructor stub
    }




    public Student(Integer id, String name, Integer age) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
    }




    public Student(String name, Integer age) {
        super();
        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 + "]";
    }






}
package com.newbeedaly.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 +"]";
    }


}
package com.newbeedaly.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 + "]";
    }


}

4.编写StudnetMapper,GradeMapper,AddressMapper映射文件

package com.newbeedaly.mappers;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.newbeedaly.model.Student;


public interface StudentMapper {

    @Insert("insert into t_student values(null,#{name},#{age})")
    public int insertStudent(Student student);

    @Update("update t_student set name=#{name},age=#{age} where id=#{id}")
    public int updateStudent(Student student);

    @Delete("delete from t_student where id=#{id}")
    public int deleteStudent(int id);

    @Select("select * from t_student where id=#{id}")
    public Student getStudentById(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> findStudents();

    @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.newbeedaly.mappers.AddressMapper.findById"))
            }
    )
    public Student selectStudentWithAddress(int 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.newbeedaly.mappers.AddressMapper.findById"))
            }
    )
    public Student selectStudentByGradeId(int gradeId);

    @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.newbeedaly.mappers.AddressMapper.findById")),
                @Result(column="gradeId",property="grade",one=@One(select="com.newbeedaly.mappers.GradeMapper.findById"))
            }
    )
    public Student selectStudentWithAddressAndGrade(int id);
}
package com.newbeedaly.mappers;

import org.apache.ibatis.annotations.Many;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

import com.newbeedaly.model.Grade;

public interface GradeMapper {

    @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.newbeedaly.mappers.StudentMapper.selectStudentByGradeId"))
            }
    )
    public Grade findById(Integer id);

}
package com.newbeedaly.mappers;

import org.apache.ibatis.annotations.Select;

import com.newbeedaly.model.Address;

public interface AddressMapper {

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

}

6.编写测试类

package com.newbeedaly.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.newbeedaly.mappers.StudentMapper;
import com.newbeedaly.model.Student;
import com.newbeedaly.util.SqlSessionFactoryUtil;

public class StudentTest {

    private static Logger logger=Logger.getLogger(StudentTest.class);
    private SqlSession sqlSession=null;
    private StudentMapper studentMapper=null;

    /**
     * 测试方法前调用
     * @throws Exception
     */
    @Before
    public void setUp() throws Exception {
        sqlSession=SqlSessionFactoryUtil.openSession();
        studentMapper=sqlSession.getMapper(StudentMapper.class);
    }

    /**
     * 测试方法后调用
     * @throws Exception
     */
    @After
    public void tearDown() throws Exception {
        sqlSession.close();
    }

    @Test
    public void testInsert() {
        logger.info("添加学生");
        Student student=new Student("琪琪",11);
        studentMapper.insertStudent(student);
        sqlSession.commit();
    }

    @Test
    public void testUpdate() {
        logger.info("更新学生");
        Student student=new Student(6,"琪琪2",12);
        studentMapper.updateStudent(student);
        sqlSession.commit();
    }

    @Test
    public void testDelete() {
        logger.info("删除学生");
        studentMapper.deleteStudent(6);
        sqlSession.commit();
    }

    @Test
    public void testGetById() {
        logger.info("通过ID查找学生");
        Student student=studentMapper.getStudentById(1);
        System.out.println(student);
    }

    @Test
    public void testFindStudents() {
        logger.info("查找所有学生");
        List<Student> studentList=studentMapper.findStudents();
        for(Student student:studentList){
            System.out.println(student);
        }
    }

}
package com.newbeedaly.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.newbeedaly.mappers.GradeMapper;
import com.newbeedaly.mappers.StudentMapper;
import com.newbeedaly.model.Grade;
import com.newbeedaly.model.Student;
import com.newbeedaly.util.SqlSessionFactoryUtil;

public class StudentTest2 {

    private static Logger logger=Logger.getLogger(StudentTest2.class);
    private SqlSession sqlSession=null;
    private StudentMapper studentMapper=null;
    private GradeMapper gradeMapper=null;

    /**
     * 测试方法前调用
     * @throws Exception
     */
    @Before
    public void setUp() throws Exception {
        sqlSession=SqlSessionFactoryUtil.openSession();
        studentMapper=sqlSession.getMapper(StudentMapper.class);
        gradeMapper=sqlSession.getMapper(GradeMapper.class);
    }

    /**
     * 测试方法后调用
     * @throws Exception
     */
    @After
    public void tearDown() throws Exception {
        sqlSession.close();
    }

    @Test
    public void testSelectStudentWithAddress() {
        logger.info("查找学生(带地址)");
        Student student=studentMapper.selectStudentWithAddress(3);
        System.out.println(student);
    }

    @Test
    public void testSelectGradeWithStudents() {
        logger.info("查找年级(带学生)");
        Grade grade=gradeMapper.findById(2);
        System.out.println(grade);
        List<Student> studentList=grade.getStudents();
        for(Student student:studentList){
            System.out.println(student);
        }
    }

    @Test
    public void testSelectStudentWithAddressAndGrade() {
        logger.info("查找学生(带年级,带地址)");
        Student student=studentMapper.selectStudentWithAddressAndGrade(1);
        System.out.println(student);
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值