因spring3发布时mybatis还没有出正式版本,所以spring没有整合最新的mybatis.不过社区倒是开发了一个中间件。
需要的jar包
mybatis-3.0.6.jar
mybatis-spring-1.0.2.jar
要点:
1.在spring中配置mybatis工厂类
2.在dao层使用spring注入的的工具bean对数据进行操作
整合时,可以有四种方式来使用mybatis进行数据处理。
spring 中必须的配置。
spring的配置文件中加入以下内容
<!-- MyBatis配置 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="c3p0DataSource" />
<property name="configLocation" value="/WEB-INF/config/db/MyBatisConfiguration.xml" />
<property name="mapperLocations" value="/WEB-INF/config/db/*Mapper.xml" />
<property name="typeAliasesPackage" value="${mybatis.alias.basepackage}" />
</bean>
1.SqlSessionFactoryBean (必需)
就是中间件所需的处理类
2.dataSource (必需)
spring中数据源引用
3.configLocation (可选)
Mybatis自身的配置文件,一般用来声明别名
4.mapperLocation (可选)
mybatis的映射文件
5.typeAliasesPackage (可选)
要映射类的包路径,如果使用了这种方式,则configLocation中不必再进行声明
使用mybatis进行数据处理的四种方式(SqlSessionTemplate/SqlSessionDaoSupport/MapperFactoryBean/MapperScannerConfigurer)
不同方式的特点
- SqlSessionTemplate 这个需要写配置文件,在实现类中注入sqlsession,再使用sqlsession,是细颗粒控制
- SqlSessionDaoSupport 这个只需要在实现类中继承特殊类就可以使用sqlsession
- MapperFactoryBean 这个要写配置文件,把对应的所有接口在配置文件中引用即可,无需写实现类
- MapperScannerConfigurer 这个要写配置文件,只要给出接口所在的包即可,会自动把包中的接口引入,无需写实现类
- SqlSessionTemplate
- 配置文件加入新配
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="sqlSessionFactory" /> <constructor-arg index="1" value="BATCH" /><!--- 如果想要进行批量操作可加入这个属性 -> </bean>
- 注入sqlsession()
@Reasource //使用spring3的注解注入 private SqlSession sqlSession;
- 使用sqlsession来进行操作
public User getUser(String userId) { return (User) sqlSession.selectOne("org.mybatis.spring.sample.mapper.UserMapper.getUser", userId); }
- SqlSessionDaoSupport(sqlSessionFactory会被spring自动装配,不需要手动注入)
- 继承SqlSessionDaoSupport类
Java代码 public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao { }
-
继承SqlSessionDaoSupport 方式不需手动注入是指不用在子类中声明sqlSessionTemplate的setter/getter方法,但在xml配置文件中仍需给子类增加一个<property name="sqlSessionTemplate" ref="sqlSessionTemplate"/>。
<bean id="idaoImpl" class="org.mybatis.spring.sample.dao.UseDaoImpl"> <property name="sqlSessionFactory" ref="sqlSessionFactory"></property> </bean>
- 使用getSqlSession()方法取sqlSession来进行数据处理
public User getUser(String userId) { return (User) getSqlSession().selectOne("org.mybatis.spring.sample.mapper.UserMapper.getUser", userId); }
- MapperFactoryBean
- 写配置文件,引入每个DAO接口
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> <property name="mapperInterface" value="org.mybatis.spring.sample.mapper.UserMapper" /> <property name="sqlSessionFactory" ref="sqlSessionFactory" /> </bean>
- 在业务层可直接注入dao的接口进行操作
- MapperScannerConfigurer
- 写配置文件,配置包名将自动引入包中的所有接口
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="org.mybatis.spring.sample.mapper" /> </bean>
- 在业务层可直接注入DAO接口操作,注入时使用的是接口名,其首字母小写
- 注意:如果有别的实现类,其提供的名称如果是接口名,且首字母小写,则会在启动时出现冲突错误
一个具体的例子:
采用抽象类org.mybatis.spring.support.SqlSessionDaoSupport提供SqlSession。
(1)spring配置文件:
(1)spring配置文件:
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:sqlMapConfig.xml"/>
<!--指定实体类映射文件,可以指定同时指定某一包以及子包下面的所有配置文件,mapperLocations和configLocation有一个即可,当需要为实体类指定别名时,可指定configLocation属性,再在mybatis总配置文件中采用mapper引入实体类映射文件。当两个都指定时,就不需要在mybatis总配置文件中重复引入mapper映射文件。这里采用指定一个的方式 -->
<!-- <property name="mapperLocations" value="classpath*:com/xxt/ibatis/dbcp/domain/user.map.xml"/ > -->
</bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<span> </span><constructor-arg index="0" ref="sqlSessionFactory" />
</bean>
<bean id="userDaoImpl3" class="com.xxt.ibatis.dbcp.dao.impl.UserDaoImpl3">
<!--注入SqlSessionTemplate实例 -->
<property name="sqlSessionTemplate" ref="sqlSession" />
<!--也可直接注入SqlSessionFactory实例,二者都指定时,SqlSessionFactory失效 -->
<!-- <property name="sqlSessionFactory" ref="sqlSessionFactory" /> -->
</bean>
(2)mybatis总配置文件sqlMapConfig.xml:
<configuration>
<typeAliases>
<typeAlias type="com.xxt.ibatis.dbcp.domain.User" alias="User" />
</typeAliases>
<mappers>
<mapper resource="com/xxt/ibatis/dbcp/domain/user.map.xml" />
</mappers>
</configuration>
(3)实体类映射文件user.map.xml:
<mapper namespace="com.xxt.ibatis.dbcp.domain.User">
<resultMap type="User" id="userMap">
<id property="id" column="id" />
<result property="name" column="name" />
<result property="password" column="password" />
<result property="createTime" column="createtime" />
</resultMap>
<select id="getUser" parameterType="User" resultMap="userMap">
select * from user where id = #{id}
</select>
<mapper/>
(2) dao层接口实现类UserDaoImpl3:
5) Java mapper类
另外可以参考:http://www.blogjava.net/stevenjohn/archive/2012/05/25/379220.html
public class UserDaoImpl3 extends SqlSessionDaoSupport implements UserDao {
public User getUserById(User user) {
return (User) getSqlSession().selectOne("com.xxt.ibatis.dbcp.domain.User.getUser", user);
}
}
例子2:
1)spring 配置文件 applicationContext-common
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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-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 ">
<context:component-scan base-package="com.hzjw"></context:component-scan>
<!-- 配置源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/hzjw01"></property>
<property name="username" value="root"></property>
<property name="password" value="123"></property>
</bean>
<!-- sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation" value="classpath:mybatis.xml"></property>
<property name="mapperLocations">
<list>
<value>classpath:com/hzjw/mapper/account-mapper.xml</value>
</list>
</property>
</bean>
<!-- 管理sqlmapper -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.hzjw.mapper"></property>
<property name="markerInterface" value="com.hzjw.mapper.SqlMapper"></property>
</bean>
</beans>
2)mybatis.xml
<?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 type="com.hzjw.entity.Account" alias="account"></typeAlias>
</typeAliases>
</configuration>
3) 映射文件 account-mapper.xml
<?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.hzjw.mapper.AccountMapper">
<!-- 插入操作 -->
<insert id="addAccount" parameterType="account">
insert into account(name,pwd) values(#{name},#{pwd})
</insert>
<!-- 删除操作 -->
<delete id="deleteById">
delete from account where id=#{0} and name=#{1}
</delete>
</mapper>
4) 实体类
package com.hzjw.entity;
import java.io.Serializable;
public class Account implements Serializable {
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
private int id;
private String name;
private String pwd;
}
package com.hzjw.mapper;
public interface SqlMapper {
}
package com.hzjw.mapper;
import com.hzjw.entity.Account;
public interface AccountMapper extends SqlMapper {
// 添加操作
public void addAccount(Account account);
// 删除
public void deleteById(int idt, String name);
}
6)Service类
package com.hzjw.service;
import com.hzjw.entity.Account;
public interface AccountService {
public void addAccount(Account acc);
public void deleteAccount(int id);
}
package com.hzjw.service.impl;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.hzjw.entity.Account;
import com.hzjw.mapper.AccountMapper;
import com.hzjw.service.AccountService;
@Service
public class AccountServiceImpl implements AccountService {
@Resource
private AccountMapper am; //直接使用接口声明一个变量, Spring会自动注入
public AccountServiceImpl () {
System.out.println("I am AccountServiceImpl");
System.out.println(this);
}
public void addAccount(Account acc) {
am.addAccount(acc);
}
public void deleteAccount(int id) {
am.deleteById(id, "sjl");
}
}