转载自:http://my.oschina.net/huangcongmin12/blog/83731

mybatis整合spring 之  基于接口映射的多对一关系。

项目用到俩个表,即student表和school表。表结构如下:

school表:

student表:

项目结构如下:

1)applicationContext.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<?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:p="http://www.springframework.org/schema/p"
    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/context
       http://www.springframework.org/schema/context/spring-context-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/aop
       http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
     
    <!-- 加载JDBC配置文件 -->
    <context:property-placeholder location="classpath:jdbc.properties" />
     
    <!-- 扫描类包,将标注Spring注解的类自动转化Bean,同时完成Bean的注入 -->
    <context:component-scan base-package="com.springbatis.dao" />
    <context:component-scan base-package="com.springbatis.service" />
     
    <!-- 配置数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass">
            <value>${jdbc.driverClassName}</value>
        </property>
        <property name="jdbcUrl">
            <value>${jdbc.url}</value>
        </property>
        <property name="user">
            <value>${jdbc.username}</value>
        </property>
        <property name="password">
            <value>${jdbc.password}</value>
        </property>
        <property name="minPoolSize">
            <value>8</value>
        </property>
        <property name="maxPoolSize">
            <value>200</value>
        </property>
        <property name="initialPoolSize">
            <value>10</value>
        </property>
        <property name="maxIdleTime">
            <value>60</value>
        </property>
        <property name="acquireIncrement">
            <value>5</value>
        </property>
        <property name="maxStatements">
            <value>10</value>
        </property>
        <property name="idleConnectionTestPeriod">
            <value>60</value>
        </property>
        <property name="acquireRetryAttempts">
            <value>30</value>
        </property>
        <property name="breakAfterAcquireFailure">
            <value>true</value>
        </property>
        <property name="testConnectionOnCheckout">
            <value>false</value>
        </property>
    </bean>
 
    <!-- 创建SqlSessionFactory,同时指定数据源 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 指定sqlMapConfig总配置文件 -->
        <property name="configLocation" value="classpath:mybatis-configuration.xml"/>
        <property name="dataSource" ref="dataSource" />
    </bean>
     
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.springbatis.dao" />
    </bean>
         
    <!-- 事务管理  -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
     
    <!-- 使用注解控制事务 -->
    <tx:annotation-driven />
     
</beans>

2)mybatis-configuration.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?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>
     
    <!-- 别名 -->
    <typeAliases>
        <typeAlias alias="School" type="com.springbatis.domain.School"/>
        <typeAlias alias="Student" type="com.springbatis.domain.Student"/>
    </typeAliases>
     
    <!-- ORM映射文件 -->
    <mappers>
        <mapper resource="com/springbatis/domain/SchoolMapper.xml" />
        <mapper resource="com/springbatis/domain/StudentMapper.xml" />
    </mappers>
     
     
</configuration>

3)School Entity

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.springbatis.domain;
 
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
 
@SuppressWarnings("serial")
public class School implements Serializable {
     
    private int id;
    private String schoolNumber;
    private String schoolName;
    private List<Student> students = new ArrayList<Student>();
     
    public School(){
    }
 
    public int getId() {
        return id;
    }
 
    public void setId(int id) {
        this.id = id;
    }
 
    public String getSchoolNumber() {
        return schoolNumber;
    }
 
    public void setSchoolNumber(String schoolNumber) {
        this.schoolNumber = schoolNumber;
    }
 
    public String getSchoolName() {
        return schoolName;
    }
 
    public void setSchoolName(String schoolName) {
        this.schoolName = schoolName;
    }
 
    public List<Student> getStudents() {
        return students;
    }
 
    public void setStudents(List<Student> students) {
        this.students = students;
    }  
 
}

4)Student Entity

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.springbatis.domain;
 
import java.io.Serializable;
 
@SuppressWarnings("serial")
public class Student implements Serializable {
     
    private int id;
    private String studentNumber;
    private String studentName;
    private String sex;
    private School school;
     
    public Student(){
    }
 
    public int getId() {
        return id;
    }
 
