网上有很多整合的例子,但大多不能跑起来,至此,本人整理了一套基本的搭建.以备不时之需.
首先Spring3.X 整合 Mybatis3.X 有些jar稍微有变化,大家注意!!! 附件是所有内容,下载测试
先上整理目录结构
pom.xml的内容
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>spring.mybatis.maven</groupId> <artifactId>spring-mybatis-maven</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>sm.maven Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <org.springframework.version>3.0.5.RELEASE</org.springframework.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> <scope>test</scope> </dependency> <!-- mybatis 3.x 结合 spring 3.x 需要的额外包 ,很多童靴出现这个问题--> <dependency> <groupId>aopalliance</groupId> <artifactId>aopalliance</artifactId> <version>1.0</version> <optional>true</optional> </dependency> <!-- mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.3</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> <!-- servlet Api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.1</version> <scope>provided</scope> </dependency> <!-- mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.18</version> </dependency> <!-- spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${org.springframework.version}</version> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${org.springframework.version}</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${org.springframework.version}</version> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${org.springframework.version}</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${org.springframework.version}</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${org.springframework.version}</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${org.springframework.version}</version> <optional>true</optional> </dependency> <!-- commons - dbcp --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>commons-pool</groupId> <artifactId>commons-pool</artifactId> <version>1.5.3</version> <scope>test</scope> </dependency> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.2.1</version> </dependency> <!-- log mybatis首先采用slf4j--> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.5</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.5</version> </dependency> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency> <!-- other 同样是必须的 --> <dependency> <groupId>javassist</groupId> <artifactId>javassist</artifactId> <version>3.3</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.7.4</version> </dependency> </dependencies> <build> <finalName>sm.maven</finalName> <!-- 指定config目录到classpath下面 --> <resources> <resource> <targetPath>.</targetPath> <directory>src/main/config</directory> </resource> </resources> </build> </project>
IUserDAO 演示几个简单的方法
package org.xyz.dao; import java.util.List; import org.springframework.dao.DataAccessException; import org.xyz.po.User; /*DataAccessException 异常是Spring整合DAO层的顶级异常*/ public interface IUserDAO { public List<User> getAllUser() throws DataAccessException; public User getUserById(Integer id)throws DataAccessException; public void deleteUserById(Integer id) throws DataAccessException; public void modifyUserById(User user) throws DataAccessException; /*保存,返回主键id*/ public Integer saveUser(User user) throws DataAccessException; }
DAO的实现
package org.xyz.dao; import java.util.List; import org.apache.ibatis.session.SqlSession; import org.apache.log4j.Logger; import org.springframework.dao.DataAccessException; import org.xyz.po.User; public class UserMapperImpl implements IUserDAO { final static Logger log = Logger.getLogger(UserMapperImpl.class); private SqlSession sqlSession; public SqlSession getSqlSession() { return sqlSession; } public void setSqlSession(SqlSession sqlSession) { log.warn("初始化sqlSession success ! "+sqlSession); this.sqlSession = sqlSession; } public User getUserById(Integer id) throws DataAccessException{ log.debug("-----------------delete user success ! --size:"+id); return sqlSession.selectOne("org.xyz.po.UserMapper.getUser",id ); } public void deleteUserById(Integer id) throws DataAccessException{ sqlSession.delete("org.xyz.po.UserMapper.deleteUser", id); log.debug("-----------------delete user success ! --"+id); } public void modifyUserById(User user)throws DataAccessException { sqlSession.update("org.xyz.po.UserMapper.modifyUser", user); log.debug("------------------modify user success ! --"+user); } public Integer saveUser(User user)throws DataAccessException { log.debug("delete user success ! --"+user); return sqlSession.insert("org.xyz.po.UserMapper.saveUser", user); } public List<User> getAllUser() throws DataAccessException{ return sqlSession.selectList("org.xyz.po.UserMapper.getAllUser"); } }
自定义异常
package org.xyz.exception; import org.springframework.dao.DataAccessException; /** * 自定义异常 */ public class ServiceException extends DataAccessException { public ServiceException(String msg) { super(msg); } @Override public String getMessage() { return super.getMessage(); } @Override public Throwable getMostSpecificCause() { return super.getMostSpecificCause(); } @Override public Throwable getRootCause() { return super.getRootCause(); } private static final long serialVersionUID = 6748277402450587224L; }
User 实体
package org.xyz.po; import java.io.Serializable; import java.sql.Date; public class User implements Serializable { private static final long serialVersionUID = 9113088589369627813L; private Integer id; private String name; private String password; private Date lastLogintime; private boolean isLogin; 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 String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Date getlastLoginTime() { return lastLogintime; } public void setlastLogintime(Date lastLogintime) { this.lastLogintime = lastLogintime; } public static long getSerialversionuid() { return serialVersionUID; } public boolean isLogin() { return isLogin; } public void setLogin(boolean isLogin) { this.isLogin = isLogin; } @Override public String toString() { return this.name+","+this.id+","+this.password; } }
Service层接口
package org.xyz.service; import java.util.List; import org.xyz.exception.ServiceException; import org.xyz.po.User; /*Service层 用来测试事务,本例没有实际意义*/ public interface IUserService { /*修改用户信息*/ public void updateAndSave(User user) throws ServiceException ; /*查询所有用户信息*/ public List<User> getAllUser() throws ServiceException; /*查询用户信息*/ public User getUserById(Integer id ) throws ServiceException; }
Service实现
package org.xyz.service; import java.util.List; import org.apache.log4j.Logger; import org.xyz.dao.IUserDAO; import org.xyz.exception.ServiceException; import org.xyz.po.User; public class UserServiceImpl implements IUserService { static final Logger log = Logger.getLogger(UserServiceImpl.class); private IUserDAO userDAO; /* 用update来测试事务 */ public void updateAndSave(User user) throws ServiceException { try { userDAO.saveUser(user); // 模拟异常 String s = null; System.out.println(s.length()); /* * 通过捕获Service层方法的DataAccessException来提交和回滚事务的, * 而Service层方法的DataAccessException又是来自调用DAO层方法所产生的异常 * 在Service层我们可以自己捕获DAO方法所产成的DataAccessException, * 然后再抛出一个业务方法有意义的异常 */ user.setlastLogintime( new java.sql.Date(System.currentTimeMillis())); log.info("updateAndSave ... updateUser() ... "); userDAO.modifyUserById(user); } catch (Exception e) { throw new ServiceException("update and save fail "); } } public User getUserById(Integer id) throws ServiceException { try { return userDAO.getUserById(id); } catch (Exception e) { throw new ServiceException("getUserById fail "); } } public void setUserDAO(IUserDAO userDAO) { this.userDAO = userDAO; } public IUserDAO getUserDAO() { return userDAO; } public List<User> getAllUser() { return userDAO.getAllUser(); } }
测试
package xyz.test; import org.apache.log4j.Logger; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.xyz.dao.IUserDAO; import org.xyz.po.User; public class Test1 { private static final Logger log = Logger.getLogger(Test1.class); @Test public void f1(){ String CONFIG = "applicationContext-1.xml"; ApplicationContext ac = new ClassPathXmlApplicationContext(CONFIG); IUserDAO UserDao = (IUserDAO) ac.getBean("UserDao"); User user = UserDao.getUserById(1); System.out.println(user.getName()); log.info(user.getName()); } }
至此 代码部分完成,接下来看配置文件.log4j.properties. jdbc.properties就不列举出来,google很多
applicationContext-1的配置内容
<?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-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/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <!-- 配置数据源 --> <context:property-placeholder location="classpath:jdbc.properties"/> <!-- 配置数据源 --> <bean id="dbcpDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${driver}"></property> <property name="url" value="${url}"></property> <property name="username" value="${username}"></property> <property name="password" value="${password}"></property> </bean> <!-- 创建SqlSessionFactory,同时指定数据源--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dbcpDataSource" /> <!-- 指定sqlMapConfig总配置文件,订制的environment在spring容器中不在生效--> <property name="configLocation" value="classpath:mybatis-config.xml" /> </bean> <!-- SqlSessionTemplate 这个需要写配置文件,在实现类中注入sqlsession,再使用sqlsession,是细颗粒控制 --> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="sqlSessionFactory" /> </bean> <!-- DAO 层 注入sqlSession --> <bean name="UserDao" class="org.xyz.dao.UserMapperImpl"> <!-- sqlSession是线程安全的 --> <property name="sqlSession" ref="sqlSession"></property> </bean> <!-- Service层 注入DAO --> <bean id="UserSerivice" class="org.xyz.service.UserServiceImpl"> <property name="userDAO" ref="UserDao"></property> </bean> <!-- 声明式事务管理 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dbcpDataSource"></property> </bean> <!-- 配置事务方案 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- propagation:事务类型 --> <tx:method name="update*" propagation="REQUIRED" /> <!-- NOT_SUPPORTED : 不使用事务管理 --> <tx:method name="get*" propagation="NOT_SUPPORTED" read-only="true"/> </tx:attributes> </tx:advice> <!-- aop进行事务配置 --> <aop:config> <!--execution(* org.xyz.service.UserServiceImpl.*(..)): org.xyz.service.UserServiceImpl类的所有方法 --> <aop:pointcut expression="execution(* org.xyz.service.UserServiceImpl.*(..))" id="servicePoint"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="servicePoint"/> </aop:config> </beans>
mybatis-config.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> <!-- 类 别名 ,这里定义了类别名,在org/xyz/po/UserMapper.xml文件中 可直接使用User --> <typeAliases> <typeAlias type="org.xyz.po.User" alias="User" /> </typeAliases> <mappers> <mapper resource="UserMapper.xml"/> </mappers> </configuration>
UserMapper.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="org.xyz.po.UserMapper"> <resultMap type="User" id="userMap"> <id property="id" column="id" /> <result property="name" column="nickname" /> <result property="password" column="password" /> <result property="lastLogintime" column="lastLogintime" /> <result property="isLogin" column="isLogin" /> </resultMap> <!--查询:通过用户ID返回一个用户对象 --> <select id="getUser" resultMap="userMap" parameterType="Integer"> select * from sm_user <where>id = #{id}</where> </select> <!--查询:所有用户对象 ,返回的是集合包含的类型User , 不是List --> <select id="getAllUser" resultMap="userMap"> select * from sm_user </select> <!--删除: --> <delete id="deleteUser" parameterType="Integer"> delete from sm_user where id=#{id} </delete> <!--修改:--> <update id="modifyUser" parameterType="User" > update sm_user set nickname =#{name}, password = #{password} , lastLogintime = #{lastLogintime}, isLogin = #{isLogin} <where>id = #{id}</where> </update> <!--保存: 其中id代表插入的User对象的主键属性--> <insert id="saveUser" parameterType="User" useGeneratedKeys="true" keyProperty="id"> insert into sm_user (nickname,password,lastLogintime,isLogin) values (#{name},#{password},#{lastLoginTime},#{isLogin}) </insert> </mapper>
全部完成.
执行maven test 即可