spring+springmvc+ibatis整合注解方式实例【转】
源自-----> http://shaohan126448.iteye.com/blog/2033563
(1)web.xml文件(Tomcat使用)
服务器根据配置内容初始化spring框架,springmvc框架和log4j日志框架
<?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"> <!-- 应用程序名称 --> <display-name>ISS</display-name> <!-- 应用程序描述说明性文字 --> <description>Spring,SpringMvc,Ibatis</description> <!-- ServletContext初始化参数 --> <context-param> <param-name>webAppRootKey</param-name> <param-value>spring_springmvc_ibatis.root</param-value> </context-param> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>/WEB-INF/classes/log4j.properties</param-value> </context-param> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/classes/applicationContext.xml</param-value> </context-param> <!-- 字符过滤,防止添加到数据库的数据为乱码 --> <filter> <filter-name>characterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- web权限配置 --> <filter> <filter-name>springSecurityFilterChain</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> </filter> <filter-mapping> <filter-name>springSecurityFilterChain</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 配置监听器,用于初始化 --> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- Servlet初始化参数,配置springmvc模块 --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/classes/springmvc-servlet.xml</param-value> </init-param> <load-on-startup>2</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 配置session存在时间 --> <session-config> <session-timeout>60</session-timeout> </session-config> <!-- 默认起始页面 --> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- 异常跳转页面 --> <error-page> <exception-type>java.lang.Exception</exception-type> <location>/WEB-INF/jsp/exception.jsp</location> </error-page> </web-app>
(2)springmvc-servlet.xml(Springmvc框架配置文件)
该文件是springmvc框架配置文件,也是它的核心文件
<?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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- 自动扫描,完成bean创建和依赖注入 --> <context:component-scan base-package="com.archie"/> <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/> <!-- 视图解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> </bean> <!-- 异常解析器 --> <bean id="simpleMappingExceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="exceptionMappings"> <props> <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">common/fileerror</prop> </props> </property> </bean> </beans>
(3)applicationContext.xml(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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-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" default-autowire="byName"> <!-- 自动扫描 --> <context:component-scan base-package="com.archie"/> <!-- 启动spring注解,当自动扫描启动后,该配置可以去掉 <context:annotation-config /> --> <!-- 启动spring注解,等同于 context:annotation-config <bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"/> <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> <bean class="org.springframework.beans.factory.annotation.PersistenceAnnotationBeanPostProcessor"/> <bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/> --> <!-- 配置数据源属性文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>jdbc.properties</value> </list> </property> </bean> <!-- 配置数据源 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </bean> <!-- 配置SqlMapClient对象 --> <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean"> <property name="configLocation" value="sqlMapConfig.xml"/> <property name="dataSource" ref="dataSource"/> </bean> <!--根据sqlMapClien创建一个SqlMapClient模版类--> <bean id="sqlMapClientTemplate" class="org.springframework.orm.ibatis.SqlMapClientTemplate"> <property name="sqlMapClient" ref="sqlMapClient"/> </bean> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- 启动spring事务注解,事务注解尽在此 --> <tx:annotation-driven transaction-manager="transactionManager"/> <!-- 配置事务特性 <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="select*" read-only="true" propagation="REQUIRED"/> <tx:method name="find*" read-only="true" propagation="REQUIRED"/> <tx:method name="save*" propagation="REQUIRED" isolation="REPEATABLE_READ"/> <tx:method name="update*" propagation="REQUIRED" isolation="REPEATABLE_READ"/> <tx:method name="add*" propagation="REQUIRED" isolation="REPEATABLE_READ"/> <tx:method name="delete*" propagation="REQUIRED" isolation="REPEATABLE_READ"/> <tx:method name="*" read-only="true"/> </tx:attributes> </tx:advice> --> <!-- 配置事务代理拦截器 <bean id="baseTransactionProxy" abstract="true" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"> <property name="transactionManager"> <ref bean="transactionManager"/> </property> <property name="transactionAttributes"> <props> <prop key="insert*">PROPAGATION_REQUIRED</prop> <prop key="update*">PROPAGATION_REQUIRED</prop> <prop key="delete*">PROPAGATION_REQUIRED</prop> <prop key="*">PROPAGATION_REQUIRED,readOnly</prop> </props> </property> </bean> --> <!-- 配置哪些类的方法需要进行事务管理 <aop:config> <aop:pointcut id="baseServiceMethods" expression="execution(* com.archie.service.*.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="baseServiceMethods"/> </aop:config> <aop:aspectj-autoproxy /> --> <!-- 配置Dao实例 <bean id="userDao" class="com.archie.dao.UserDao"> <property name="sqlMapClient" ref="sqlMapClient"/> </bean> --> <!-- 配置Service实例 <bean id="userService" class="com.archie.service.UserService"> <property name="userDao" ref="userDao"/> </bean> --> <!-- 添加了事务的管理类 <bean id="userManager" parent="baseTransactionProxy"> <property name="target"> <bean class="com.archie.service.UserService"/> </property> </bean> --> </beans>
(4)jdbc.properties(数据源属性文件)
数据源连接信息的源出处,目前配置了三种数据库Oracle,DB2和Mysql
# Database Connectivity
# Oracle
#driver = oracle.jdbc.driver.OracleDriver
#url = jdbc:oracle:thin:@localhost:1521:oracl
#username = scott
#password = tiger
# DB2
#driver = com.ibm.db2.jcc.DB2Driver
#url = jdbc:db2://192.168.1.2:50000/mydb
#username = root
#password = root
# Mysql
driver = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf-8
username = root
password = 1234
initialPoolSize = 1
minPoolSize = 1
maxPoolSize =10
(5)log4j.properties(log4j框架属性文件)
# log4j.properties
log4j.rootLogger=warn,console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%d] [%t] (%F:%L) %-5p %c - %m%n
log4j.appender.console.Encoding=GB18030
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.MaxFileSize=10240KB
log4j.appender.file.MaxBackupIndex=100
log4j.appender.file.Encoding=GB18030
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%d] [%t] (%F:%L) %-5p %c - %m%n
log4j.appender.ROLLING_FILE_CUSTOMER=org.apache.log4j.RollingFileAppender
log4j.appender.ROLLING_FILE_CUSTOMER.Threshold=debug
log4j.appender.ROLLING_FILE_CUSTOMER.Append=true
log4j.appender.ROLLING_FILE_CUSTOMER.MaxFileSize=1024KB
log4j.appender.ROLLING_FILE_CUSTOMER.MaxBackupIndex=30
log4j.appender.ROLLING_FILE_CUSTOMER.layout=org.apache.log4j.PatternLayout
log4j.appender.ROLLING_FILE_CUSTOMER.layout.ConversionPattern=%d - %c:%L - %-5p %c %x - %m%n
log4j.appender.ROLLING_FILE_WORKMANAGER=org.apache.log4j.RollingFileAppender
log4j.appender.ROLLING_FILE_WORKMANAGER.Threshold=debug
log4j.appender.ROLLING_FILE_WORKMANAGER.Append=true
log4j.appender.ROLLING_FILE_WORKMANAGER.MaxFileSize=1024KB
log4j.appender.ROLLING_FILE_WORKMANAGER.MaxBackupIndex=30
log4j.appender.ROLLING_FILE_WORKMANAGER.layout=org.apache.log4j.PatternLayout
log4j.appender.ROLLING_FILE_WORKMANAGER.layout.ConversionPattern=%d - %c:%L - %-5p %c %x - %m%n
log4j.appender.ROLLING_FILE_RSS=org.apache.log4j.RollingFileAppender
log4j.appender.ROLLING_FILE_RSS.Threshold=debug
log4j.appender.ROLLING_FILE_RSS.Append=true
log4j.appender.ROLLING_FILE_RSS.MaxFileSize=1024KB
log4j.appender.ROLLING_FILE_RSS.MaxBackupIndex=30
log4j.appender.ROLLING_FILE_RSS.layout=org.apache.log4j.PatternLayout
log4j.appender.ROLLING_FILE_RSS.layout.ConversionPattern=%d - %c:%L - %-5p %c %x - %m%n
(6)sqlMapConfig.xml(Ibatis框架配置文件)
该文件主要负责指定sql映射文件,即与model层对象对应的映射文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE sqlMapConfig PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN" "http://www.ibatis.com/dtd/sql-map-config-2.dtd"> <sqlMapConfig> <!-- 配置settings --> <settings lazyLoadingEnabled="true" useStatementNamespaces="false"/> <!-- 配置sql映射文件 --> <sqlMap resource="com/archie/model/User.xml"/> </sqlMapConfig>
6.Java代码编写
根据包目录,可以看出分成model层,dao层,service层和web层,另外附加test层,用于java环境测试
(1)model层(User.java+User.xml)
User.java代码
package com.archie.model; public class User { private int id; private String username; private String password; public User(){ } public User(int id){ this.id = id; } public User(int id, String username){ this.id = id; this.username = username; } public User(String username, String password) { this.username = username; this.password = password; } public User(int id, String username, String password){ this.id = id; this.username = username; this.password = password; } public int getId() { return id; } public void setId(int id) { this.id = id; } 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; } }
User.xml代码
(model层对象的sql映射文件,被dao层调用,本质是sql语句集合,所有相关的sql均于此)
<?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 namespace="User"> <typeAlias alias="User" type="com.archie.model.User"/> <select id="findAllUser" resultClass="User" > select * from t_user </select> <select id="findUserByID" resultClass="User" parameterClass="int"> select * from t_user where id=#id# </select> <select id="getTotalCount" resultClass="int"> select count(*) from t_user </select> <select id="searchUsers" resultClass="User" parameterClass="User"> select * from t_user <dynamic prepend="where"> <!-- 模糊查询,用$表示文本替换,而用#表示替换PrepareStatement中的?号 --> <isNotEmpty prepend="and" property="username"> (username like '%$username$%') </isNotEmpty> <isNotEmpty prepend="and" property="password"> (password like '%$password$%') </isNotEmpty> </dynamic> </select> <select id="findUserByNameAndPassword" resultClass="User" parameterClass="User"> select * from t_user where username=#username# and password=#password# </select> <insert id="insertUser" parameterClass="User"> insert into t_user(id,username,password) values(null,#username#,#password#) </insert> <update id="updateUser" parameterClass="User"> update t_user set username = #username#, password=#password# where id=#id# </update> <delete id="deleteUser" parameterClass="int"> delete from t_user where id=#id# </delete> <delete id="deleteUserByLike" parameterClass="User"> delete from t_user <dynamic prepend="where"> <!-- 模糊查询,用$表示文本替换,而用#表示替换PrepareStatement中的?号 --> <isNotEmpty prepend="and" property="username"> (username like '%$username$%') </isNotEmpty> <isNotEmpty prepend="and" property="password"> (password like '%$password$%') </isNotEmpty> </dynamic> </delete> </sqlMap>
(2)dao层(数据服务层,BaseDao.java+UserDao.java)
BaseDao.java(公共Dao,其他Dao均继承它)
package com.archie.dao; import javax.annotation.PostConstruct; import javax.annotation.Resource; import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport; import com.ibatis.sqlmap.client.SqlMapClient; public class BaseDao extends SqlMapClientDaoSupport { @Resource(name="sqlMapClient") //通过bean名称注入 private SqlMapClient sqlMapClient; @PostConstruct //完成sqlMapClient初始化工作 public void initSqlMapClient(){ super.setSqlMapClient(sqlMapClient); } }
UserDao.java(user数据服务层)
package com.archie.dao; import java.util.List; import org.springframework.stereotype.Component; import com.archie.model.User; @Component //将UserDao类注入到bean里面 public class UserDao extends BaseDao { public boolean addUser(User user) throws Exception{ User bean = (User)getSqlMapClientTemplate().insert("insertUser", user); return bean != null ? true : false; } public boolean deleteUser(int id) throws Exception{ int result = getSqlMapClientTemplate().delete("deleteUser", id); return result > 0 ? true : false; } public User getUserById(int id) throws Exception{ return (User)getSqlMapClientTemplate().queryForObject("findUserByID", id); } @SuppressWarnings("unchecked") public List getAllUsers() throws Exception{ return getSqlMapClientTemplate().queryForList("findAllUser"); } public boolean updateUser(User user) throws Exception{ int result = getSqlMapClientTemplate().update("updateUser", user); return result > 0 ? true : false; } public User getUserByNameAndPassword(User user) throws Exception{ return (User)getSqlMapClientTemplate().queryForObject("findUserByNameAndPassword", user); } public int getTotalCount() throws Exception{ return (Integer)getSqlMapClientTemplate().queryForObject("getTotalCount"); } @SuppressWarnings("unchecked") public List getUsersByLike(User user) throws Exception{ return getSqlMapClientTemplate().queryForList("searchUsers", user); } public int deleteUserByLike(User user) throws Exception{ int result = getSqlMapClientTemplate().delete("deleteUserByLike", user); if (result > 0) { System.out.println("模糊删除成功!"); }else { System.out.println("没有匹配的记录1"); } return result; } }
(3)service层(业务服务层,UserService.java)
UserService.java代码如下
package com.archie.service; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import com.archie.dao.UserDao; import com.archie.model.User; @Component //将UserService类注入到bean里面 @Transactional //注入事务管理 public class UserService { @Resource(name="userDao") // 通过名称注入到bean里面 private UserDao userDao; public User login(User user) throws Exception{ return userDao.getUserByNameAndPassword(user); } public void addUser(User user) throws Exception{ userDao.addUser(user); } public void deleteUser(int id) throws Exception{ boolean bool = userDao.deleteUser(id); if (!bool) { System.out.println("删除的记录不存在!"); throw new RuntimeException(); } } public User getUserById(int id) throws Exception{ User user = userDao.getUserById(id); if (user == null) { return null; } return userDao.getUserById(id); } public void updateUser(User user) throws Exception{ userDao.updateUser(user); } public int getTotalCount() throws Exception{ return userDao.getTotalCount(); } @SuppressWarnings("unchecked") public List getUsersByLike(User user) throws Exception{ return userDao.getUsersByLike(user); } public int deleteUserByLike(User user) throws Exception{ return userDao.deleteUserByLike(user); } public void insertUsers(List<User> list) throws Exception{ for (int i = 0; i < list.size(); i++) { if (i > 3) { System.out.println("列表太长,中断事务"); throw new RuntimeException("中断事务异常,当列表长度大于3的时候故意抛出,看看事务是否回滚"); } User user = list.get(i); userDao.addUser(user); } } }
(4)web层(界面控制层,UserController.java)
UserController.java
package com.archie.web;</P><P>import javax.annotation.Resource; import javax.servlet.http.HttpSession; import javax.validation.Valid;</P><P>import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView;</P><P>import com.archie.model.User; import com.archie.service.UserService;</P><P>@Controller @RequestMapping("/user/*") public class UserController { @Resource(name="userService") private UserService userService; private final String LIST="redirect:/detail"; /** * 登录 * @param user * @param session * @return */ @RequestMapping("/login") public ModelAndView login(@Valid User user,BindingResult result,HttpSession session) throws Exception{ if(!result.hasErrors()){ User loginUser=userService.login(user); if(loginUser!=null){ session.setAttribute("USER", loginUser); return new ModelAndView(LIST); }else{ return new ModelAndView("redirect:/"); } }else{ ModelAndView view=new ModelAndView(); view.setViewName("redirect:/"); view.addObject("error", result.getAllErrors()); return view; } } /** * 跳转至添加页 * @return */ @RequestMapping(value="/toAdd",method=RequestMethod.GET) public ModelAndView toAdd(){ return new ModelAndView("user/add"); } /** * 保存 * @param user * @return */ @RequestMapping(value="/add",method=RequestMethod.POST) public ModelAndView add(@Valid User user,BindingResult result) throws Exception{ if(result.hasErrors()){ return new ModelAndView("user/add","error", result.getAllErrors()); }else{ userService.addUser(user); return new ModelAndView(LIST); } } /** * 根据ID删除 * @param id * @return */ @RequestMapping(value="/delete/{id}") public ModelAndView delete(@PathVariable int id) throws Exception{ userService.deleteUser(id); return new ModelAndView(LIST); } /** * 跳转至编辑页面 * @param id * @return */ @RequestMapping(value="/edit/{id}") public ModelAndView edit(@PathVariable int id) throws Exception{ User user=userService.getUserById(id); return new ModelAndView("user/edit","user",user); } /** * 编辑 * @param user * @return */ @RequestMapping(value="/edit") public ModelAndView update(@Valid User user,BindingResult result)throws Exception{ ModelAndView view=new ModelAndView(); if(result.hasErrors()){ view.addObject("error", result.getAllErrors()); view.setViewName("user/edit"); return view; }else{ userService.updateUser(user); return new ModelAndView(LIST); } } }
TestUserController.java
import java.util.ArrayList; import java.util.List; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.archie.model.User; import com.archie.service.UserService; public class TestUserController { public static void main(String[] args) throws Exception{ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); UserService userService = (UserService)context.getBean("userService"); List<User> list = new ArrayList<User>(); list.add(new User("wang", "wang")); list.add(new User("wang", "wang")); list.add(new User("wang", "wang")); userService.insertUsers(list); System.out.println("恭喜恭喜,添加成功!"); userService.deleteUser(26); System.out.println("恭喜恭喜,删除成功!"); User beanUser = userService.getUserById(21); if (beanUser != null) { System.out.println("恭喜恭喜,查找成功!"); }else { System.out.println("不好意思,您所查找的用户不存在!"); } int totalCount = userService.getTotalCount(); System.out.println("TotalCount="+totalCount); int result = userService.deleteUserByLike(new User("wang","wang")); System.out.println("模糊删除的记录条数是:"+result); List users = userService.getUsersByLike(new User("meimei","1234")); if (users == null || users.size() == 0) { System.out.println("没有匹配的记录2"); }else { for (int i = 0; i < users.size(); i++) { User user = (User)users.get(i); System.out.println("username="+user.getUsername()+",password="+user.getPassword()); } } System.out.println("length="+users.size()); } }
感觉空虚寂寞,只是因为你无所关注,无处付出。