    public void setId(int id) {
        this.id = id;
    }
 
    public String getStudentNumber() {
        return studentNumber;
    }
 
    public void setStudentNumber(String studentNumber) {
        this.studentNumber = studentNumber;
    }
 
    public String getStudentName() {
        return studentName;
    }
 
    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }
 
    public String getSex() {
        return sex;
    }
 
    public void setSex(String sex) {
        this.sex = sex;
    }
 
    public School getSchool() {
        return school;
    }
 
    public void setSchool(School school) {
        this.school = school;
    }
     
}

5)SchoolMapper.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper    
PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"    
"http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">    
    
<mapper namespace="com.springbatis.dao.SchoolMybatisDao">
 
    <!-- 一对多映射 -->
    <resultMap id="schoolResult" type="School">
        <id property="id" column="school_id" />
        <result property="schoolNumber" column="school_number"/>
        <result property="schoolName" column="school_name"/>
        <collection property="students" ofType="Student">
            <id property="id" column="student_id"/>
            <result property="studentNumber" column="student_number"/>
            <result property="studentName" column="student_name"/>
            <result property="sex" column="student_sex"/>
        </collection>
    </resultMap>
     
    <select id="loadSchoolWithStudent" parameterType="int" resultMap="schoolResult">
        select
            sch.id                  as  school_id,
            sch.schoolNumber        as  school_number,
            sch.schoolName          as  school_name,
            stu.id                  as  student_id,
            stu.studentNumber       as  student_number,
            stu.studentName         as  student_name,
            stu.sex                 as  student_sex
        from  school sch
        left outer join student stu on sch.id=stu.school_id
        where sch.id=#{school_id}
    </select>
     
</mapper

6)StudentMapper.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper    
PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"    
"http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">    
 
<mapper namespace="com.springbatis.dao.StudentMybatisDao">
     
    <!-- 多对一映射 -->
    <resultMap id="studentResult" type="Student" >
        <id property="id" column="student_id"/>
        <result property="studentNumber" column="student_number"/>
        <result property="studentName" column="student_name"/>
        <result property="sex" column="student_sex"/>
        <association property="school" javaType="School">
            <id property="id" column="school_id"/>
            <result property="schoolNumber" column="school_number"/>
            <result property="schoolName" column="school_name"/>
       </association>
    </resultMap>
     
    <select id="loadStudentWithSchool" parameterType="int" resultMap="studentResult">
        select
            stu.id                  as  student_id,
            stu.studentNumber       as  student_number,
            stu.studentName         as  student_name,
            stu.sex                 as  student_sex,
            sch.id                  as  school_id,
            sch.schoolNumber        as  school_number,
            sch.schoolName          as  school_name
        from student stu
        left outer join school sch on sch.id=stu.school_id
        where stu.id=#{student_id}
    </select>
     
</mapper>

7)SchoolMybatisDao Interface

1
2
3
4
5
6
7
8
9
10
11
12
package com.springbatis.dao;
 
import org.springframework.stereotype.Repository;
 
import com.springbatis.domain.School;
 
@Repository
public interface SchoolMybatisDao {
     
    School loadSchoolWithStudent(int school_id);
     
}

8)StudentMybatisDao Interface

1
2
3
4
5
6
7
8
9
10
11
12
package com.springbatis.dao;
 
import org.springframework.stereotype.Repository;
 
import com.springbatis.domain.Student;
 
@Repository
public interface StudentMybatisDao {
 
    Student loadStudentWithSchool(int student_id);
     
}

9)SchoolService Interface

1
2
3
4
5
6
7
8
9
10
11
12
package com.springbatis.service;
 
import org.springframework.stereotype.Repository;
 
import com.springbatis.domain.School;
 
@Repository
public interface SchoolService {
     
    public School loadSchoolWithStudent(int school_id);
     
}

10)StudentServiec Interface

1
2
3
4
5
6
7
8
9
package com.springbatis.service;
 
import com.springbatis.domain.Student;
 
public interface StudentService {
     
