Mybatis学习一对多和反向一对一
内容:查询年级带学生和查询学生带年级
1.编写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();
}
}
2.编写学生类、年级类和地址类
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 + "]";
}
}
3.编写配置文件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"/> -->
<properties>
<property name="jdbc.driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="jdbc.url" value="jdbc:mysql://localhost:3306/db_mybatis"/>
<property name="jdbc.username" value="root"/>
<property name="jdbc.password" value="123456"/>
</properties>
<!-- <typeAliases>
<typeAlias alias="Student" type="com.newbeedaly.model.Student"/>
</typeAliases> -->
<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>
<!-- <mapper resource="com/newbeedaly/mappers/StudentMapper.xml" /> -->
<!-- <mapper class="com.newbeedaly.mappers.StudentMapper"/> -->
<package name="com.newbeedaly.mappers"/>
</mappers>
</configuration>
4.编写GradeMapper.java和GradeMapper.xml以及学生和地址
package com.newbeedaly.mappers;
import com.newbeedaly.model.Grade;
public interface GradeMapper {
public Grade findById(Integer id);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.newbeedaly.mappers.GradeMapper">
<resultMap type="Grade" id="GradeResult">
<result property="id" column="id"/>
<result property="gradeName" column="gradeName"/>
<collection property="students" column="id" select="com.newbeedaly.mappers.StudentMapper.findByGradeId"></collection>
</resultMap>
<select id="findById" parameterType="Integer" resultMap="GradeResult">
select * from t_grade where id=#{id}
</select>
</mapper>
package com.newbeedaly.mappers;
import java.util.List;
import com.newbeedaly.model.Student;
public interface StudentMapper {
public int add(Student student);
public int update(Student student);
public int delete(Integer id);
public Student findById(Integer id);
public List<Student> find();
public Student findStudentWithAddress(Integer id);
public Student findByGradeId(Integer gradeId);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.newbeedaly.mappers.StudentMapper">
<!-- <resultMap type="Student" id="StudentResult">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="age" column="age"/>
<result property="address.id" column="addressId"/>
<result property="address.sheng" column="sheng"/>
<result property="address.shi" column="shi"/>
<result property="address.qu" column="qu"/>
</resultMap> -->
<!-- <resultMap type="Address" id="AddressResult">
<result property="id" column="id"/>
<result property="sheng" column="sheng"/>
<result property="shi" column="shi"/>
<result property="qu" column="qu"/>
</resultMap>
<resultMap type="Student" id="StudentResult">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="age" column="age"/>
<association property="address" resultMap="AddressResult"/>
</resultMap> -->
<!-- <resultMap type="Student" id="StudentResult">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="age" column="age"/>
<association property="address" javaType="Address">
<result property="id" column="id"/>
<result property="sheng" column="sheng"/>
<result property="shi" column="shi"/>
<result property="qu" column="qu"/>
</association>
</resultMap> -->
<resultMap type="Student" id="StudentResult">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="age" column="age"/>
<association property="address" column="addressId" select="com.newbeedaly.mappers.AddressMapper.findById"></association>
<association property="grade" column="gradeId" select="com.newbeedaly.mappers.GradeMapper.findById"></association>
</resultMap>
<select id="findStudentWithAddress" resultMap="StudentResult" parameterType="Integer">
select * from t_student t1,t_address t2 where t1.addressId=t2.id and t1.id=#{id}
</select>
<select id="findByGradeId" resultMap="StudentResult" parameterType="Integer">
select * from t_student where gradeId=#{gradeId}
</select>
<insert id="add" parameterType="Student" >
insert into t_student values(null,#{name},#{age})
</insert>
<update id="update" parameterType="Student">
update t_student set name=#{name},age=#{age} where id=#{id}
</update>
<delete id="delete" parameterType="Integer">
delete from t_student where id=#{id}
</delete>
<select id="findById" parameterType="Integer" resultType="Student">
select * from t_student where id=#{id}
</select>
<select id="find" resultMap="StudentResult">
select * from t_student
</select>
</mapper>
package com.newbeedaly.mappers;
import com.newbeedaly.model.Address;
public interface AddressMapper {
public Address findById(Integer id);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.newbeedaly.mappers.AddressMapper">
<resultMap type="Address" id="AddressResult">
<result property="id" column="id"/>
<result property="sheng" column="sheng"/>
<result property="shi" column="shi"/>
<result property="qu" column="qu"/>
</resultMap>
<select id="findById" parameterType="Integer" resultType="Address">
select * from t_address where id=#{id}
</select>
</mapper>
5.编写测试类
package com.newbeedaly.service;
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.model.Grade;
import com.newbeedaly.util.SqlSessionFactoryUtil;
public class GradeTest {
private static Logger logger=Logger.getLogger(StudentTest.class);
private SqlSession sqlSession=null;
private GradeMapper gradeMapper=null;
/**
* 测试方法前调用
* @throws Exception
*/
@Before
public void setUp() throws Exception {
sqlSession=SqlSessionFactoryUtil.openSession();
gradeMapper=sqlSession.getMapper(GradeMapper.class);
}
/**
* 测试方法后调用
* @throws Exception
*/
@After
public void tearDown() throws Exception {
sqlSession.close();
}
@Test
public void testFindGradeWithStudents() {
logger.info("查询年级(带学生)");
Grade grade=gradeMapper.findById(1);
System.out.println(grade);
}
}
package com.newbeedaly.service;
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 StudentTest3 {
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 testFindStudentWithAddress() {
logger.info("查询学生(带地址)");
Student student=studentMapper.findStudentWithAddress(3);
System.out.println(student);
}
@Test
public void testFindStudentWithGrade(){
logger.info("查询学生(带年级)");
Student student=studentMapper.findStudentWithAddress(1);
System.out.println(student);
}
}
package com.newbeedaly.service;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
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);
public static void main(String[] args) {
SqlSession sqlSession=SqlSessionFactoryUtil.openSession();
StudentMapper studentMapper=sqlSession.getMapper(StudentMapper.class);
Student student=new Student("李四",11);
int result=studentMapper.add(student);
sqlSession.commit();
if(result>0){
logger.info("添加成功!");
}
}
}
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 StudentTest2 {
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 testAdd() {
logger.info("添加学生");
Student student=new Student("王五",12);
studentMapper.add(student);
sqlSession.commit();
}
@Test
public void testUpdate(){
logger.info("修改学生");
Student student=new Student(8,"王五2",13);
studentMapper.update(student);
sqlSession.commit();
}
@Test
public void testDelete(){
logger.info("删除学生");
studentMapper.delete(8);
sqlSession.commit();
}
@Test
public void testFindById(){
logger.info("通过ID查找学生");
Student student=studentMapper.findById(1);
System.out.println(student);
}
@Test
public void testFind(){
logger.info("查找所有学生");
List<Student> studentList=studentMapper.find();
for(Student s:studentList){
System.out.println(s);
}
}
}