一、步骤
- 导入相关jar包
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.10</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.2.1.RELEASE</version>
</dependency>
切记:spring系列的包,一定要版本相符。不然会出现类找不到的问题(即使这个类在spring的包中能找到)。就比如这里之前
spring-jdbc的版本是4.3.7.RELEASE,但是spring-webmvc的版本是4.2.1.RELEASE要低于spring-jdbc的版本。所以测试结果会
出现找不到类的情况。
|
|
只要是出现 java.lang.NoSuchMethodError,
java.lang.ClassNotFoundException,
Cannot find class ,
这些类型的异常,都可以更换jar包的版本来看看。
|
- 编写配置文件
spring的配置文件(beans.xml):
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 配置数据源 -->
<beanid="dataSource"class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<propertyname="driverClassName"value="com.mysql.jdbc.Driver"></property>
<propertyname="url"value="jdbc:mysql://localhost:3306/test"></property>
<propertyname="username"value="root"></property>
<propertyname="password"value="123456"></property>
</bean>
<!-- 配置sqlSessionFactory -->
<beanid="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean">
<propertyname="dataSource"ref="dataSource"></property>
<propertyname="configLocation"value="classpath:mybatis-config.xml"></property>
</bean>
<beanid="sqlSessionTemplate"class="org.mybatis.spring.SqlSessionTemplate">
<constructor-argindex="0"ref="sqlSessionFactory"></constructor-arg>
</bean>
<beanid="userDao"class="com.liujie.dao.impl.UserDaoImpl">
<propertyname="sqlSession"ref="sqlSessionTemplate"></property>
</bean>
</beans>
mybatis的配置文件(mybatis-config.xml):
<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPEconfiguration
PUBLIC
"-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<packagename="com.liujie.model"/>
</typeAliases>
<mappers>
<mapperresource="com/liujie/model/user.mapper.xml"/>
</mappers>
</configuration>
user.mapper.xml:
<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPEmapper
PUBLIC
"-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mappernamespace="com.liujie.model.UserMapper">
<selectid="selectUser"resultType="User">
select * from user
</select>
<selectid="selectUserById"resultType="User">
select * from user where id = #{id}
</select>
</mapper>
- 实现
Dao的实现:
publicclass
UserDaoImpl
implementsUserDao {
privateSqlSessionTemplatesqlSession;
publicvoid
setSqlSession(SqlSessionTemplatesqlSession)
{
this.sqlSession=
sqlSession;
}
publicList<User> selectUser() {
returnsqlSession.selectList("com.liujie.model.UserMapper.selectUser");
}
publicUser selectUserById(intid)
{
returnsqlSession.selectOne("com.liujie.model.UserMapper.selectUserById",id);
}
}
测试:
publicclass
Test {
publicstatic
void
main(String[]args) {
ApplicationContextcontext
=
newClassPathXmlApplicationContext("beans.xml");
UserDaouserDao
= (UserDao)context.getBean("userDao");
System.out.println(userDao.selectUser().size());
}
}
二、声明式事务管理
- 使用声明式事务之前
<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPEmapper
PUBLIC
"-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mappernamespace="com.liujie.model.UserMapper">
<selectid="selectUser"resultType="User">
select * from user
</select>
<selectid="selectUserById"resultType="User">
select * from user where id = #{id}
</select>
<insertid="addUser"parameterType="User"useGeneratedKeys="true">
insert into user(name, pwd) values(#{name}, #{pwd})
</insert>
<deleteid="remove">
<!-- 这里故意写错,执行时就会报错 -->
deletes from user where id = #{id}
</delete>
</mapper>
publicclass
UserDaoImpl
implementsUserDao {
privateSqlSessionTemplate
sqlSession;
publicvoid
setSqlSession(SqlSessionTemplate
sqlSession) {
this.sqlSession=
sqlSession;
}
publicList<User> selectUser() {
Useruser
=
newUser();
user.setName("大虾");
user.setPwd("666");
sqlSession.insert("com.liujie.model.UserMapper.addUser",user);
//执行delete时会报错
sqlSession.delete("com.liujie.model.UserMapper.remove",
20);
returnsqlSession.selectList("com.liujie.model.UserMapper.selectUser");
}
publicUser selectUserById(intid)
{
returnsqlSession.selectOne("com.liujie.model.UserMapper.selectUserById",id);
}
}
|
运行结果:虽然在执行delete的时候报错了,但是insert还是执行成功了。 |
- 使用声明式事务以后
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 配置数据源 -->
<beanid="dataSource"class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<propertyname="driverClassName"value="com.mysql.jdbc.Driver"></property>
<propertyname="url"value="jdbc:mysql://localhost:3306/test"></property>
<propertyname="username"value="root"></property>
<propertyname="password"value="123456"></property>
</bean>
<!-- 声明式事务配置 -->
<!-- 配置事务管理器 -->
<beanid="txManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<propertyname="dataSource"ref="dataSource"/>
</bean>
<!-- 配置事务通知 -->
<tx:adviceid="txAdvice"transaction-manager="txManager">
<tx:attributes>
<!-- 配置哪些方法使用什么样的事务,配置事务的传播特性 -->
<tx:methodname="add"propagation="REQUIRED"/>
<tx:methodname="insert"propagation="REQUIRED"/>
<tx:methodname="update"propagation="REQUIRED"/>
<tx:methodname="delete"propagation="REQUIRED"/>
<tx:methodname="remove*"propagation="REQUIRED"/>
<tx:methodname="get"read-only="true"/>
<tx:methodname="*"propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<aop:config>
<!-- 切入点应该是service.impl下的所有类的所有方法,这里为了方便测试所以直接用了dao.impl -->
<aop:pointcutexpression="execution(*
com.liujie.dao.impl.*.*(..))"id="pointcut"/>
<aop:advisoradvice-ref="txAdvice"pointcut-ref="pointcut"/>
</aop:config>
<!-- 声明式事务配置结束 -->
<!-- 配置sqlSessionFactory -->
<beanid="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean">
<propertyname="dataSource"ref="dataSource"></property>
<propertyname="configLocation"value="classpath:mybatis-config.xml"></property>
</bean>
<beanid="sqlSessionTemplate"class="org.mybatis.spring.SqlSessionTemplate">
<constructor-argindex="0"ref="sqlSessionFactory"></constructor-arg>
</bean>
<beanid="userDao"class="com.liujie.dao.impl.UserDaoImpl">
<propertyname="sqlSession"ref="sqlSessionTemplate"></property>
</bean>
</beans>
Spring事务类型详解:
PROPAGATION_REQUIRED--支持当前事务,如果当前没有事务,就新建一个事务。这是最常见的选择。
PROPAGATION_SUPPORTS--支持当前事务,如果当前没有事务,就以非事务方式执行。
PROPAGATION_MANDATORY--支持当前事务,如果当前没有事务,就抛出异常。
PROPAGATION_REQUIRES_NEW--新建事务,如果当前存在事务,把当前事务挂起。
PROPAGATION_NOT_SUPPORTED--以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。
PROPAGATION_NEVER--以非事务方式执行,如果当前存在事务,则抛出异常。
PROPAGATION_NESTED--如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则进行与PROPAGATION_REQUIRED类似的
操作。
|
<tx:methodname="get"read-only="true"/>就是说名为get的函数里面只能有select等读取操作,不能有insert等写入操作。否则就
会报异常。
|
运行结果:publicList<User> selectUser()里面的所有对数据库的操作都不会成功。(一旦其中一个出错,其他的都会回滚) |
三、使用最新的mybatis-spring(这里用的是1.3.1)整合。在spring配置文件中,不需要管理sqlSessionTemplate。在Dao的实现中,需要
继承SqlSessionDaoSupport。
现在的写法:(第二中方式)
<!-- 配置sqlSessionFactory -->
<beanid="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean">
<propertyname="dataSource"ref="dataSource"></property>
<propertyname="configLocation"value="classpath:mybatis-config.xml"></property>
</bean>
<beanid="userDao"class="com.liujie.dao.impl.UserDaoImpl">
<propertyname="sqlSessionFactory"ref="sqlSessionFactory"></property>
</bean>
publicclass
UserDaoImpl
extendsSqlSessionDaoSupportimplementsUserDao
{
publicList<User> selectUser() {
returngetSqlSession().selectList("com.liujie.model.UserMapper.selectUser");
}
publicUser selectUserById(intid)
{
returngetSqlSession().selectOne("com.liujie.model.UserMapper.selectUserById",id);
}
}
|
以前的写法:(第一种方式)
<!-- 配置sqlSessionFactory -->
<beanid="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean">
<propertyname="dataSource"ref="dataSource"></property>
<propertyname="configLocation"value="classpath:mybatis-config.xml"></property>
</bean>
<beanid="sqlSessionTemplate"class="org.mybatis.spring.SqlSessionTemplate">
<constructor-argindex="0"ref="sqlSessionFactory"></constructor-arg>
</bean>
<beanid="userDao"class="com.liujie.dao.impl.UserDaoImpl">
<propertyname="sqlSession"ref="sqlSessionTemplate"></property>
</bean>
publicclass
UserDaoImpl
implementsUserDao {
privateSqlSessionTemplate
sqlSession;
publicvoid
setSqlSession(SqlSessionTemplatesqlSession) {
this.sqlSession=
sqlSession;
}
publicList<User> selectUser() {
returnsqlSession.selectList("com.liujie.model.UserMapper.selectUser");
}
publicUser selectUserById(intid)
{
returnsqlSession.selectOne("com.liujie.model.UserMapper.selectUserById",id);
}
}
|
明显是简洁了不少。 |
四、spring整合mybatis第三种方式
mybatis使用注解(不需要配置user.mapper.xml文件):
publicinterfaceUserMapper
{
@Select("select
* from user")
publicList<User> selectUser();
}
publicinterfaceUserService {
publicList<User> selectUser();
}
publicclass
UserServiceImpl
implementsUserService {
privateUserMapper
userMapper;
publicvoid
setUserMapper(UserMapperuserMapper) {
this.userMapper=
userMapper;
}
publicList<User> selectUser() {
returnuserMapper.selectUser();
}
}
<!-- 配置sqlSessionFactory -->
<beanid="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean">
<propertyname="dataSource"ref="dataSource"></property>
<propertyname="configLocation"value="classpath:mybatis-config.xml"></property>
</bean>
<beanid="userMapper"class="org.mybatis.spring.mapper.MapperFactoryBean">
<propertyname="mapperInterface"value="com.liujie.mapper.UserMapper"></property>
<propertyname="sqlSessionFactory"ref="sqlSessionFactory"></property>
</bean>
<beanid="userService"class="com.liujie.service.impl.UserServiceImpl">
<propertyname="userMapper"ref="userMapper"></property>
</bean>
五、spring整合mybatis第四种方式(不需要配置mybatis-config.xml文件)
<propertyname="mapperLocations"value="classpath:com/liujie/model/*.mapper.xml"></property>只是改了这里。 |
<!-- 配置sqlSessionFactory -->
<beanid="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean">
<propertyname="dataSource"ref="dataSource"></property>
<propertyname="mapperLocations"value="classpath:com/liujie/model/*.mapper.xml"></property>
</bean>
<beanid="userDao"class="com.liujie.dao.impl.UserDaoImpl">
<propertyname="sqlSessionFactory"ref="sqlSessionFactory"></property>
</bean>
<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPEmapper
PUBLIC
"-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mappernamespace="com.liujie.model.UserMapper">
<selectid="selectUser"resultType="com.liujie.model.User">
select * from user
</select>
<selectid="selectUserById"resultType="com.liujie.model.User">
select * from user where id = #{id}
</select>
<insertid="addUser"parameterType="com.liujie.model.User"useGeneratedKeys="true">
insert into user(name, pwd) values(#{name}, #{pwd})
</insert>
<deleteid="remove">
<!-- 这里故意写错,执行时就会报错 -->
deletes from user where id = #{id}
</delete>
</mapper>
没有了mybatis-config.xml文件,就不能用别名了,
resultType="com.liujie.model.User"和parameterType="com.liujie.model.User"都要使用类名的全称。
|
publicclass
UserDaoImpl
extendsSqlSessionDaoSupport
implements
UserDao {
publicList<User> selectUser() {
returngetSqlSession().selectList("com.liujie.model.UserMapper.selectUser");
}
publicUser selectUserById(intid)
{
returngetSqlSession().selectOne("com.liujie.model.UserMapper.selectUserById",id);
}
}