Spring + mybatis整合實例應用
項目結構圖 (Spring3.0.2 +mybatis3.0.4)
方案一: 通過配置文件整合Spring和mybatis
應用數據庫
-- --數據庫 tb_user --
drop table if exists tb_user; create table tb_user( id int primary key auto_increment comment '主鍵', username varchar(40) not null unique comment '用戶名', password varchar(40) not null comment '密碼', email varchar(40) comment '郵件', age int comment '年齡', sex char(2) not null comment '性別' );
對應的實體類
package com.icreate.entity; /** * * * @version : 1.0 * * @author : 蘇若年 <a href="mailto:DennisIT@163.com">發送郵件</a> * * @since : 1.0 創建時間: 2013-4-9 上午11:15:50 * * @function: TODO * */
public class User { private int id; private String username; private String password; private String sex; private String email; private int age; //getter() and setter ()
}
數據Dao接口
package com.icreate.dao; import java.util.List; import com.icreate.entity.User; /** * * * @version : 1.0 * * @author : 蘇若年 <a href="mailto:DennisIT@163.com">發送郵件</a> * * @since : 1.0 創建時間: 2013-4-9 上午11:36:34 * * @function: TODO * */
public interface UserDao { public int insert(User user); public int update(User user); public int delete(String userName); public List<User> selectAll(); public int countAll(); public User findByUserName(String userName); }
在config目錄下進行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.icreate.dao.UserDao">
<select id="countAll" resultType="int"> <!-- 查詢表中記錄總數 --> select count(*) c from tb_user; </select>
<select id="selectAll" resultType="com.icreate.entity.User"> <!-- 查詢表中的所有用戶 --> select * from tb_user order by username asc </select>
<insert id="insert" parameterType="com.icreate.entity.User"> <!-- 向數據庫中插入用戶 --> insert into tb_user(username,password,email,sex,age) values(#{username},#{password},#{email},#{sex},#{age}) </insert>
<update id="update" parameterType="com.icreate.entity.User"> <!-- 更新庫中的用戶 --> update tb_user set username=#{username},password=#{password},email=#{email},sex=#{sex},age=#{age} where username=#{username} </update>
<delete id="delete" parameterType="String"> <!-- 刪除用戶 --> delete from tb_user where username=#{username} </delete>
<select id="findByUserName" parameterType="String" resultType="com.icreate.entity.User"> <!-- 根據用戶名查找用戶 --> select * from tb_user where username=#{username} </select>
</mapper>
Mybatis應用配置文件MyBatis-Configuration.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>
<mappers>
<mapper resource="com/icreate/dao/UserDao.xml"/>
</mappers>
</configuration>
Spring配置文件,本例中我們放在/WebRoot/WEB-INF/applicationContext.xml
<?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:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- 配置數據源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/db_mybatis?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:MyBatis-Configuration.xml"></property>
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="userDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.icreate.dao.UserDao"></property>
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
<bean id="userService" class="com.icreate.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean>
</beans>
同目錄下的web.xml文件進行如下配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<!-- applicationContext.xml文件在/WEB-INF/目錄下時可以這樣配置,-->
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<!-- 配置上下文監聽 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
配置說明:
<context-param/> 節點配置contextConfigLocation屬性是為了讓ContextLoaderListener找到Spring上下文的位置並加載它,如果不指定contextConfigLocation,ContextLoaderListener會到/WEB-INF/目錄下找applicationContext.xml來加載。
<listener/> 節點上配了ContextLoaderListener。它實現了ServletContextListener接口,所以web server啟動時ContextLoaderListener能讀取到ServletContext,也就能通過<context-param/>指定的Spring上下文的路徑來找到上下文並加載它。
當然,如果你不需要Spring來管理你的Bean,可以去掉上面兩個節點。
定義service接口
package com.icreate.service; import java.util.List; import com.icreate.entity.User; /** * * * @version : 1.0 * * @author : 蘇若年 <a href="mailto:DennisIT@163.com">發送郵件</a> * * @since : 1.0 創建時間: 2013-4-9 下午03:52:07 * * @function: TODO * */
public interface UserService { public int insert(User user); public int update(User user); public int delete(String userName); public List<User> selectAll(); public int countAll(); public User findByUserName(String userName); }
實現service接口,執行dao操作
package com.icreate.service.impl; import java.util.List; import com.icreate.dao.UserDao; import com.icreate.entity.User; import com.icreate.service.UserService; /** * * * @version : 1.0 * * @author : 蘇若年 <a href="mailto:DennisIT@163.com">發送郵件</a> * * @since : 1.0 創建時間: 2013-4-9 下午03:53:26 * * @function: TODO * */
public class UserServiceImpl implements UserService{ private UserDao userDao; public UserDao getUserDao() { return userDao; } public void setUserDao(UserDao userDao) { this.userDao = userDao; } public int countAll() { return this.userDao.countAll(); } public int delete(String userName) { return this.userDao.delete(userName); } public User findByUserName(String userName) { return this.userDao.findByUserName(userName); } public int insert(User user) { return this.userDao.insert(user); } public List<User> selectAll() { return this.userDao.selectAll(); } public int update(User user) { return this.userDao.update(user); } }
接下來寫我們的測試用例
package com.icreate.service; import java.util.List; import org.junit.Before; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; import com.icreate.entity.User; /** * * * @version : 1.0 * * @author : 蘇若年 <a href="mailto:DennisIT@163.com">發送郵件</a> * * @since : 1.0 創建時間: 2013-4-9 下午05:16:28 * * @function: TODO * */
public class SpringBatis { ApplicationContext context = null; UserService userService = null; @Before public void initContext(){ this.context = new FileSystemXmlApplicationContext("WebRoot/WEB-INF/applicationContext.xml"); this.userService = (UserService) context.getBean("userService"); } @Test public void countAll(){ System.out.println("數據庫中的記錄條數:" + userService.countAll()); } @Test public void insert(){ User user = new User(); user.setUsername("蘇若年"); user.setPassword("passtest"); user.setEmail("dennisit@163.com"); user.setSex("男"); user.setAge(23); userService.insert(user); } @Test public void selectAll(){ List<User> list = userService.selectAll(); for(int i=0; i<list.size(); i++){ User user = list.get(i); System.out.println("用戶名:" + user.getUsername() + "\t密碼:" + user.getPassword() + "\t郵箱:" + user.getEmail()); } } @Test public void update(){ User user = new User(); user.setUsername("蘇若年"); user.setPassword("xxxxxxxx"); user.setEmail("xxxxxx@163xxx"); user.setSex("男"); user.setAge(23); userService.update(user); } @Test public void delete(){ userService.delete("蘇若年"); } @Test public void findByName(){ User user = userService.findByUserName("蘇若年"); System.out.println("用戶名:" + user.getUsername() + "\t密碼:" + user.getPassword() + "\t郵箱:" + user.getEmail()); } }
方案二:使用注解整合
這次將配置文件放置在config目錄下.
數據庫表與實體類同上
數據dao接口定義
package com.icreate.dao; import java.util.List; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import com.icreate.entity.User; /** * * * @version : 1.0 * * @author : 蘇若年 <a href="mailto:DennisIT@163.com">發送郵件</a> * * @since : 1.0 創建時間: 2013-4-9 上午11:36:34 * * @function: TODO * */
public interface UserDao { @Insert("insert into tb_user(username,password,email,sex,age) values(#{username},#{password},#{email},#{sex},#{age})") public int insert(User user); @Update("update tb_user set username=#{username},password=#{password},email=#{email},sex=#{sex},age=#{age} where username=#{username}") public int update(User user); @Delete("delete from tb_user where username=#{username}") public int delete(String userName); @Select("select * from tb_user ") public List<User> selectAll(); @Select("select count(*) from tb_user") public int countAll(); @Select("select * from tb_user where username=#{username}") public User findByUserName(String userName); }
Service接口與實現不變.
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:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- 配置數據源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/db_mybatis?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="userDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.icreate.dao.UserDao"></property>
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
<bean id="userService" class="com.icreate.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean>
</beans>
Web.xml文件配置如下
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<!-- applicationContext.xml文件在/WEB-INF/目錄下時可以這樣配置,-->
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 配置上下文監聽 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
測試類大致上沒有變化,只是ApplicationContext初始化的方法改變成了下面方式
ApplicationContext context = null; UserService userService = null; @Before public void initContext(){ this.context = new ClassPathXmlApplicationContext("applicationContext.xml"); //this.context = new FileSystemXmlApplicationContext("WebRoot/WEB-INF/applicationContext.xml");
this.userService = (UserService) context.getBean("userService"); }
至此我們Spring與mybatis整合實例應用演示完畢
轉載請注明出處:[http://www.cnblogs.com/dennisit/archive/2013/04/10/3012972.html]