ssm框架之Spring和Mybatis整合(适合新手)
2018-02-11 16:54
447 查看
最近刚学习完ssm框架,找了个项目熟悉下整合的步骤,大概是spring和mybatis先整合,之后是mybatis和springmvc的整合,这里先讲spring和mybatis的整合,已备今后的学习。
一、搭建开发环境
首先在IDEA中创建maven项目(以ecplise为例)
创建中的Group id等看情况填写即可,图中为本人的配置。
创建好的工程目录如下
如果遇到创建好的工程中没有src/main/java以及test目录等,需要右击该项目,选择Build Path中的Configure Build Path,在JRE Library选相框中Remove掉JRE再重新添加即可,如下图
接着就是pom.xml文件了
二、创建数据库和表(针对MySQL)
sql创建语句如下
创建好的数据库和表如下:
三、使用generator工具生成代码
这里我们使用generator工具生成数据库对应的pojo,如果不会使用generator,可以看我的前一篇文章。具体的generatorConfig.xml配置如下
生成后的实体类
生成后的dao类
生成后的mapper文件
四、spring和mybaits的具体配置
注意下面的配置文件都是放在resources目录中
首先是db.properties的配置
接下是spring.xml,我是放在resources/spring/spring.xml中的
然后是spring-dao.xml的配置
五、进行单元测试
经过以上的四个步骤,srping和mybatis基本整合完成,接下来进行单元测试
首先创建com.ssm.service包,并在下面创建UserServiceI接口,代码如下
接着创建一个com.smm.service.impl包,在包内创建一个针对UserServiceI接口的实现类:UserServiceImpl,代码如下
最后在src/test/java目录下创建com.ssm.test测试包,并在里面创建MybatisTest测试类,代码如下
运行该测试类,成功运行
如果遇到项目出错,首先检查之前的配置是否正确,然后右击pom.xml文件,DEBUG AS-MAVEN INSTALL,出现下图结果后再次尝试运行
到这里整合完毕,遇到任何问题欢迎留言讨论
一、搭建开发环境
首先在IDEA中创建maven项目(以ecplise为例)
创建中的Group id等看情况填写即可,图中为本人的配置。
创建好的工程目录如下
如果遇到创建好的工程中没有src/main/java以及test目录等,需要右击该项目,选择Build Path中的Configure Build Path,在JRE Library选相框中Remove掉JRE再重新添加即可,如下图
接着就是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>me.gacl</groupId> <artifactId>spring4-mybatis3</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>spring4-mybatis3</name> <url>http://maven.apache.org</url> <dependencies> <!-- 添加Spring-core包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <vers 4000 ion>4.1.4.RELEASE</version> </dependency> <!-- 添加spring-context包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.1.4.RELEASE</version> </dependency> <!-- 添加spring-tx包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.1.4.RELEASE</version> </dependency> <!-- 添加spring-jdbc包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.1.4.RELEASE</version> </dependency> <!-- 为了方便进行单元测试,添加spring-test包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.1.4.RELEASE</version> </dependency> <!--添加spring-web包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.1.4.RELEASE</version> </dependency> <!--添加aspectjweaver包 --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.5</version> </dependency> <!-- 添加mybatis的核心包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.8</version> </dependency> <!-- 添加mybatis与Spring整合的核心包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> <!-- 添加servlet3.0核心包 --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.2-b01</version> </dependency> <!-- jstl --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- 添加mysql驱动包 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.34</version> </dependency> <!-- 添加druid连接池包 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.12</version> </dependency> <!-- 添加junit单元测试包 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> </dependencies> <build> <finalName>spring4-mybatis3</finalName> </build> </project>
二、创建数据库和表(针对MySQL)
sql创建语句如下
Create DATABASE ssm; USE ssm; DROP TABLE IF EXISTS t_user; CREATE TABLE t_user ( user_id char(32) NOT NULL, user_name varchar(30) DEFAULT NULL, user_birthday date DEFAULT NULL, user_salary double DEFAULT NULL, PRIMARY KEY (user_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
创建好的数据库和表如下:
三、使用generator工具生成代码
这里我们使用generator工具生成数据库对应的pojo,如果不会使用generator,可以看我的前一篇文章。具体的generatorConfig.xml配置如下
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <context id="DB2Tables" targetRuntime="MyBatis3"> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1:3306/ssm" userId="root" password=""> </jdbcConnection> <javaTypeResolver > <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <javaModelGenerator targetPackage="com.ssm.domain" targetProject="./src"> <property name="enableSubPackages" value="false" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <sqlMapGenerator targetPackage="com.ssm.mapping" targetProject="./src"> <property name="enableSubPackages" value="false" /> </sqlMapGenerator> <javaClientGenerator type="XMLMAPPER" targetPackage="com.ssm.dao" targetProject="./src"> <property name="enableSubPackages" value="false" /> </javaClientGenerator> <table tableName="t_user"></table> </context> </generatorConfiguration>
生成后的实体类
package com.ssm.domain; import java.util.Date; public class User { private String userId; private String userName; private Date userBirthday; private Double userSalary; public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId == null ? null : userId.trim(); } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName == null ? null : userName.trim(); } public Date getUserBirthday() { return userBirthday; } public void setUserBirthday(Date userBirthday) { this.userBirthday = userBirthday; } public Double getUserSalary() { return userSalary; } public void setUserSalary(Double userSalary) { this.userSalary = userSalary; } }
生成后的dao类
package com.ssm.dao; import com.ssm.domain.User; public interface UserMapper { int deleteByPrimaryKey(String userId); int insert(User record); int insertSelective(User record); User selectByPrimaryKey(String userId); int updateByPrimaryKeySelective(User record); int updateByPrimaryKey(User record); }
生成后的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.ssm.dao.UserMapper" > <resultMap id="BaseResultMap" type="com.ssm.domain.User" > <id column="user_id" property="userId" jdbcType="CHAR" /> <result column="user_name" property="userName" jdbcType="VARCHAR" /> <result column="user_birthday" property="userBirthday" jdbcType="DATE" /> <result column="user_salary" property="userSalary" jdbcType="DOUBLE" /> </resultMap> <sql id="Base_Column_List" > user_id, user_name, user_birthday, user_salary </sql> <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.String" > select <include refid="Base_Column_List" /> from t_user where user_id = #{userId,jdbcType=CHAR} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.String" > delete from t_user where user_id = #{userId,jdbcType=CHAR} </delete> <insert id="insert" parameterType="com.ssm.domain.User" > insert into t_user (user_id, user_name, user_birthday, user_salary) values (#{userId,jdbcType=CHAR}, #{userName,jdbcType=VARCHAR}, #{userBirthday,jdbcType=DATE}, #{userSalary,jdbcType=DOUBLE}) </insert> <insert id="insertSelective" parameterType="com.ssm.domain.User" > insert into t_user <trim prefix="(" suffix=")" suffixOverrides="," > <if test="userId != null" > user_id, </if> <if test="userName != null" > user_name, </if> <if test="userBirthday != null" > user_birthday, </if> <if test="userSalary != null" > user_salary, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides="," > <if test="userId != null" > #{userId,jdbcType=CHAR}, </if> <if test="userName != null" > #{userName,jdbcType=VARCHAR}, </if> <if test="userBirthday != null" > #{userBirthday,jdbcType=DATE}, </if> <if test="userSalary != null" > #{userSalary,jdbcType=DOUBLE}, </if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="com.ssm.domain.User" > update t_user <set > <if test="userName != null" > user_name = #{userName,jdbcType=VARCHAR}, </if> <if test="userBirthday != null" > user_birthday = #{userBirthday,jdbcType=DATE}, </if> <if test="userSalary != null" > user_salary = #{userSalary,jdbcType=DOUBLE}, </if> </set> where user_id = #{userId,jdbcType=CHAR} </update> <update id="updateByPrimaryKey" parameterType="com.ssm.domain.User" > update t_user set user_name = #{userName,jdbcType=VARCHAR}, user_birthday = #{userBirthday,jdbcType=DATE}, user_salary = #{userSalary,jdbcType=DOUBLE} where user_id = #{userId,jdbcType=CHAR} </update> </mapper>
四、spring和mybaits的具体配置
注意下面的配置文件都是放在resources目录中
首先是db.properties的配置
driverClassName=com.mysql.jdbc.Driver validationQuery=SELECT 1 jdbc_url=jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull jdbc_username=root jdbc_password=
接下是spring.xml,我是放在resources/spring/spring.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: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/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- 引入数据库配置文件 --> <context:property-placeholder location="classpath:db.properties"></context:property-placeholder> <!-- 扫描生成的接口类中的注释 --> <context:component-scan base-package="com.ssm.service"></context:component-scan> </beans>
然后是spring-dao.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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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"> <!-- 连接池,数据源的配置 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="url" value="${jdbc_url}"></property> <property name="username" value="${jdbc_username}"></property> <property name="password" value="${jdbc_password}"></property> <!-- 初始化连接大小 --> <property name="initialSize" value="0" /> <!-- 连接池最大使用连接数量 --> <property name="maxActive" value="20" /> <!-- 连接池最大空闲 --> <property name="maxIdle" value="20" /> <!-- 连接池最小空闲 --> <property name="minIdle" value="0" /> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="60000" /> <!-- <property name="poolPreparedStatements" value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="33" /> --> <property name="validationQuery" value="${validationQuery}" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <property name="testWhileIdle" value="true" /> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000" /> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="25200000" /> <!-- 打开removeAbandoned功能 --> <property name="removeAbandoned" value="true" /> <!-- 1800秒,也就是30分钟 --> <property name="removeAbandonedTimeout" value="1800" /> <!-- 关闭abanded连接时输出错误日志 --> <property name="logAbandoned" value="true" /> <!-- 监控数据库 --> <!-- <property name="filters" value="stat" /> --> <property name="filters" value="mergeStat" /> </bean> <!-- 配置sqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 用于之后实例化sqlSessionFactory --> <property name="dataSource" ref="dataSource"></property> <!-- 扫描com.smm.mapping包中的mapper配置文件 --> <property name="mapperLocations" value="classpath:com/ssm/mapping/*.xml"></property> </bean> <!-- 配置扫描器 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 扫描me.gacl.dao这个包以及它的子包下的所有映射接口类 --> <property name="basePackage" value="com.ssm.dao"></property> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!-- 配置Spring的事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 拦截器方式配置事物 --> <tx:advice id="transactionAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="append*" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="modify*" propagation="REQUIRED" /> <tx:method name="edit*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="remove*" propagation="REQUIRED" /> <tx:method name="repair" propagation="REQUIRED" /> <tx:method name="delAndRepair" propagation="REQUIRED" /> <tx:method name="get*" propagation="SUPPORTS" /> <tx:method name="find*" propagation="SUPPORTS" /> <tx:method name="load*" propagation="SUPPORTS" /> <tx:method name="search*" propagation="SUPPORTS" /> <tx:method name="datagrid*" propagation="SUPPORTS" /> <tx:method name="*" propagation="SUPPORTS" /> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="transactionPointcut" expression="execution(* me.gacl.service..*Impl.*(..))" /> <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" /> </aop:config> </beans>
五、进行单元测试
经过以上的四个步骤,srping和mybatis基本整合完成,接下来进行单元测试
首先创建com.ssm.service包,并在下面创建UserServiceI接口,代码如下
package com.ssm.service; import com.ssm.domain.User; public interface UserServiceI { void addUser(User user); User findUserById(String user_id); }
接着创建一个com.smm.service.impl包,在包内创建一个针对UserServiceI接口的实现类:UserServiceImpl,代码如下
package com.ssm.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ssm.dao.UserMapper; import com.ssm.domain.User; import com.ssm.service.UserServiceI; @Service("userService") public class UserServiceImpl implements UserServiceI { @Autowired private UserMapper userMapper; @Override public void addUser(User user) { userMapper.insert(user); } @Override public User findUserById(String user_id) { return userMapper.selectByPrimaryKey(user_id); } }
最后在src/test/java目录下创建com.ssm.test测试包,并在里面创建MybatisTest测试类,代码如下
package com.ssm.test; import java.util.Date; import org.junit.Before; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.ssm.domain.User; import com.ssm.service.UserServiceI; public class MybatisTest { private UserServiceI userService; @Before public void setUp() { ApplicationContext bean =new ClassPathXmlApplicationContext(new String[] {"classpath:spring/spring.xml","classpath:spring/spring-dao.xml"}); userService = (UserServiceI) bean.getBean("userService"); } @Test public void testAddUser() { User user = new User(); user.setUserId("3"); user.setUserBirthday(new Date()); user.setUserName("gatsby"); user.setUserSalary(10000.0); userService.addUser(user); } }
运行该测试类,成功运行
如果遇到项目出错,首先检查之前的配置是否正确,然后右击pom.xml文件,DEBUG AS-MAVEN INSTALL,出现下图结果后再次尝试运行
到这里整合完毕,遇到任何问题欢迎留言讨论
相关文章推荐
- [新手-图文]整合ssm框架,从mybatis到spring+mybatis再到ssm(sping+mybatis+spingmvc),数据库mysql
- SSM框架——详细整合教程(Spring+SpringMVC+MyBatis)
- SSM框架——详细整合教程(Spring+SpringMVC+MyBatis)
- SSM框架——详细整合教程(Spring+SpringMVC+MyBatis)
- SSM框架——详细整合教程(Spring+SpringMVC+MyBatis)
- SSM框架——详细整合教程(Spring+SpringMVC+MyBatis+Maven)
- SSM(Spring+SpringMVC+Mybatis)框架整合配置方法
- SSM框架——详细整合教程(Spring+SpringMVC+MyBatis)
- SSM框架——详细整合教程(Spring+SpringMVC+MyBatis) (转载)
- SSM框架——详细整合教程(Spring+SpringMVC+MyBatis)
- SSM框架——详细整合教程(Spring+SpringMVC+MyBatis)
- SSM框架——详细整合教程(Spring+SpringMVC+MyBatis)
- SSM框架——详细整合教程(Spring+SpringMVC+MyBatis)
- SSM框架——详细整合教程(Spring+SpringMVC+MyBatis)
- SSM(Spring+SpringMVC+MyBatis)三大框架整合及遇到的各种问题
- Maven学习笔记(五)-Maven整合SSM(spring+springMVC+Mybatis)框架
- SSM框架——详细整合教程(Spring+SpringMVC+MyBatis)
- Eclipse+Tomcat+MAVEN+SVN项目完整环境搭建+SSM框架——详细整合教程(Spring+SpringMVC+MyBatis)
- SSM框架——详细整合教程(Spring+SpringMVC+MyBatis)
- SSM框架——详细整合教程(Spring+SpringMVC+MyBatis)