前言:
spring+springmvc+mybatis,称为ssm。ssm可以说是后端程序员必备技能,应该也是目前用得最多的,所以无论如何都要掌握!下面一起来看整合案例。点我下载源码。
开发环境:
1、开发工具:eclipse 4.7.3
2、maven 3.5.2
3、jdk 1.9
4、tomcat 8.5
5、mysql 5.7.21
一、项目环境搭建:
1、创建项目:
打开eclipse,file --> new --> maven project --> maven archetype webapp,然后填写好artifactId,点finish即可。若是创建maven项目失败,请参考eclipse创建maven项目失败解决方法
2、创建项目目录结构:
创建好项目以后,按照下图创建项目结构:
注意:项目刚创建出来可能只有src/main/java,自己创建其他的时候是 new source folder,而不是package。
3、添加依赖:
接下来就是添加依赖,本案例需要如下依赖:
<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.zhu</groupId>
<artifactId>ssm</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>ssm Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.14.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.3.14.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.14.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.14.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.3.14.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.14.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.14.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.14.RELEASE</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.7</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-collections/commons-collections -->
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.37</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
>> </dependencies>
<build>
<finalName>ssm</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>3.6.1</version>
</plugin>
</plugins>
</build>
</project>
4、完成各项配置:
添加好依赖之后,就来完成jdbc数据源、mybatis和spring 的配置:
jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///ssm?useUnicode=true&characterEncoding=utf8
jdbc.username=#
jdbc.password=#
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>
<!-- 使用jdbc的getGeneratedKeys获取数据库自增主键值 -->
<setting name="useGeneratedKeys" value="true" />
<!-- 使用列别名替换列名 -->
<!-- <setting name="useColumnLabel" value="true"/> -->
<!-- 开启驼峰命名转换(userId === user_id) -->
<setting name="mapUnderscoreToCamelCase" value="true" />
</settings>
<!-- 取别名,比如一个方法中返回值类型是User,
配置了这个在 parameterType属性中就不用写User的全类名,
直接写User即可,可以在这里配置,也可以再spring配置文件中配置 -->
<!-- <typeAliases> <package name="com.zhu.smm.entity"/> </typeAliases> -->
</configuration>
src/main/resource/spring下有如下三个配置文件,分别配置dao层,service层,controller层:
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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<!-- 配置整合mybatis过程 -->
<!-- 1、配置数据库相关参数properties的属性:${url} -->
<context:property-placeholder location="classpath:jdbc.properties" />
<!-- 2、配置数据库连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 配置连接池属性 -->
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<!-- c3p0连接池的私有属性 -->
<property name="maxPoolSize" value="30"/>
<property name="minPoolSize" value="10"/>
<!-- 关闭连接不自动commit -->
<property name="autoCommitOnClose" value="false"/>
<!-- 获取连接超时时间 -->
<property name="checkoutTimeout" value="10000"/>
<!-- 当获取连接失败时重试次数 -->
<property name="acquireRetryAttempts" value="2"/>
</bean>
<!-- 3、配置mybatis的sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 自动扫描mappers.xml文件 -->
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
<!-- 扫描mybatis-config文件 -->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!-- 扫描entity包,使用别名,或者在mybatis-config中配置,二选一 -->
<property name="typeAliasesPackage" value="com.zhu.ssm.entity"></property>
</bean>
<!-- 4、DAO接口所在包名,Spring会自动查找其下的类 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.zhu.ssm.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
</beans>
spring-service.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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<!-- 扫描service包下所有使用注解的类型 -->
<context:component-scan base-package="com.zhu.ssm.service"/>
<!-- 事务管理 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 开启声明式事物 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
spring-web.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"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<!-- 配置springmvc -->
<!-- 1、开启springMvc注解模式 -->
<mvc:annotation-driven />
<context:component-scan base-package="com.zhu.ssm.controller"/>
</beans>
注意:spring-web.xml中还可以配置视图解析器、文件上传器、静态资源的处理等,因为本案例未涉及这些内容,所以没有配置。
5、对web.xml进行配置
需要在web.xml中进行如下配置,让web容器能够加载到spring的配置文件:
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/spring-.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>spring-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
至此,就完成了环境的搭建了,接下来就可以进行代码的编写了!
二、分层编写代码:
1、entity层:
User.java
public class User {
private Integer userId;
private String userName;
private Integer age;
private Card card;//一个人一张身份证,1对1
private List<MobilePhone> mobilePhone;//土豪,多个手机,1对多
}
Card.java
public class Card {
private Integer cardId;
private String cardNum;//身份证号
private String address;//地址
}
MobilePhone.java
public class MobilePhone {
private Integer mobilePhoneId;
private String brand;//品牌
private double price;//价格
private User user;//主人
}
注意:以上实体类均省略了set和get方法。
2、数据库设计:
借助数据库客户端工具navicat进行数据库以及表的创建。
tb_mobile_phone中以user_id作为外键关联tu_user,tb_user中以card_id作为外键关联tb_card。
3、dao层:
UserDao.java
/**
* 带条件分页查询:
* 可输入的条件:名字(模糊),cardId,age,
* @param userCondition 把条件封装成一个user对象
* @param rowIndex 表示从第几行开始取数据
* @param pageSize 表示要返回多少行数据
* @return 返回user列表
*/
List<User> queryUserList(@Param("userCondition") User userCondition, @Param("rowIndex") int rowIndex,
@Param("pageSize") int pageSize);
UserDao.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.zhu.ssm.dao.UserDao">
<resultMap type="User" id="userMap">
<id property="userId" column="user_id"/>
<result property="userName" column="user_name"/>
<result property="age" column="age"/>
<association property="card" column="card_id" javaType="Card">
<id property="cardId" column="card_id"/>
<result property="cardNum" column="card_num"/>
<result property="address" column="address"/>
</association>
<collection property="mobilePhone" column="user_id" ofType="MobilePhone">
<id column="mobile_phone_id" property="mobilePhoneId" />
<result column="brand" property="brand" />
<result column="price" property="price" />
</collection>
</resultMap>
<!-- 带条件分页查询 -->
<select id="queryUserList" resultMap="userMap">
SELECT
u.user_name,u.age,u.card_id,c.card_num,c.address,m.brand,m.price
FROM
tb_user u,tb_card c,tb_mobile_phone m
<where>
<if
test="userCondition.card != null
and
userCondition.card.cardId != null">
and u.card_id =
#{userCondition.card.cardId}
</if>
<if test="userCondition.userName != null">
and u.user_name like '%${userCondition.userName}%'
</if>
<if test="userCondition.age != null">
and u.age = #{userCondition.age}
</if>
AND
u.card_id = c.card_id
AND
u.user_id = m.user_id
</where>
LIMIT #{rowIndex},#{pageSize}
</select>
</mapper>
dao层的带条件分页查询用到了mybatis的动态sql,对动态sql不熟悉的请参考:mybatis笔记整理
养成良好习惯,写完dao应该做个Junit测试:
BaseTest.java
/**
* 初始化spring各项配置的
* @author zhu
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:spring/spring-dao.xml","classpath:spring/spring-service.xml"})
public class BaseTest {
}
注意:BaseTest.java是用来加载spring配置文件的。
UserDaoTest.java
public class UserDaoTest extends BaseTest {
@Autowired
private UserDao userDao;
@Test
public void testQueryUserList() {
User userCondition = new User();
/*Card c = new Card();
c.setCardId(2);
userCondition.setCard(c);*/
//userCondition.setAge(22);
userCondition.setUserName("菲");
List<User> ul = userDao.queryUserList(userCondition, 1, 99);
for(User user : ul) {
System.out.println(user.getUserName());
/*List<MobilePhone> list = new ArrayList<>();
list = user.getMobilePhone();
for(MobilePhone mp : list) {
System.out.println(mp.getBrand());
}*/
}
}
}
userCondition设置了userName一个"菲"字,就是模糊查询名字中带"菲"字的用户。
先看数据库表中的数据:
数据表中名字带"菲"字的用户只有"刘亦菲",正常运行的话应该输出"刘亦菲"。
再看运行结果:
在控制台输出了"刘亦菲",符合预期,测试通过。
4、service层:
UserService.java
public interface UserService {
/**
* 带条件分页查询:
* 可输入的条件:名字(模糊),cardId,age,
* @param userCondition 把条件封装成一个user对象
* @param rowIndex 表示从第几行开始取数据
* @param pageSize 表示要返回多少行数据
* @return 返回user列表
/
List<User> queryUserList(@Param("userCondition") User userCondition, @Param("rowIndex") int rowIndex,
@Param("pageSize") int pageSize);
}
UserServiceImpl.java
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public List<User> queryUserList(User userCondition, int rowIndex, int pageSize) {
// TODO Auto-generated method stub
return userDao.queryUserList(userCondition, rowIndex, pageSize);
}
}
由于service层只是简单的调用了dao层,这里不再做Junit测试。
5、controller层:
UserController.java
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value = "/listusers", method = RequestMethod.GET)
@ResponseBody
public Map<String, Object> listUsers() {
Map<String, Object> modelMap = new HashMap<>();
User userCondition = new User();
List<User> userList = userService.queryUserList(userCondition, 1, 99);
modelMap.put("userList", userList);
return modelMap;
}
}
至此,已完成所有代码。接下来,在浏览器输入:localhost:8080/ssm/user/listusers
在页面就可以看到访问结果了:
注意:
图片中有几个值为null,是因为查询UserDao.xml中写查询语句时并没有查这几个字段,自己加上就行了。
总结:
常见问题:
1、做测试的时候一定要在BaseTest中加载spring 配置文件,其他test在继承BaseTest。
2、一定不要忘记web.xml中的配置,且路径一定要写对,否则web容器加载不到spring 配置文件,访问controller时会报404错误。
3、由于tb_user中的card_id作为外键关联了tb_card,所以为user设置card时,cardId一定得是tb_card中存在的,否则会报错,user_id也是tb_mobile_phone的外键,同样的道理。