Mybatis one-to-many(一对多)

Mybatis one-to-many(一对多)

CREATE TABLE `teacher` (
  `tid` int(11) NOT NULL AUTO_INCREMENT,
  `tname` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`tid`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;

 


CREATE TABLE `student` (
  `sid` int(11) NOT NULL AUTO_INCREMENT,
  `sname` varchar(100) DEFAULT NULL,
  `teacherid` int(11) DEFAULT NULL,
  PRIMARY KEY (`sid`),
  KEY `ftid` (`teacherid`),
  CONSTRAINT `ftid` FOREIGN KEY (`teacherid`) REFERENCES `teacher` (`tid`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;

 



package org.abin.lee.bean;

public class Student implements java.io.Serializable{
 
 private static final long serialVersionUID = 2664268794619785937L;
 private int sid;
 private String sname;
 private int teacherId;
 private Teacher teacher;
 
 public Student() {
 }

 public int getSid() {
  return sid;
 }

 public void setSid(int sid) {
  this.sid = sid;
 }

 public String getSname() {
  return sname;
 }

 public void setSname(String sname) {
  this.sname = sname;
 }

 public Teacher getTeacher() {
  return teacher;
 }

 public void setTeacher(Teacher teacher) {
  this.teacher = teacher;
 }

 public int getTeacherId() {
  return teacherId;
 }

 public void setTeacherId(int teacherId) {
  this.teacherId = teacherId;
 }
 
}





package org.abin.lee.bean;

import java.util.ArrayList;
import java.util.List;

public class Teacher implements java.io.Serializable{
 
 private static final long serialVersionUID = -7053173500969534203L;
 private int tid;
 private String tname;
 private List<Student> student=new ArrayList<Student>();
 
 public Teacher() {
 }
 
 public int getTid() {
  return tid;
 }
 public void setTid(int tid) {
  this.tid = tid;
 }
 public String getTname() {
  return tname;
 }
 public void setTname(String tname) {
  this.tname = tname;
 }

 public List<Student> getStudent() {
  return student;
 }

 public void setStudent(List<Student> student) {
  this.student = student;
 }

 
}





StudentMapper.xml(org.abin.lee.bean)
<?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="org.abin.lee.dao.StudentDao">
  <parameterMap type="Student" id="parameterStudentMap">
    <parameter property="sid"/>
    <parameter property="sname"/>
    <parameter property="teacherId"/>
  </parameterMap>
   
  <insert id="insertStudent"    parameterMap="parameterStudentMap">
    <selectKey    keyProperty="sid" resultType="int" order="AFTER">
      SELECT LAST_INSERT_ID() AS ID
    </selectKey>
    INSERT INTO student(sname,teacherId)
    VALUES(#{sname},#{teacherId})
  </insert>   
   
  <resultMap type="Student" id="StudentMap">
    <result property="sid" column="sid"/>
    <result property="sname" column="sname"/>
    <result property="teacherId" column="teacherId"/>
    <association property="teacher" javaType="Teacher" column="teacherId" select="org.abin.lee.dao.TeacherDao.getTeacher"/>
  </resultMap>   
  <select id="getStudent" resultMap="StudentMap" parameterType="int">
    SELECT * FROM student
    WHERE sid=#{sid}
  </select>
   
  <select id="getStudentById" resultMap="StudentMap" parameterType="int">
    SELECT * FROM student
    WHERE teacherId=#{teacherId}
  </select>
 
 
</mapper>  



TeacherMapper.xml(org.abin.lee.bean)

<?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="org.abin.lee.dao.TeacherDao">
  <parameterMap type="Teacher" id="parameterTeacherMap">
    <parameter property="tid"/>
    <parameter property="tname"/>
  </parameterMap>

  <insert id="insertTeacher" parameterMap="parameterTeacherMap">
    <selectKey    keyProperty="tid" resultType="int" order="AFTER">
      SELECT @@IDENTITY AS ID
    </selectKey>
    INSERT INTO teacher(tname)
    VALUES(#{tname})
  </insert>       
   
  <resultMap type="Teacher" id="resultTeacherMap">
    <result property="tid" column="tid"/>
    <result property="tname" column="tname"/>
    <collection property="student" column="sid" select="org.abin.lee.dao.StudentDao.getStudentById"/>
  </resultMap>
   
  <select id="getTeacher" resultMap="resultTeacherMap" parameterType="int">
    SELECT *
    FROM teacher
    WHERE tid=#{id}
  </select>         
  
</mapper>



package org.abin.lee.dao;

import java.util.List;

import org.abin.lee.bean.Student;

public interface StudentDao {
 void insertStudent(Student student);
 List<Student> getStudent(int id);
 List<Student> getStudentById(int teacherId);
}




package org.abin.lee.dao;

import org.abin.lee.bean.Teacher;

public interface TeacherDao {
 void insertTeacher(Teacher teacher);
 Teacher getTeacher(int id);
}





package org.abin.lee.dao.impl;

import java.util.List;

import org.abin.lee.bean.Student;
import org.abin.lee.dao.StudentDao;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class StudentDaoImpl extends HibernateDaoSupport implements StudentDao{

 public List<Student> getStudent(int id) {
  List<Student> list=null;
  String hql="select o from Student o where o.id="+id;
  try {
   list=(List<Student>)this.getHibernateTemplate().find(hql);
  } catch (Exception e) {
   e.printStackTrace();
  }
  return list;
 }

 public List<Student> getStudentById(int teacherId) {
  List<Student> list=null;
  String hql="select o from Student o where o.id="+teacherId;
  try {
   list=(List<Student>)this.getHibernateTemplate().find(hql);
  } catch (Exception e) {
   e.printStackTrace();
  }
  return list;
 }

 public void insertStudent(Student student) {
  try {
   this.getHibernateTemplate().save(student);
  } catch (Exception e) {
   e.printStackTrace();
  }
  
 }

}





package org.abin.lee.dao.impl;

import org.abin.lee.bean.Teacher;
import org.abin.lee.dao.TeacherDao;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class TeacherDaoImpl extends HibernateDaoSupport implements TeacherDao{

 public Teacher getTeacher(int id) {
  Teacher teacher=null;
  String hql="select o from Teacher o where o.id="+id;
  try {
   teacher=(Teacher)this.getHibernateTemplate().find(hql);
   this.getHibernateTemplate().flush();
  } catch (Exception e) {
   e.printStackTrace();
  }
  return teacher;
 }

 public void insertTeacher(Teacher teacher) {
  try {
   this.getHibernateTemplate().save(teacher);
   this.getHibernateTemplate().flush();
   
  } catch (Exception e) {
   e.printStackTrace();
  }
  
 }

}





package org.abin.lee.service;

import java.util.List;

import org.abin.lee.bean.Student;

public interface StudentService {
 
 void insertStudent(Student student);
 List<Student> getStudent(int id);
 List<Student> getStudentById(int teacherId);
 
}




package org.abin.lee.service;

import org.abin.lee.bean.Teacher;

public interface TeacherService {
 
 void insertTeacher(Teacher teacher);
 Teacher getTeacher(int id);
}




package org.abin.lee.service.impl;

import java.util.List;

import org.abin.lee.bean.Student;
import org.abin.lee.dao.StudentDao;
import org.abin.lee.service.StudentService;

public class StudentServiceImpl implements StudentService{
 private StudentDao studentDao;
 
 public List<Student> getStudent(int id) {
  return this.studentDao.getStudent(id);
 }

 public List<Student> getStudentById(int teacherId) {
  
  return this.studentDao.getStudentById(teacherId);
 }

 public void insertStudent(Student student) {
  this.studentDao.insertStudent(student);
  
 }

 public StudentDao getStudentDao() {
  return studentDao;
 }

 public void setStudentDao(StudentDao studentDao) {
  this.studentDao = studentDao;
 }

}




package org.abin.lee.service.impl;

import org.abin.lee.bean.Teacher;
import org.abin.lee.dao.TeacherDao;
import org.abin.lee.service.TeacherService;

public class TeacherServiceImpl implements TeacherService{
 private TeacherDao teacherDao;
 
 public Teacher getTeacher(int id) {
  
  return this.teacherDao.getTeacher(id);
 }

 public void insertTeacher(Teacher teacher) {
  this.teacherDao.insertTeacher(teacher);
  
 }

 public TeacherDao getTeacherDao() {
  return teacherDao;
 }

 public void setTeacherDao(TeacherDao teacherDao) {
  this.teacherDao = teacherDao;
 }
 
}





applicationContext-mapper.xml(org.abin.lee.spring)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xsi:schemaLocation="
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

   <!--创建数据映射器,数据映射器必须为接口-->
 <bean id="studentDao"
  class="org.mybatis.spring.mapper.MapperFactoryBean">
  <property name="sqlSessionFactory" ref="sqlSessionFactory" />
  <property name="mapperInterface"
   value="org.abin.lee.dao.StudentDao" />
 </bean>
 
 <bean id="teacherDao"
  class="org.mybatis.spring.mapper.MapperFactoryBean">
  <property name="sqlSessionFactory" ref="sqlSessionFactory" />
  <property name="mapperInterface"
   value="org.abin.lee.dao.TeacherDao" />
 </bean>


</beans>






applicationContext-resource.xml(org.abin.lee.spring)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xsi:schemaLocation="
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">


 <!--配置数据源 -->
 <bean id="dataSource"
  class="org.apache.commons.dbcp.BasicDataSource"
  destroy-method="close">
  <property name="driverClassName"
   value="com.mysql.jdbc.Driver">
  </property>
  <property name="url" value="jdbc:mysql://localhost:3306/abin"></property>
  <property name="username" value="root"></property>
  <property name="password" value=""></property>
  <property name="maxActive" value="100"></property>
  <property name="maxIdle" value="30"></property>
  <property name="maxWait" value="500"></property>
  <property name="defaultAutoCommit" value="true"></property>
 </bean>

    <!-- 创建SqlSessionFactory,同时指定数据源-->
 <bean id="sqlSessionFactory"
  class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
  <property name="configLocation"
   value="classpath:mybatis-config.xml" />
 </bean>

 <bean id="transactionManager"
  class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  <property name="dataSource" ref="dataSource" />
 </bean>


</beans>







applicationContext-service.xml(org.abin.lee.spring)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xsi:schemaLocation="
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

 <bean id="studentService"
  class="org.abin.lee.service.impl.StudentServiceImpl">
  <property name="studentDao">
   <ref bean="studentDao" />
  </property>
 </bean>

 <bean id="teacherService"
  class="org.abin.lee.service.impl.TeacherServiceImpl">
  <property name="teacherDao">
   <ref bean="teacherDao" />
  </property>
 </bean>

</beans>





mybatis-config.xml(直接放在src目录下面)

<?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>

 <settings>
  <!-- changes from the defaults for testing -->
  <setting name="cacheEnabled" value="false" />
  <setting name="useGeneratedKeys" value="true" />
  <setting name="defaultExecutorType" value="REUSE" />
 </settings>


 <typeAliases>
  <typeAlias type="org.abin.lee.bean.Student" alias="Student" />
  <typeAlias type="org.abin.lee.bean.Teacher" alias="Teacher" />
 </typeAliases>

 

 <mappers>
  <mapper resource="org/abin/lee/bean/StudentMapper.xml" />
  <mapper resource="org/abin/lee/bean/TeacherMapper.xml" />
 </mappers>


</configuration>





log4j.properties(直接放在src目录下面)

log4j.rootLogger=INFO,stdout,logfile
//log4j.rootLogger=INFO,logfile

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [%c]-[%p] %m%n

log4j.appender.logfile=org.apache.log4j.RollingFileAppender
log4j.appender.logfile.File=../logs/contacts.log
log4j.appender.logfile.MaxFileSize=2048KB
log4j.appender.logfile.MaxBackupIndex=5
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss} (%c) - %m%n

 





下面是测试代码:

package org.abin.lee.test;

import junit.framework.TestCase;

import org.abin.lee.bean.Student;
import org.abin.lee.bean.Teacher;
import org.abin.lee.service.StudentService;
import org.abin.lee.service.TeacherService;
import org.junit.Before;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestStudent extends TestCase{
 
 private StudentService studentService;
 private TeacherService teacherService;
 private ApplicationContext context;
 @Before
 public void setUp(){
  String[] xml=new String[3];
  xml[0]="org/abin/lee/spring/applicationContext-resource.xml";
  xml[1]="org/abin/lee/spring/applicationContext-mapper.xml";
  xml[2]="org/abin/lee/spring/applicationContext-service.xml";
  context=new ClassPathXmlApplicationContext(xml);
 }
 
 public void testStudent(){
  Teacher tea=new Teacher();
  tea.setTname("steven");
  teacherService=(TeacherService)context.getBean("teacherService");
  this.teacherService.insertTeacher(tea);
  Student stu=new Student();
  stu.setSname("john");
  stu.setTeacherId(tea.getTid());
  studentService=(StudentService)context.getBean("studentService");
  this.studentService.insertStudent(stu);
 }
 public StudentService getStudentService() {
  return studentService;
 }
 public void setStudentService(StudentService studentService) {
  this.studentService = studentService;
 }
 public TeacherService getTeacherService() {
  return teacherService;
 }
 public void setTeacherService(TeacherService teacherService) {
  this.teacherService = teacherService;
 }
 
}






package org.abin.lee.test;

import java.util.List;

import junit.framework.TestCase;

import org.abin.lee.bean.Student;
import org.abin.lee.bean.Teacher;
import org.abin.lee.service.StudentService;
import org.abin.lee.service.TeacherService;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestFind extends TestCase{
 private StudentService studentService;
 private TeacherService teacherService;
 private ApplicationContext context;
 @Before
 public void setUp(){
  String[] xml=new String[3];
  xml[0]="org/abin/lee/spring/applicationContext-resource.xml";
  xml[1]="org/abin/lee/spring/applicationContext-mapper.xml";
  xml[2]="org/abin/lee/spring/applicationContext-service.xml";
  context=new ClassPathXmlApplicationContext(xml);
 }
 @Test
 public void testFind(){
  teacherService=(TeacherService)context.getBean("teacherService");
  studentService=(StudentService)context.getBean("studentService");
  List<Student> list=this.studentService.getStudentById(4);
  Student stu=new Student();
  Teacher tea=new Teacher();
  for(int i=0;i<list.size();i++){
   System.out.println("666");
   stu=list.get(i);
   System.out.println("sid="+stu.getSid()+",sname="+stu.getSname()+",teacherid="+stu.getTeacherId());
   tea=stu.getTeacher();
   System.out.println("tid="+tea.getTid()+",tname="+tea.getTname());
  }
 }
 public StudentService getStudentService() {
  return studentService;
 }
 public void setStudentService(StudentService studentService) {
  this.studentService = studentService;
 }
 public TeacherService getTeacherService() {
  return teacherService;
 }
 public void setTeacherService(TeacherService teacherService) {
  this.teacherService = teacherService;
 }
 
}


你可能感兴趣的:(Mybatis one-to-many(一对多))