本人刚刚接触mybatis,今天把它和spring整合起来用了一个上午==。
一开始是通过配置文件来配置,后来尝试用了一下注解,觉得mybatis的注解真的有点恶心。。。一大坨的,所以我还是建议使用配置文件吧!
1.首先配置spring配置文件
<!--数据源-->
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean> <!--mybatis 的 sqlsessionFactoryNean-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource"/>
<property name="configLocation" value="classpath:conf.xml"/>
<property name="mapperLocations" value="classpath:com/seven/dao/*.xml"/>
<property name="typeAliasesPackage" value="com.seven.domain"/><!--指定实体类包,自动将实体类的简单类名映射为别名-->
</bean> <!--映射器接口,,,,有了 下面配置就不用了-->
<!-- <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
<property name="mapperInterface" value="com.seven.dao.UserMapper"/>
</bean>--> <!--mybatis自动扫描加载sql映射文件:mapperScannerConfigurer-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.seven.dao"/><!--指定sql映射文件、接口所在的包-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean> <!--事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="datasource"/>
</bean> <!--声明事务-->
<tx:annotation-driven transaction-manager="transactionManager"/>
2.mybatis本身的相关配置
<?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> <settings>
<!-- 全局映射器启用缓存 -->
<setting name="cacheEnabled" value="true" />
<!-- 查询时,关闭关联对象即时加载以提高性能 -->
<setting name="lazyLoadingEnabled" value="true" />
<!-- 设置关联对象加载的形态,此处为按需加载字段(加载字段由SQL指 定),不会加载关联表的所有字段,以提高性能 -->
<setting name="aggressiveLazyLoading" value="false" />
<!-- 对于未知的SQL查询,允许返回不同的结果集以达到通用的效果 -->
<setting name="multipleResultSetsEnabled" value="true" />
<!-- 允许使用列标签代替列名 -->
<setting name="useColumnLabel" value="true" />
<!-- 允许使用自定义的主键值(比如由程序生成的UUID 32位编码作为键值),数据表的PK生成策略将被覆盖 -->
<setting name="useGeneratedKeys" value="true" />
<!-- 给予被嵌套的resultMap以字段-属性的映射支持 -->
<setting name="autoMappingBehavior" value="FULL" />
<!-- 对于批量更新操作缓存SQL以提高性能 -->
<setting name="defaultExecutorType" value="BATCH" />
<!-- 数据库超过25000秒仍未响应则超时 -->
<setting name="defaultStatementTimeout" value="25000" />
</settings> <!-- 全局别名设置,在映射文件中只需写别名,而不必写出整个类路径 -->
<!-- <typeAliases>
<typeAlias alias="TestBean"
type="com.wotao.taotao.persist.test.dataobject.TestBean" />
</typeAliases>--> <!-- 非注解的sql映射文件配置,如果使用mybatis注解,该mapper无需配置,但是如果mybatis注解中包含@resultMap注解,则mapper必须配置,给resultMap注解使用,交给spring管理了 -->
<!--<mappers>
<mapper resource="persist/test/orm/test.xml" />
</mappers>--> </configuration>
3.实体,接口
package com.seven.domain; import java.util.Date; /**
* Created by Seven on 2015/5/29.
*/
public class User {
private int id;
private String loginName;
private String userName;
private String password; public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String getLoginName() {
return loginName;
} public void setLoginName(String loginName) {
this.loginName = loginName;
} public String getUserName() {
return userName;
} public void setUserName(String userName) {
this.userName = userName;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
}
}
package com.seven.dao; import com.seven.domain.User;
import org.springframework.transaction.annotation.Transactional; import java.util.List; /**
* Created by Seven on 2015/5/29.
*/
@Transactional
public interface UserMapper { void save(User user); void update(User user); void delete(int id); User findById(int id); List<User> findAll(); }
4.接下就是比较重要的一步,写接口的映射文件,这样就实验了dao
<?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">
<!--namespace必须是接口的全类名 -->
<mapper namespace="com.seven.dao.UserMapper"> <resultMap id="userResult" type="User">
<result column="id" property="id"/>
<result column="loginName" property="loginName"/>
<result column="userName" property="userName"/>
<result column="password" property="password"/>
</resultMap> <!-- 取得插入数据后的id -->
<insert id="save">
insert into tb_user(loginName,userName,password)
values(#{loginName},#{userName},#{password})
</insert> <update id="update">
update tb_user
set loginName = #{loginName},
userName = #{userName},
password = #{password}
where id = #{id}
</update> <delete id="delete">
delete from tb_user
where id = #{id}
</delete> <select id="findById" resultMap="userResult">
select *
from tb_user
where id = #{id}
</select> <select id="findAll" resultMap="userResult">
select *
from tb_user
</select>
</mapper>
5.测试,需要导入spring的测试包
package com.seven.test; import com.seven.dao.UserMapper;
import com.seven.domain.User;
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 java.util.Date; /**
* Created by Seven on 2015/5/29.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/application.xml")
public class MyTest { @Autowired
private UserMapper userMapper; @Test
public void testSave(){
System.out.println(userMapper);
User user = new User();
user.setLoginName("seven");
user.setUserName("lin");
user.setPassword("123"); userMapper.save(user);
} } 总结,通过这种配置可以实现不用sqlsession而实现crud,因为都交给sprin来实现了,但是这种方法在service层实现的时候代码会比较冗余,但是这种方法思路比较清晰,有好有坏==。