转载请注明:http://www.cnblogs.com/tiantianbyconan/archive/2013/03/03/2941554.html
本文使用Struts+iBatis+Spring三层框架开实现对user表的CRUD。
分层如下:
iBatis配置文件(sqlMapConfig.xml):
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE sqlMapConfig PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-config-2.dtd"> <sqlMapConfig> <settings cacheModelsEnabled="true" enhancementEnabled="true" lazyLoadingEnabled="true" errorTracingEnabled="true" maxRequests="32" maxSessions="10" maxTransactions="5" useStatementNamespaces="false" /> <sqlMap resource="com/tiantian/ibatis/model/user.xml" /> </sqlMapConfig>
struts.xml:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <package name="ibatis_test" extends="struts-default"> <!-- 注册User action --> <action name="registerUser" class="registerUserAction"> </action> <!-- 删除User action --> <action name="deleteUser" class="deleteUserAction"> </action> <!-- 更新User action --> <action name="updateUser" class="updateUserAction"> </action> <!-- 查询所有User action --> <action name="findAllUsers" class="findAllUsersAction"> </action> <!-- 查询指定id的User action --> <action name="findUserById" class="findUserByIdAction"> </action> <!-- 模糊查询User action --> <action name="findUsersBykeyword" class="findUsersBykeywordAction"> </action> </package> </struts>
user.xml配置文件:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd"> <sqlMap> <!-- 为Student类取个别名 --> <typeAlias alias="UserAlias" type="com.tiantian.ibatis.model.User"/> <!-- 配置表和实体Bean之间的映射关系 --> <resultMap id="userMap" class="com.tiantian.ibatis.model.User"> <result property="id" column="id"/> <result property="username" column="username"/> <result property="password" column="password"/> <result property="age" column="age"/> </resultMap> <!-- 添加数据 --> <insert id="registerUser" parameterClass="UserAlias"> INSERT INTO user VALUES (NULL, #username#, #password#, #age#); </insert> <!-- 删除指定id的数据 --> <delete id="deleteUser" parameterClass="UserAlias"> DELETE FROM user WHERE id = #id#; </delete> <!-- 修改指定id的数据 --> <update id="updateUser" parameterClass="UserAlias"> UPDATE user SET username = #username#, password = #password#, age = #age# WHERE id = #id#; </update> <!-- 查询所有User信息 --> <select id="findAllUsers" resultMap="userMap"> SELECT * FROM user; </select> <!-- 查询指定id的User信息 --> <select id="findUserById" resultMap="userMap"> SELECT * FROM user WHERE id = #id#; </select> <!-- 模糊查询 --> <select id="findUsersByKeyword" resultMap="userMap"> SELECT * FROM user WHERE username LIKE '%$keyword$%'; </select> </sqlMap>
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" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/test" /> <property name="username" value="root" /> <property name="password" value="XXXX" /> <property name="validationQuery" value="select user.id from user"></property> <property name="maxIdle" value="15"></property> <property name="maxActive" value="15"></property> <property name="maxWait" value="1000"></property> </bean> <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean"> <property name="configLocation" value="classpath:sqlMapConfig.xml"></property> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 事务管理 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 声明式事务管理 --> <bean id="baseTransactionProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" abstract="true"> <property name="transactionManager" ref="transactionManager"></property> <property name="transactionAttributes"> <props> <!-- 表示设置事务属性所有以"find"和"get"开头的方法: - PROPAGATION_REQUIRED: 当前存在事务则使用存在的事务,如果不存在,则开启一个新的事务 - readOnly:表示只读的事务 --> <prop key="find*">PROPAGATION_REQUIRED,readOnly</prop> <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop> <prop key="*">PROPAGATION_REQUIRED</prop> </props> </property> </bean> <!-- *****************************以上一般只需修改数据库配置******************************** --> <!-- ********************************************************************* --> <!-- *******************************DAO*********************************** --> <!-- ********************************************************************* --> <!-- DAO、Service一般都配置成singleton(可以不写,因为默认是singleton) --> <bean id="userDao" class="com.tiantian.ibatis.dao.impl.UserDaoImpl" scope="singleton"> <property name="sqlMapClient" ref="sqlMapClient"></property> </bean> <!-- ************************************************************************* --> <!-- *******************************Service*********************************** --> <!-- ************************************************************************* --> <!-- Service,没有事务功能 --> <bean id="userServiceTarget" class="com.tiantian.ibatis.service.impl.UserServiceImpl"> <property name="userDao" ref="userDao"></property> </bean> <!-- Service的代理,目的是为Service添加事务的功能 --> <bean id="userService" parent="baseTransactionProxy"> <property name="target" ref="userServiceTarget"></property> </bean> <!-- ************************************************************************ --> <!-- *******************************Action*********************************** --> <!-- ************************************************************************ --> <!-- Action一般都配置成prototype(必须要写!) --> <!-- **User Actions** --> <bean id="registerUserAction" class="com.tiantian.ibatis.action.user.RegisterUserAction" scope="prototype"> <property name="userService" ref="userService"></property> </bean> <bean id="deleteUserAction" class="com.tiantian.ibatis.action.user.DeleteUserAction" scope="prototype"> <property name="userService" ref="userService"></property> </bean> <bean id="updateUserAction" class="com.tiantian.ibatis.action.user.UpdateUserAction" scope="prototype"> <property name="userService" ref="userService"></property> </bean> <bean id="findAllUsersAction" class="com.tiantian.ibatis.action.user.FindAllUsersAction"> <property name="userService" ref="userService"></property> </bean> <bean id="findUserByIdAction" class="com.tiantian.ibatis.action.user.FindUserByIdAction"> <property name="userService" ref="userService"></property> </bean> <bean id="findUsersBykeywordAction" class="com.tiantian.ibatis.action.user.FindUsersByKeywordAction"> <property name="userService" ref="userService"></property> </bean> </beans>
DAO接口:
/** * @author wangjie * @version 创建时间:2013-3-1 下午5:44:21 */ public interface UserDao { public void registerUser(User user); public boolean deleteUser(User user); public boolean updateUser(User user); public List<User> findAllUsers(); public User findUserById(User user); public List<User> findUsersByKeyword(String keyword); }
DAO实现类(执行各个Action所需的数据库查询操作):
package com.tiantian.ibatis.dao.impl; import java.util.List; import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport; import com.tiantian.ibatis.dao.UserDao; import com.tiantian.ibatis.model.User; /** * @author wangjie * @version 创建时间:2013-3-1 下午6:09:53 */ public class UserDaoImpl extends SqlMapClientDaoSupport implements UserDao{ public void registerUser(User user) { getSqlMapClientTemplate().insert("registerUser", user); } public boolean deleteUser(User user) { boolean result = false; int effectedRow = getSqlMapClientTemplate().delete("deleteUser", user); System.out.println("delete effectedRow: " + effectedRow); result = effectedRow > 0 ? true : false; return result; } public boolean updateUser(User user) { boolean result = false; int effectedRow = getSqlMapClientTemplate().update("updateUser", user); System.out.println("update effectedRow: " + effectedRow); result = effectedRow > 0 ? true : false; return result; } public List<User> findAllUsers() { return (List<User>)getSqlMapClientTemplate().queryForList("findAllUsers"); } public User findUserById(User user) { return (User) getSqlMapClientTemplate().queryForObject("findUserById", user); } public List<User> findUsersByKeyword(String keyword) { return (List<User>)getSqlMapClientTemplate().queryForList("findUsersByKeyword", keyword); } }
Action类(以RegisterUserAction为例):
package com.tiantian.ibatis.action.user; import com.opensymphony.xwork2.ActionSupport; import com.tiantian.ibatis.model.User; import com.tiantian.ibatis.service.UserService; import com.tiantian.ibatis.service.impl.UserServiceImpl; /** * @author wangjie * @version 创建时间:2013-3-2 下午11:26:18 */ public class RegisterUserAction extends ActionSupport{ private UserService userService; private User user; public User getUser() { return user; } public void setUser(User user) { this.user = user; } public UserService getUserService() { return userService; } public void setUserService(UserService userService) { this.userService = userService; } @Override public String execute() throws Exception { userService.registerUser(user); System.out.println("数据已经插入"); return null; } }