作为Bean容器,Spring框架提供了IoC机制,可以接管所有组件的创建工作并进行依赖管理,因而整合的主要工作就是把MyBatis框架使用中涉及的核心组件配置带Spring容器中,交给Spring来创建和管理。
具体来说:业务逻辑对象依赖基于MyBatis技术实现的DAO对象,核心是获取SqlSession实例。要获得SqlSession实例,则需要依赖SqlSessionFactory实例。而SqlSessionFactory是SqlSessionFactoryBuilder依赖MyBatis配置文件中的数据源、SQL映射文件等信息来创建的。
针对上述依赖关系,以上流程移交给Spring,发挥Spring框架Bean容器的作用,接管组件的创建工作,管理组件的生命周期,并对组件之间的依赖关系进行解耦合管理。
这里以Web项目为例实现两张表的增删改查 两张表分别是Emp(eid,ename,epwd,money,did)表和Dept表(did,dname)
1、 在项目中加入相关jar包,包括Spring的5个核心jar包、MyBatis和Spring的整合资源包(mybatis-spring-1.3.0.jar)、Spring的数据源支持(spring-jdbc-4.0.0.RELEASE.jar)以及事务支持(spring-tx-4.0.0.RELEASE.jar)包、数据源,这里以c3p0为例的相关jar包(c3p0-0.9.5.2.jar 、mchange-commons-java-0.2.11.jar)以及Mybatis和连接数据库的相关jar包等等。
2、 创建实体类:
package com.xyj.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Emp {
private int eid;
private String ename;
private String epwd;
private double money;
private Dept dept;
public Emp(int eid, String ename, String epwd, double money) {
this.eid = eid;
this.ename = ename;
this.epwd = epwd;
this.money = money;
}
public Emp(String ename, String epwd, double money) {
super();
this.ename = ename;
this.epwd = epwd;
this.money = money;
}
}
package com.xyj.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Dept {
private int did;
private String dname;
public Dept(int did) {
super();
this.did = did;
}
}
3、 创建Dao接口
package com.xyj.dao;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.xyj.entity.Emp;
public interface EmpDao {
List<Emp> findAll();
int delete(@Param("eid")int id);
int insert(Emp emp);
int update(Emp emp);
Emp findById(@Param("eid")int eid);
}
package com.xyj.dao;
import org.apache.ibatis.annotations.Param;
import com.xyj.entity.Dept;
public interface DeptDao {
Dept findById(@Param("did")int did);
}
4、 创建MyBatis的Sql映射文件:
<?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.xyj.dao.EmpDao">
<select id="findAll" resultMap="empmap">
select * from emp
</select>
<resultMap type="Emp" id="empmap">
<id column="eid" property="eid"/>
<result column="ename" property="ename"/>
<result column="epwd" property="epwd"/>
<result column="money" property="money"/>
<association property="dept" column="did" select="com.xyj.dao.DeptDao.findById"></association>
</resultMap>
<select id="findById" resultMap="empmap">
select * from emp where eid=#{eid}
</select>
<delete id="delete">
delete from emp where eid=#{eid}
</delete>
<insert id="insert">
insert into emp values(default,#{ename},#{epwd},#{money},1)
</insert>
<update id="update">
update emp set ename=#{ename},epwd=#{epwd},money=#{money} where eid=#{eid}
</update>
</mapper>
<?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.xyj.dao.DeptDao">
<select id="findById" resultType="Dept">
select * from dept where did=#{did}
</select>
</mapper>
5、 实现Spring对MyBatis的整合,编写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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- 自定义扫描包中的注解 -->
<context:component-scan base-package="com.xyj"></context:component-scan>
<!-- 配置数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql:///empdemo0821"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
</bean>
<!-- 2、创建会话工厂SqlSessionFactoryBean -->
<bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 引用数据源组件 -->
<property name="dataSource" ref="dataSource"></property>
<!-- 设置别名 -->
<property name="typeAliasesPackage" value="com.xyj.entity"></property>
<!-- Sql映射文件的路径 -->
<property name="mapperLocations" value="classpath*:mapper/*Mapper.xml"></property>
</bean>
<!-- 3、构建自动映射关系 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 指定会话工厂 -->
<property name="sqlSessionFactoryBeanName" value="SqlSessionFactory"></property>
<!-- 指定自动扫描接口包 -->
<property name="basePackage" value="com.xyj.dao"></property>
</bean>
</beans>
6、 编写Service层:
package com.xyj.service;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.xyj.entity.Emp;
public interface EmpService {
List<Emp> findAll();
int delete(@Param("eid")int id);
int insert(Emp emp);
int update(Emp emp);
Emp findById(@Param("eid")int eid);
}
package com.xyj.service;
import org.apache.ibatis.annotations.Param;
import com.xyj.entity.Dept;
public interface DeptService {
Dept findById(@Param("did")int did);
}
7、 编写ServiceImpl层:
package com.xyj.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.xyj.dao.EmpDao;
import com.xyj.entity.Emp;
import com.xyj.service.EmpService;
@Service(value="empService") //把当前类放进IOC容器
public class EmpServiceImpl implements EmpService{
@Resource
private EmpDao ed;
@Override
public List<Emp> findAll() {
return ed.findAll();
}
@Override
public int delete(int id) {
return ed.delete(id);
}
@Override
public int insert(Emp emp) {
return ed.insert(emp);
}
@Override
public int update(Emp emp) {
return ed.update(emp);
}
@Override
public Emp findById(int eid) {
return ed.findById(eid);
}
}
package com.xyj.service.impl;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.xyj.dao.DeptDao;
import com.xyj.entity.Dept;
import com.xyj.service.DeptService;
@Service(value="deptService") //把当前类放进IOC容器
public class DeptServiceImpl implements DeptService{
@Resource
private DeptDao dd;
@Override
public Dept findById(int did) {
return dd.findById(did);
}
}
8、 编写Servlet层:
SelectAll的Servlet:
package com.xyj.servlet;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.xyj.entity.Emp;
import com.xyj.service.EmpService;
@WebServlet(name = "selectAll", urlPatterns = { "/selectAll" })
public class SelectAll extends HttpServlet {
private static final long serialVersionUID = 1L;
public SelectAll() {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
ApplicationContext ctx=new ClassPathXmlApplicationContext("bean.xml");
EmpService es = ctx.getBean(EmpService.class);
List<Emp> list = es.findAll();
System.out.println(list);
request.setAttribute("list",list);
request.getRequestDispatcher("index.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
其他的不再展示,省略余下的Servlet和jsp页面。