    public Student loadStudentWithSchool(int student_id);
     
}

11)SchoolService Implement

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.springbatis.service.implement;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import com.springbatis.dao.SchoolMybatisDao;
import com.springbatis.domain.School;
import com.springbatis.service.SchoolService;
 
@Service
@Transactional
public class SchoolServiceImpl implements SchoolService {
     
    @Autowired
    private SchoolMybatisDao schoolDao;
 
    @Override
    public School loadSchoolWithStudent(int school_id) {
        return schoolDao.loadSchoolWithStudent(school_id);
    }
 
}

12)StudentService Implement

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.springbatis.service.implement;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import com.springbatis.dao.StudentMybatisDao;
import com.springbatis.domain.Student;
import com.springbatis.service.StudentService;
 
@Service
@Transactional
public class StudentServiceImpl implements StudentService {
 
    @Autowired
    private StudentMybatisDao studentDao;
     
    @Override
    public Student loadStudentWithSchool(int student_id) {
        return studentDao.loadStudentWithSchool(student_id);
    }
 
}

13)test/StudentServiceTest

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package com.springbatis.service;
 
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 
import com.springbatis.domain.Student;
 
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="/applicationContext.xml")
public class StudentServiceTest {
     
    @Autowired
    private StudentService studentService;
     
    @Test
    public void testLoadStudentWithSchool(){
        Student stu = studentService.loadStudentWithSchool(2);
        if(stu!=null){
            System.out.println("=====》studentId:"+stu.getId()+"   studentNumber:"+stu.getStudentNumber()+"  studentName:"+stu.getStudentName()+"   sex:"+stu.getSex());
            System.out.println("=====》schoolId:"+stu.getSchool().getId()+"  schoolNumber:"+stu.getSchool().getSchoolNumber()+"  schoolName:"+stu.getSchool().getSchoolName());
        }
        else{
            System.out.println("id不存在!!");
        }
    }
}

14)test/SchoolServiceTest

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.springbatis.service;
 
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 
import com.springbatis.domain.School;
import com.springbatis.domain.Student;
 
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="/applicationContext.xml")
public class SchoolServiceTest {
     
    @Autowired
    private SchoolService schoolService;
     
    @Test
    public void testLoadSchoolWithStudent(){
        School school = schoolService.loadSchoolWithStudent(1);
        if(school!=null){
            System.out.println("=====》schoolId:"+school.getId()+"  schoolNumber:"+school.getSchoolNumber()+"  schoolName:"+school.getSchoolName());
            if(school.getStudents().size()>0){
                for(Student stu : school.getStudents()){
                    System.out.println("=====》studentId:"+stu.getId()+"   studentNumber:"+stu.getStudentNumber()+"  studentName:"+stu.getStudentName()+"   sex:"+stu.getSex());
                }
            }else{
                System.out.println("无学生!");
            }
        }
        else{
            System.out.println("id不存在!!");
        }
    }
     
}

15)     执行testLoadSchoolWithStudent()

输出:

1
2
3
4
==》schoolId: 1   schoolNumber:100001  schoolName:清华大学
=====》studentId:1   studentNumber:1007300220  studentName:露西   sex:女
=====》studentId:2   studentNumber:1007300222  studentName:杰克   sex:男
=====》studentId:4   studentNumber:1007300225  studentName:露露   sex:女

