一、配置maven的pom.xml加载jar包
为了后续开发的方便,将SSM框架所有需要的jar包一并加载进来
-
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>com.ustc.finance</groupId>
<artifactId>USTC</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>USTC Maven Webapp</name>
<url>http://maven.apache.org</url><properties> <!-- spring release number --> <spring.version>4.3.2.RELEASE</spring.version> <!-- log4j release number --> <slf4j.version>1.7.21</slf4j.version> <log4j.version>1.2.16</log4j.version> <!-- junit release number --> <junit.version>4.12</junit.version> <!-- mybatis release number --> <mybatis.version>3.4.1</mybatis.version> <!-- mybatis-spring release number --> <mybatis-spring.version>1.3.0</mybatis-spring.version> </properties> <dependencies> <!-- junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <!--mysql driver--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> <!--jsp--> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.1</version> </dependency> <!-- log management --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!-- mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!-- mybatis-spring dependency --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatis-spring.version}</version> </dependency> <!-- spring dependency --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <!-- spring unit test dependency --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> <scope>test</scope> </dependency> </dependencies> <build> <finalName>USTC</finalName> </build> </project>
配置好pom.xml之后右键单击工程名:Runs As ->Maven Install 将这些jar包下载至之前配置好的本地仓库
二、创建实体类
此处与Hibernate中实体类相同,都是按照ORM思想将类与数据库中的表做一对一的映射,类名与表名对应、类中 成员变量与表中字段名对应、表中的一对多关系在类中表现为组合关系(一对多时在类中添加Set或者List集合,多对一时在类中添加相应的对象),如图所示(User与StockComment就是一对多的关系):
当类中存在TreeSet时需要实现Comparable接口并重写compareTo方法(方便TreeSet集合进行排序)。之后自动生成成员变量的Get和Set方法。
三、创建实体类对应的Dao
Dao中主要定义一些基本的数据库访问操作如CRUD,此处注意Dao只是接口,而不是类。而且在Mybati中Dao不需要用类实现,而是通过配置映射文件Mapping.xml来实现Dao接口。
public interface UserDao {
/**
* Select from t_user by userID
* @param userID
* @return
*/
public User selectUserByID(int userID);
/**
* Select from t_user by userName
* @param userName
* @return
*/
public User selectUserByName(String userName);
/**
* Insert a record in t_user
* @param user
* @return
*/
public int addUser(User user);
/**
* Update a record in t_user
* @param user
* @return
*/
public int updateUser(User user);
/**
* Delete a record in t_user that dependents on the userID
* @param userID
* @return
*/
public int deleteUserByID(int userID);
}
四、配置Dao对应的实现UserMapping.xml
<?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.ustc.finance.dao.UserDao">
<resultMap type="com.ustc.finance.entity.User" id="userResultMap">
<id column="userID" jdbcType="INTEGER" property="userID"/>
<result column="userName" jdbcType="VARCHAR" property="userName"/>
<result column="userPassword" jdbcType="VARCHAR" property="userPassword"/>
<result column="userRealName" jdbcType="VARCHAR" property="userRealName"/>
<result column="userEmail" jdbcType="VARCHAR" property="userEmail"/>
<result column="userGender" jdbcType="VARCHAR" property="userGender"/>
<result column="userFinance" jdbcType="DOUBLE" property="userFinance"/>
<!-- 个股评论的一对多的关系 -->
<!-- property: 指的是集合属性的值, ofType:指的是集合中元素的类型 -->
<collection property="stockComments" ofType="com.ustc.finance.entity.StockComment"
select="com.ustc.finance.dao.StockCommentDao.selectStockCommentByID" column="stockCommentID">
</collection>
<!-- 个股交易的一对多的关系 -->
<collection property="stockTransactions" ofType="com.ustc.finance.entity.StockTransaction"
select="com.ustc.finance.dao.StockTransactionDao.selectStockTransactionByID" column="stockTransactionID">
</collection>
</resultMap>
<!-- 查询单条记录 -->
<select id="selectUserByID" parameterType="int" resultMap="userResultMap">
SELECT * FROM t_user
<where>
<if test="_parameter !=null and _parameter != ''">
AND userID = #{userID, jdbcType = INTEGER}
</if>
</where>
</select>
<!-- 通过用户名查询 -->
<select id="selectUserByName" parameterType="java.lang.String" resultMap="userResultMap">
SELECT * FROM t_user
<where>
<if test="_parameter !=null and _parameter != ''">
AND userName = #{userName, jdbcType = VARCHAR}
</if>
</where>
</select>
<!-- 添加用户记录 -->
<insert id="addUser" parameterType="com.ustc.finance.entity.User" useGeneratedKeys="true" keyProperty="userID">
INSERT INTO t_user (userName, userPassword, userRealName, userPhone, userEmail, userGender, userFinance)
VALUES (#{userName}, #{userPassword}, #{userRealName}, #{userPhone}, #{userEmail}, #{userGender}, #{userFinance})
</insert>
<!-- 更新用户记录 -->
<update id="updateUser" parameterType="com.ustc.finance.entity.User">
UPDATE t_user SET userName = #{userName}, userPassword = #{userPassword},
userRealName = #{userRealName}, userPhone = #{userPhone}, userEmail = #{userEmail},
userGender = #{userGender}, userFinance = #{userFinance} WHERE userID = #{userID}
</update>
<!-- 删除用户记录 -->
<delete id="deleteUserByID" parameterType="int">
DELETE FROM t_user WHERE userID = #{userID}
</delete>
</mapper>
- 在MyBatis中所有的数据库访问操作都需要我们自己实现SQL,这样就可以拥有更高的管理权限和更多的灵活性,可以精确地控制到每一次数据库访问,减少不必要的依赖操作。
<resultMap>标签定义了查询返回结果的存储格式,一般情况下是为实体类中的成员变量与数据库表中的字段做对应,其中column属性的值是数据库字段名,property的值是类中对应的成员变量名,resultMap中的id方便在下面进行查询时指明返回结果使用哪一个resultMap进行存储
当使用MyBatis处理一对多关系时,首先在resultMap中声明关系(一对多的关系使用collection 声明,多对一的关系使用association声明)如下:
<association property="user" javaType="com.ustc.finance.entity.User"
select="com.ustc.finance.dao.UserDao.selectUserByID" column="userID">
</association>首先说明collection :其中的property是指实体类中的集合变量名(TreeSet),ofType指明集合变量(TreeSet)的类型,select指明可以使用哪一个select语句查询出关联对象,column指明关联对象的主键(这里填数据库中的字段名)
然后说明一下association:其实与collection 大同小异,只是ofType换成了javaType
这里需要额外说明一下,在我的测试之下MyBatis不会自动的帮你联表查询,想要实现联表查询的话要么在SQL中直接查两个表,要么自己想一下替代的策略。我所使用的策略是:对于多对一关系,由于每个对象中只存放一条关联数据(比如StockComment中只存放有一个User类的对象),查询起来比较方便,因此在StockComment的所有查询SQL中一并将User查出来;对于一对多关系,由于每个对象中存放有多条关联数据(比如User中存放了一个TreeSet类型的StockComment,存放了一个对象集合),查询起来过于复杂而且容易存在冗余查询(即只需要User自身的信息,但关联查询出了多余的Stock信息),因此我在处理一对多关系时“一”的一方(User)只查询自身表的内容,“多”的一方(StockComment)增加根据userID查询的接口
public TreeSet<StockComment> selectStockCommentByUserID(@Param("userID") int userID);
这样当需要查询某个user对应的stockComment时使用该方法就可以实现。然后说明一下SQL标签<select>、<insert>、<update>、<delete>等,这些都大同小异。标签id要与Dao中的方法名对应,parameterType指明Dao中方法参数的类型,resultMap指明select语句返回查询结果时以哪种格式存储,useGeneratedKeys设置为true时指明数据库中的主键是自增模式,并且在后面keyProperty指明主键名称
五、创建Dao对应的Service
-
UserService
package com.ustc.finance.service;
import com.ustc.finance.entity.User;
public interface UserService {
/**
* Select from t_user by userID
* @param userID
* @return
/
User selectUserByID(int userID);
/*
* Select from t_user by userName
* @param userName
* @return
/
User selectUserByName(String userName);
/*
* Checkout if the userName is available
* @param userName
* @return
/
Boolean checkUserName(String userName);
/*
* Checkout if the login action is success
* @param userName
* @param password
* @return
*/
Boolean loginCheck(String userName, String password);/** * Insert a record in t_user * @param user * @return */ int addUser(User user); /** * Update a record in t_user * @param user * @return */ int updateUser(User user); /** * Delete a record in t_user that dependents on the userID * @param userID * @return */ int deleteUserByID(int userID); }
UserService与UserDao大同小异,主要是在UserDao的基础上再定义一些针对项目所需要的接口如checkUserName与loginCheck
六、创建UserServiceImpl实现UserService接口
-
UserServiceImpl
package com.ustc.finance.serviceimpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ustc.finance.dao.UserDao;
import com.ustc.finance.entity.User;
import com.ustc.finance.service.UserService;
@Service("UserService")
public class UserServiceImpl implements UserService {@Autowired private UserDao userDao; @Override public User selectUserByID(int userID) { return userDao.selectUserByID(userID); } @Override public User selectUserByName(String userName) { return userDao.selectUserByName(userName); } @Override public Boolean checkUserName(String userName) { Boolean ret = false; User user = userDao.selectUserByName(userName); if(user != null) ret = false; else ret = true; return ret; } @Override public Boolean loginCheck(String userName, String password) { Boolean ret = false; User user = userDao.selectUserByName(userName); if(user == null) ret = false; else if(!(user.getUserPassword().equals(password))) ret = false; else ret = true; return ret; } @Override public int addUser(User user) { return userDao.addUser(user); } @Override public int updateUser(User user) { return userDao.updateUser(user); } @Override public int deleteUserByID(int userID) { return userDao.deleteUserByID(userID); } }
在类上边加Service注解标注该类实现的哪一个Service。然后使用注解Autowired自动注入一个UserDao的对象。之后实现UserService接口中定义的方法。
七、MyBatis与Spring配置文件
-
MyBatis配置文件mybatis-config.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> <!-- 开启延迟加载 --> <settings> <!-- lazyLoadingEnabled:延迟加载启动,默认是false --> <setting name="lazyLoadingEnabled" value="false"/> <!-- aggressiveLazyLoading:积极的懒加载,false的话按需加载,默认是true --> <setting name="aggressiveLazyLoading" value="false"/> </settings> </configuration>
-
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-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"><!-- 加载配置文件 --> <!-- 将多个配置文件读取到容器中,交给Spring管理 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:jdbc.properties</value> </list> </property> </bean> <!-- 自动扫描dao和service包(自动注入) --> <context:component-scan base-package="com.ustc.finance.serviceimpl" /> </beans>
-
Spring与MyBatis整合配置文件spring-mybatis.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-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd"><!-- 配置数据源 --> <bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </bean> <!-- 配置MyBatis session工厂 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 加载全局的配置文件 --> <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"></property> <!-- 自动扫描mapping.xml文件 --> <property name="mapperLocations" value="classpath:com/ustc/finance/mapping/*.xml"></property> </bean> <!-- 自动扫描了所有的XxxxMapper.xml对应的mapper接口文件, 这样就不用一个一个手动配置Mpper的映射了,只要Mapper接口类和Mapper映射文件对应起来就可以了。 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.ustc.finance.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!-- (事务管理)transaction manager --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 第一种方式: 注解方式配置事物 --> <!-- <tx:annotation-driven transaction-manager="transactionManager" /> --> <!-- 第二种方式: 拦截器方式配置事物 --> <tx:advice id="transactionAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="add*" propagation="REQUIRED" rollback-for="java.lang.Exception"/> <tx:method name="update*" propagation="REQUIRED" rollback-for="java.lang.Exception"/> <tx:method name="delete*" propagation="REQUIRED" rollback-for="java.lang.Exception"/> <tx:method name="check*" propagation="SUPPORTS" rollback-for="java.lang.Exception"/> <tx:method name="login*" propagation="SUPPORTS" rollback-for="java.lang.Exception"/> <tx:method name="select*" propagation="SUPPORTS" rollback-for="java.lang.Exception"/> <tx:method name="find*" propagation="SUPPORTS" rollback-for="java.lang.Exception"/> <tx:method name="load*" propagation="SUPPORTS" rollback-for="java.lang.Exception"/> <tx:method name="search*" propagation="SUPPORTS" rollback-for="java.lang.Exception"/> <tx:method name="*" propagation="REQUIRED" rollback-for="java.lang.Exception"/> </tx:attributes> </tx:advice> <!-- Spring AOP config 解释一下 (* com.evan.crm.service.*.*(..)) 中几个通配符的含义: --> <!-- 第一个 * —— 通配 任意返回值类型 --> <!-- 第二个 * —— 通配 包com.evan.crm.service下的任意class --> <!-- 第三个 * —— 通配包com.evan.crm.service下的任意class的任意方法 --> <!-- 第四个 .. —— 通配 方法可以有0个或多个参数 --> <!-- 事务控制位置,一般在业务层service --> <aop:config> <aop:pointcut id="transactionPointcut" expression="execution(* com.ustc.finance.serviceimpl.*Impl.*(..))" /> <!-- 多个 expression="(execution(* com.weixin.web.service..*Impl.*(..)))or(execution(* org.weixin.service..*Impl.*(..)))" --> <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" /> </aop:config> </beans>
数据库相关配置jdbc.properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ustc_finance?useUnicode=true&characterEncoding=UTF-8&useSSL=false
jdbc.username=root
jdbc.password=123456-
日志文件相关配置log4j.properties
log4j.rootLogger=DEBUG,Console,Stdout#Console log4j.appender.Console=org.apache.log4j.ConsoleAppender log4j.appender.Console.layout=org.apache.log4j.PatternLayout log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n log4j.logger.java.sql.ResultSet=INFO log4j.logger.org.apache=INFO log4j.logger.java.sql.Connection=DEBUG log4j.logger.java.sql.Statement=DEBUG log4j.logger.java.sql.PreparedStatement=DEBUG log4j.appender.Stdout = org.apache.log4j.DailyRollingFileAppender log4j.appender.Stdout.File = D\:\\Java\\MyEclipse2017\\MyEclipse\\JavaFiles\\USTC_Finance\\src\\main\\resources\\log\\log.log log4j.appender.Stdout.Append = true log4j.appender.Stdout.Threshold = DEBUG log4j.appender.Stdout.layout = org.apache.log4j.PatternLayout log4j.appender.Stdout.layout.ConversionPattern =%-d{yyyy-MM-dd HH\:mm\:ss} [ %t\:%r ] - [ %p ] %m%n
八、编写测试类
-
先创建一个测试基类,配置一些东西方便以后的测试类通用:
package MyBatisTest;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;@ContextConfiguration(locations = {"classpath:spring.xml", "classpath:spring-mybatis.xml"}) @RunWith(SpringJUnit4ClassRunner.class) public abstract class BaseTest extends AbstractJUnit4SpringContextTests { }
-
创建User测试类
package MyBatisTest;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import com.ustc.finance.entity.User;
import com.ustc.finance.service.UserService;public class UserTest extends BaseTest { @Autowired private UserService userService; Logger logger = Logger.getLogger(UserTest.class); @Test public void selectByIdTest(){ User user = userService.selectUserByID(3); logger.debug("\n\n用户查询结果: " + user.getUserName()+user.getUserRealName()+"\n\n"); } @Test public void selectByNameTest(){ String userName = "aaa"; User user = userService.selectUserByName(userName); logger.debug("\n\n用户查询结果: " + user+"\n\n"); } @Test public void checkUserNameTest(){ String userName = "test"; Boolean result = userService.checkUserName(userName); if(result) logger.debug("\n\n用户名校验结果: 该用户名可以使用\n\n"); else logger.debug("\n\n用户名校验结果: 该用户名已被其他人使用\n\n"); } @Test public void loginCheckTest(){ Boolean result = userService.loginCheck("docki", "8888"); if(result) logger.debug("\n\n用户登录验证: 登录成功\n\n"); else logger.debug("\n\n用户登录验证: 登录失败\n\n"); } }
-
Autowired注解是Spring中的注解,用于自动注入,当程序运行时需要用到userService时,Spring会帮我们自动创建一个userService对象供我们使用。Test注解是Junit注解,用于标注测试方法。logger.debug帮助我们打印测试方法的执行结果。测试类的运行方法:选中需要运行的测试方法名,右键->Run As ->Junit 。测试通过则证明项目后台与数据库已经连通!