Unit08: Spring集成mybatis
Unit08: Spring集成mybatis
1. Spring集成mybatis
(1)方式一
step1. 导包。
spring-webmvc,mybatis,mybatis-spring,
ojdbc,dbcp,spring-jdbc,junit。
step2. 添加spring的配置文件。
注:集成之后,不再需要mybatis的配置文件了,之前的配置信息
用一个bean(SqlSessionFactoryBean)来代替。
step3.实体类。
step4.映射文件。
step5.Mapper映射器。
step6.配置MapperScannerConfigurer。
注:该bean负责调用SqlSession的getMapper方法,获得 符合Mapper映射器要求的对象。并且会将这些对象放到spring 容器里面(默认的id是首字母小写之后的接口名,比如Mapper 映射器名为EmpDAO,则默认的id是empDAO,也可以使用@Repository 来修改默认的id)。
注:如果只扫描特定的映射器,可以做如下两步。
step1.开发一个注解,比如@MyBatisRepository,并且,将
该注解添加到需要扫描的映射器上面。
注入annotationClass属性值。
代码:
src/main/java
annotations
package annotations; public @interface MyBatisRepository { }
MyBatisRepository.java
dao
package dao; import java.util.List;
import java.util.Map; import org.springframework.stereotype.Repository; import annotations.MyBatisRepository;
import entity.Employee;
import entity.Employee2; /**
* Mapper映射器
*
*/
@Repository("empDAO")
@MyBatisRepository
public interface EmployeeDAO {
public void save(Employee e);
public List<Employee> findAll();
public Employee findById(int id);
public void modify(Employee e);
public void delete(int id);
public Map findById2(int id);
public Employee2 findById3(int id);
}
EmployeeDAO.java
entity
package entity; public class Employee {
private Integer id;
private String name;
private Integer age; @Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", 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;
} }
Employee.java
package entity; public class Employee2 {
private Integer empNo;
private String ename;
private Integer age; @Override
public String toString() {
return "Employee2 [empNo=" + empNo + ", ename=" + ename + ", age=" + age + "]";
} public void setEmpNo(Integer empNo) {
this.empNo = empNo;
}
public void setEname(String ename) {
this.ename = ename;
}
public void setAge(Integer age) {
this.age = age;
} }
Employee2.java
<?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="dao.EmployeeDAO">
<!--
id:要求唯一
parameterType:参数类型,要写类的完整的名称。
-->
<insert id="save"
parameterType="entity.Employee">
INSERT INTO emp_czh
VALUES(emp_czh_seq.nextval,#{name},#{age})
</insert> <!--
resultType:返回类型,要写类的完整的名称。
-->
<select id="findAll"
resultType="entity.Employee">
SELECT * FROM emp_czh
</select> <select id="findById"
parameterType="int"
resultType="entity.Employee">
SELECT * FROM emp_czh
WHERE id = #{id1}
</select> <update id="modify"
parameterType="entity.Employee">
UPDATE emp_czh SET name = #{name},
age = #{age} WHERE id = #{id}
</update> <delete id="delete" parameterType="int">
DELETE FROM emp_czh WHERE id = #{id1}
</delete> <!-- 返回Map类型的结果 -->
<!--
map是java.util.Map的简写形式
-->
<select id="findById2" parameterType="int"
resultType="map">
SELECT * FROM emp_czh WHERE id = #{id1}
</select> <!--
resultMap告诉mybatis表的字段名
与实体类的属性名的对应关系。
(如果表的字段名与属性名相同,则不用写了)
-->
<resultMap type="entity.Employee2"
id="empResultMap">
<result property="empNo" column="id"/>
<result property="ename" column="name"/>
</resultMap> <select id="findById3" parameterType="int"
resultMap="empResultMap">
SELECT * FROM emp_czh WHERE id = #{id1}
</select>
</mapper>
EmpMapper.xml
src/mian/resources
# db connection parameters
# key=value
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@192.168.201.227:1521:orcl
user=openlab
pwd=open123
# datasource parameters
initSize=1
maxSize=1
db.properties
<?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:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">
<!-- 读取db.properties文件 -->
<util:properties id="db"
location="classpath:db.properties"/>
<!-- 配置连接池 -->
<bean id="ds"
class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName"
value="#{db.driver}" />
<property name="url"
value="#{db.url}" />
<property name="username"
value="#{db.user}" />
<property name="password"
value="#{db.pwd}" />
</bean>
<!-- 配置SqlSessionFactoryBean -->
<bean id="ssfb"
class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入连接池 -->
<property name="dataSource" ref="ds"/>
<!-- 注入映射文件的位置信息 -->
<property name="mapperLocations"
value="classpath:entity/*.xml"/>
</bean>
<!-- 配置MapperScannerConfigurer -->
<bean
class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入要扫描的包名 -->
<property name="basePackage"
value="dao"/>
<!-- 只扫描带有该注解的映射器 -->
<property name="annotationClass"
value="annotations.MyBatisRepository"/>
</bean>
</beans>
spring-mybatis.xml
src/test/java
test
package test; import java.util.List; import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import dao.EmployeeDAO;
import entity.Employee; public class TestCase {
private EmployeeDAO dao;
@Before
public void init(){
ApplicationContext ac =
new ClassPathXmlApplicationContext(
"spring-mybatis.xml");
dao = ac.getBean("empDAO",
EmployeeDAO.class);
}
@Test
public void test1(){
List<Employee> emps =
dao.findAll();
System.out.println(emps);
}
@Test
public void test2(){
Employee e = new Employee();
e.setName("Rod Johnson");
e.setAge(40);
dao.save(e);
}
}
TestCase.java
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.8</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>3.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc14</artifactId>
<version>10.2.0.4.0</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
pom.xml
(2)方式二
step1. 导包。
spring-webmvc,mybatis,mybatis-spring,
ojdbc,dbcp,spring-jdbc,junit。
step2. 添加spring的配置文件。
注:集成之后,不再需要mybatis的配置文件了,之前的配置信息
用一个bean(SqlSessionFactoryBean)来代替。
step3.实体类。
step4.映射文件。
step5.Mapper映射器。
step6.写映射器的实现类。
SqlSessionTemplate注入到实现类中,然后调用 SqlSessionTemplate的方法即可。
step7.配置SqlSessionTemplate。
代码:
src/main/java
annotations
package annotations; public @interface MyBatisRepository { }
MyBatisRepository.java
dao
package dao; import java.util.List;
import java.util.Map; import org.springframework.stereotype.Repository; import annotations.MyBatisRepository;
import entity.Employee;
import entity.Employee2; /**
* Mapper映射器
*
*/
public interface EmployeeDAO {
public void save(Employee e);
public List<Employee> findAll();
public Employee findById(int id);
public void modify(Employee e);
public void delete(int id);
public Map findById2(int id);
public Employee2 findById3(int id);
}
EmployeeDAO.java
package dao; import java.util.List;
import java.util.Map; import javax.annotation.Resource; import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Repository; import entity.Employee;
import entity.Employee2; @Repository("empDAO")
public class EmployeeDAOMybatisImpl implements
EmployeeDAO{ @Resource(name="sst")
private SqlSessionTemplate sst; public void save(Employee e) {
sst.insert("dao.EmployeeDAO.save",
e);
} public List<Employee> findAll() {
return sst.selectList(
"dao.EmployeeDAO.findAll");
} public Employee findById(int id) {
return sst.selectOne(
"dao.EmployeeDAO.findById", id);
} public void modify(Employee e) {
sst.update("dao.EmployeeDAO.modify",
e);
} public void delete(int id) {
sst.delete("dao.EmployeeDAO.delete",
id);
} public Map findById2(int id) {
return sst.selectOne(
"dao.EmployeeDAO.findById2", id);
} public Employee2 findById3(int id) {
return sst.selectOne(
"dao.EmployeeDAO.findById3", id);
} }
EmployeeDAOMybatisImpl.java
entity
package entity; public class Employee {
private Integer id;
private String name;
private Integer age; @Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", 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;
} }
Employee.java
package entity; public class Employee2 {
private Integer empNo;
private String ename;
private Integer age; @Override
public String toString() {
return "Employee2 [empNo=" + empNo + ", ename=" + ename + ", age=" + age + "]";
} public void setEmpNo(Integer empNo) {
this.empNo = empNo;
}
public void setEname(String ename) {
this.ename = ename;
}
public void setAge(Integer age) {
this.age = age;
} }
Employee2.java
<?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="dao.EmployeeDAO">
<!--
id:要求唯一
parameterType:参数类型,要写类的完整的名称。
-->
<insert id="save"
parameterType="entity.Employee">
INSERT INTO emp_czh
VALUES(emp_czh_seq.nextval,#{name},#{age})
</insert> <!--
resultType:返回类型,要写类的完整的名称。
-->
<select id="findAll"
resultType="entity.Employee">
SELECT * FROM emp_czh
</select> <select id="findById"
parameterType="int"
resultType="entity.Employee">
SELECT * FROM emp_czh
WHERE id = #{id1}
</select> <update id="modify"
parameterType="entity.Employee">
UPDATE emp_czh SET name = #{name},
age = #{age} WHERE id = #{id}
</update> <delete id="delete" parameterType="int">
DELETE FROM emp_czh WHERE id = #{id1}
</delete> <!-- 返回Map类型的结果 -->
<!--
map是java.util.Map的简写形式
-->
<select id="findById2" parameterType="int"
resultType="map">
SELECT * FROM emp_czh WHERE id = #{id1}
</select> <!--
resultMap告诉mybatis表的字段名
与实体类的属性名的对应关系。
(如果表的字段名与属性名相同,则不用写了)
-->
<resultMap type="entity.Employee2"
id="empResultMap">
<result property="empNo" column="id"/>
<result property="ename" column="name"/>
</resultMap> <select id="findById3" parameterType="int"
resultMap="empResultMap">
SELECT * FROM emp_czh WHERE id = #{id1}
</select>
</mapper>
EmpMapper.xml
src/main/resources
# db connection parameters
# key=value
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@192.168.201.227:1521:orcl
user=openlab
pwd=open123
# datasource parameters
initSize=1
maxSize=1
db.properties
<?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:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">
<!-- 读取db.properties文件 -->
<util:properties id="db"
location="classpath:db.properties"/>
<!-- 配置连接池 -->
<bean id="ds"
class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName"
value="#{db.driver}" />
<property name="url"
value="#{db.url}" />
<property name="username"
value="#{db.user}" />
<property name="password"
value="#{db.pwd}" />
</bean>
<!-- 配置SqlSessionFactoryBean -->
<bean id="ssfb"
class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入连接池 -->
<property name="dataSource" ref="ds"/>
<!-- 注入映射文件的位置信息 -->
<property name="mapperLocations"
value="classpath:entity/*.xml"/>
</bean>
<!-- 配置SqlSessionTemplate -->
<bean id="sst"
class="org.mybatis.spring.SqlSessionTemplate">
<!-- 注入SqlSessionFactoryBean -->
<constructor-arg index="0"
ref="ssfb"/>
</bean>
<!-- 配置组件扫描 -->
<context:component-scan
base-package="dao"/>
</beans>
spring-mybatis.xml
src/test/java
test
package test; import java.util.List; import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import dao.EmployeeDAO;
import entity.Employee; public class TestCase {
private EmployeeDAO dao;
@Before
public void init(){
ApplicationContext ac =
new ClassPathXmlApplicationContext(
"spring-mybatis.xml");
dao = ac.getBean("empDAO",
EmployeeDAO.class);
}
@Test
public void test1(){
List<Employee> emps =
dao.findAll();
System.out.println(emps);
} @Test
public void test2(){
Employee e = new Employee();
e.setName("Hello Kitty");
e.setAge(40);
dao.save(e);
}
}
TestCase.java
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.8</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>3.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc14</artifactId>
<version>10.2.0.4.0</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
pom.xml
Unit08: Spring集成mybatis的更多相关文章
- Spring集成MyBatis框架
Java在写数据库查询时,我接触过四种方式: 1.纯Java代码,引用对应的数据库驱动包,自己写连接与释放逻辑(可以用连接池) 这种模式实际上性能是非常不错的,但是使用起来并不是非常方便:一是要手工为 ...
- SSM框架开发web项目系列(五) Spring集成MyBatis
前言 在前面的MyBatis部分内容中,我们已经可以独立的基于MyBatis构建一个数据库访问层应用,但是在实际的项目开发中,我们的程序不会这么简单,层次也更加复杂,除了这里说到的持久层,还有业务逻辑 ...
- Spring集成MyBatis的使用-使用SqlSessionTemplate
Spring集成MyBatis的使用 Spring集成MyBatis,早期是使用SqlSessionTemplate,当时并没有用Mapper映射器,既然是早期,当然跟使用Mapper映射器是存在一些 ...
- Spring集成MyBatis的使用-使用Mapper映射器
Spring集成MyBatis使用 前面复习MyBatis时,发现在测试时,需要手动创建sqlSessionFactory,Spring将帮忙自动创建sqlSessionFactory,并且将自动扫描 ...
- Spring集成Mybatis,spring4.x整合Mybatis3.x
Spring集成Mybatis,spring4.x整合Mybatis3.x ============================== 蕃薯耀 2018年3月14日 http://www.cnblo ...
- spring集成mybatis配置多个数据源,通过aop自动切换
spring集成mybatis,配置多个数据源并自动切换. spring-mybatis.xml如下: <?xml version="1.0" encoding=" ...
- MyBatis从入门到精通(第9章):Spring集成MyBatis(下)
MyBatis从入门到精通(第9章):Spring集成MyBatis(下) springmvc执行流程原理 mybatis-spring 可以帮助我们将MyBatis代码无缝整合到Spring中.使 ...
- MyBatis从入门到精通(第9章):Spring集成MyBatis(中)
MyBatis从入门到精通(第9章):Spring集成MyBatis(中) 框架(Framework)是整个或部分系统的可重用设计,表现为一组抽象构件及构件实例间交互的方法.应该将应用自身的设计和具体 ...
- MyBatis从入门到精通(第9章):Spring集成MyBatis(上)
MyBatis从入门到精通(第9章):Spring集成MyBatis(上) Spring是一个为了解决企业级Web应用开发过程中面临的复杂性,而被创建的一个非常流行的轻量级框架. mybatis-sp ...
随机推荐
- yum 数据库报错与重构
[root@dhcp yum.repos.d]# cd /var/lib/rpm/ [root@dhcp rpm]# rm __db.* -rf[root@dhcp rpm]# rpm --rebui ...
- hdu3488
题解: 首先把每一个点拆到两边 然后做KM求最大 吧没一条边相反即可 代码: #include<cstdio> #include<cmath> #include<algo ...
- codis3.2安装配置中的一些问题
1.参考文档与参考资料问题 安装codis集群之前,我先在网上找资料,然后又到github的项目官方地址找,不得不说,相关的资料不好找,而且找到之后有些东西说的也不是很清楚.由于codis版本迭代的问 ...
- 使用LeakCanary进行内存泄漏追踪
LeakCanary使用 1.在build.gradle 中 dependencies { //添加 debugCompile 'com.squareup.leakcanary:lea ...
- jmeter测试FTP
1.下载并运行FTP服务器软件:Quick Easy FTP Server V4.0.0.exe 2.点击右上角的绿色按钮,开启服务器,直到中间的红色按钮亮起 3.在账户管理处可以管理账号信息(用户名 ...
- CSS 清除浮动 clear 属性
CSS 清除浮动 clear 属性用于设定元素哪一侧不允许有其他浮动元素(而并非取消元素的浮动). 可能的取值如下: 取值 说明 none 默认值,允许两侧都有浮动元素 left 左侧不允许有其他浮动 ...
- 运算符和typeof
算术运算符 例: var a =10; var b = "a"; var c = a-b; 那么c的值是NaN. 逻辑运算符:&&,|| 注意:如果是非布尔类型 ...
- OK335xS knob driver hacking
/************************************************************************* * OK335xS knob driver hac ...
- SQL查询执行步骤
1.总结 执行顺序 3.select ...聚合函数 from 表名 1.where ... 2.group by ... 4.having ... 5.order by ... 6.limit .. ...
- Linux 中断处理
HardIRQ 和 softirq : http://www.it165.net/os/html/201211/3766.html 博文:http://blog.csdn.net/yin262/art ...