mybatis整合spring 之 基于接口映射的多对一关系的更多相关文章

  1. JAVAEE——Mybatis第二天:输入和输出映射、动态sql、关联查询、Mybatis整合spring、Mybatis逆向工程

    1. 学习计划 1.输入映射和输出映射 a) 输入参数映射 b) 返回值映射 2.动态sql a) If标签 b) Where标签 c) Sql片段 d) Foreach标签 3.关联查询 a) 一对 ...

  2. (转)MyBatis框架的学习(六)——MyBatis整合Spring

    http://blog.csdn.net/yerenyuan_pku/article/details/71904315 本文将手把手教你如何使用MyBatis整合Spring,这儿,我本人使用的MyB ...

  3. Mybatis整合Spring -- typeAliasesPackage

    Mybatis整合Spring 根据官方的说法,在ibatis3,也就是Mybatis3问世之前,Spring3的开发工作就已经完成了,所以Spring3中还是没有对Mybatis3的支持. 因此由M ...

  4. 160330、Mybatis整合Spring

    转自csdn文章 http://haohaoxuexi.iteye.com/blog/1843309 Mybatis整合Spring 根据官方的说法,在ibatis3,也就是Mybatis3问世之前, ...

  5. 不需要怎么修改配置的Mybatis整合Spring要点

    首先对于Mybatis的主配置文件,只需要修改一处地方,将事务交给Spring管理,其它地方可以原封不动. <?xml version="1.0" encoding=&quo ...

  6. Mybatis整合spring(适合小白)

    目录 1.整合思路 2.整合需要的jar包 3.整合的步骤 4.Dao的开发的两种实现方式 6.Dao的开发的实现方式总结图 @ Mybatis整合spring其实就是SSM框架中SM的整合集成. 1 ...

  7. Mybatis整合spring详细教程(适合小白童鞋)

    目录 1.整合思路 2.整合需要的jar包 3.整合的步骤 4.Dao的开发的两种实现方式 6.Dao的开发的实现方式总结图 @ Mybatis整合spring其实就是SSM框架中SM的整合集成. 1 ...

  8. mybatis整合Spring编码

    mybatis整合Spring的核心代码 spring-dao.xml <?xml version="1.0" encoding="UTF-8"?> ...

  9. MyBatis整合Spring原理分析

    目录 MyBatis整合Spring原理分析 MapperScan的秘密 简单总结 假如不结合Spring框架,我们使用MyBatis时的一个典型使用方式如下: public class UserDa ...

随机推荐

  1. system.badimageformatexception 未能加载文件或程序集问题解决

    原因是项目CPU默认X86我的系统是X64,将目标平台改为 Any CPU就可以了; 解决方法:

  2. DEDECMS数据库执行原理、CMS代码层SQL注入防御思路

    我们在上一篇文章中学习了DEDECMS的模板标签.模板解析原理,以及通过对模板核心类的Hook Patch来对模板的解析流量的攻击模式检测,达到修复模板类代码执行漏洞的目的 http://www.cn ...

  3. TCP/IP详解 学习七

    静态选路的前提: 1)         网络比较小 2)         网络之间单点连接 3)         网络之间没有多余的路由 动态选路协议,用于路由器之间的通信,有以下几种: 1)     ...

  4. java判断list为空

    isEmpty()判断有没有元素而size()返回有几个元素 list.isEmpty()和list.size()==0 没有区别 list!=null跟!list.isEmpty()有什么区别? 这 ...

  5. schemaLocation value = 'xxxxxxxxxxxx' must have even number of URI's

    这是因为没有加上Spring的版本号,加上就行了,如: http://www.springframework.org/schema/beans/spring-beans.xsd -3.2.2 http ...

  6. Java Observer 观察者

    http://www.cnblogs.com/jaward/p/3277619.html 1.API 被观察者 java.util.Observable; public class Observabl ...

  7. jQuery操作滚动条

    一.窗体滚动条 1.获取窗体滚动条当前纵向和横向位置 var currentY=$(document.body).scrollTop();//窗体滚动条纵向位置 var currentX=$(docu ...

  8. 初学hibernate之缓存

    一.1.Session级别缓存属于一级缓存,持久化对象保存在Session一级缓存中(一级缓存引用持久化对象地址),只要session不关闭,一级缓存就存在,缓存中对象也不会被回收: Session会 ...

  9. WAF绕过小结

    WAF介绍 什么是WAF? Web应用防火墙是通过执行一系列针对HTTP/HTTPS的安全策略来专门为Web应用提供保护的一款产品. 基本/简单绕过方法: 1.注释符 http://www.site. ...

  10. php中mysql参数化查询

    $query = sprintf("SELECT * FROM Users where UserName='%s' and Password='%s'",mysql_real_es ...