本次讲述的是MyBatis整合Struts2和Spring3的示例。
本文中使用的框架版本号为MyBatis3.1.0,Struts2.3.1.2,Spring3.1.1。
相关下载地址不再赘述,请读者自寻搜索下载。
本例中还使用到了其他的jar包,如commons-dbcp,commons-collections,commons-logging,commons-pool,log4j,slf4j。所需要的所有jar包截图如下:
1.建立一个web工程ssm,选择好运行环境:
2.导入上图中所有的jar包,文件组织方式如图所示:
2.在MySQL中建立数据库mybatis,
建表语句如下:
DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(100) DEFAULT NULL, `password` varchar(100) DEFAULT NULL, `role` varchar(20) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=utf8; INSERT INTO `user` VALUES ('1', 'zhangsan', '123456', 'user'); INSERT INTO `user` VALUES ('2', 'lisi', '123456', 'user'); INSERT INTO `user` VALUES ('3', 'admin', 'admin', 'admin');
3.工程中的文件源码如下:
package com.ssm.mapper; import com.ssm.pojo.User; public interface UserMapper { int insertUser(User user); User selectUser(int id); }
<?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.ssm.mapper.UserMapper"> <select id="selectUser" parameterType="int" resultType="com.ssm.pojo.User"> select * from User where id = #{id} </select> <insert id="insertUser" parameterType="com.ssm.pojo.User" useGeneratedKeys="true" keyProperty="id"> insert into User(username,password,role) values(#{username},#{password},#{role}) </insert> </mapper>
package com.ssm.pojo; import java.io.Serializable; public class User implements Serializable { private static final long serialVersionUID = -4260619761538644683L; private Integer id; private String username; private String password; private String role; public Integer getId() { return id; } public void setId(Integer 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; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } }
package com.ssm.service; import org.springframework.beans.factory.annotation.Autowired; @Service(value="userService") public class UserService { @Autowired private UserMapper userMapper; //让Spring帮助进行事务回滚 @Transactional public User register(User user){ //此处的length表示的是更改生效的行数,大于0即表示新增成功,然后user对象的id值被自动赋予新值 int length = userMapper.insertUser(user); if (length>0) { return user; }else { //新增失败,抛出异常,让spring进行事物回滚 throw new RuntimeException(); } } }
package com.ssm.web; import javax.annotation.Resource; @Namespace(value="/work") public class UserAction extends ActionSupport { private static final long serialVersionUID = 8907605561460172723L; @Resource(name="userService") private UserService userService; private User userReg; public User getUserReg() { return userReg; } public void setUserReg(User userReg) { this.userReg = userReg; } @Action(value="user", results={ @Result(name="success",location="/WEB-INF/content/success.jsp"), @Result(name="error",location="/WEB-INF/content/error.jsp") }) public String register(){ userReg = userService.register(userReg); if (userReg!=null) { return SUCCESS; }else { return ERROR; } } }
<?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/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd"> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" /> <property name="ignoreResourceNotFound" value="true" /> <property name="locations"> <list> <value>classpath*:/config.properties</value> </list> </property> </bean> <!-- 开启注解配置 --> <context:annotation-config /> <!-- 扫描service层 --> <context:component-scan base-package="com.ssm.service" /> <!-- 开启事务注解驱动 --> <tx:annotation-driven /> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="typeAliasesPackage" value="com.ssm.pojo" /> </bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </bean> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 自动扫描映射器 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.ssm.mapper" /> </bean> </beans>
#mysql version database setting jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:9906/mybatis jdbc.username=root jdbc.password=root
# Rules reminder: # DEBUG < INFO < WARN < ERROR < FATAL # Global logging configuration log4j.rootLogger=DEBUG, stdout # My logging configuration... log4j.logger.org.mybatis.jpetstore=DEBUG ## Console output... log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%5p %d %C: %m%n
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.enable.DynamicMethodInvocation" value="true" /> <constant name="struts.devMode" value="true" /> <constant name="struts.convention.package.locators" value="web" /> <constant name="struts.convention.default.parent.package" value="params-default" /> <package name="params-default" extends="convention-default"> <interceptors> <interceptor-stack name="paramsStack"> <interceptor-ref name="store"> <param name="operationMode">AUTOMATIC</param> </interceptor-ref> <interceptor-ref name="paramsPrepareParamsStack" /> </interceptor-stack> </interceptors> <default-interceptor-ref name="paramsStack" /> </package> </struts>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>注册页面</title> </head> <body> 欢迎注册,请在这里输入必要的注册信息: <s:form action="work/user!register.action" method="post"> <s:textfield name="userReg.username" label="用户名"></s:textfield> <s:password name="userReg.password" label="密码"></s:password> <s:textfield name="userReg.role" label="角色"></s:textfield> <s:submit value="提交"></s:submit> </s:form> </body> </html>
4.运行该工程,截图如下: