SSM框架整合
导入依赖
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>xm</groupId>
<artifactId>ssm</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- spring所需的包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.7.RELEASE</version>
</dependency>
<!-- mybatis所需的包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.7</version>
</dependency>
<!-- mybatis和spring整合的包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.1</version>
</dependency>
<!-- mysql驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
<!-- 数据库连接池 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.4</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.5.0-RC2</version>
<scope>test</scope>
</dependency>
</dependencies>
<!-- 逆向工程maven插件 -->
<build>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.7</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>
创建mybatis逆向工程
generatorConfig.xml
会自动创建mapper.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="mysqlTable" targetRuntime="MyBatis3">
<commentGenerator>
<!-- 是否去除自动生成的注释-->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!--数据库配置-->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/sm?useSSL=false"
userId="root"
password="zm19980225">
</jdbcConnection>
<!-- 数据库类型与java类型转换
当属性为false或未指定时,默认Java类型解析器将尝试通过替换Integral类型(如果可能)来使JDBC DECIMAL和NUMERIC类型更易于使用。
替代规则如下:
如果比例大于零,或者长度大于18,则将使用java.math.BigDecimal类型
如果比例为零,并且长度为10到18,那么Java类型解析器将替换java.lang.Long。
如果比例为零,并且长度为5到9,那么Java类型解析器将替换java.lang.Integer。
如果比例为零,并且长度小于5,那么Java类型解析器将替换java.lang.Short。-->
<javaTypeResolver >
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- 生成Model类存放位置 -->
<javaModelGenerator targetPackage="com.xm.pojo" targetProject="src/main/java">
<!-- 是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="true" />
<!-- 从数据库返回的值被清理前后的空格 -->
<property name="trimStrings" value="false" />
</javaModelGenerator>
<!-- 生成映射文件存放位置 -->
<sqlMapGenerator targetPackage="com.xm.mapper" targetProject="src/main/java">
<!-- 是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- <!– 生成Dao类存放位置 –>-->
<!-- <javaClientGenerator type="XMLMAPPER" targetPackage="com.xm.dao" targetProject="src/main/java">-->
<!-- <property name="enableSubPackages" value="true" />-->
<!-- </javaClientGenerator>-->
<!-- 生成对应表及类名 -->
<!-- 指定是否需要生成xxxbyExample的mapper -->
<table tableName="users" domainObjectName="User"
enableCountByExample="false"
enableDeleteByExample="false"
enableSelectByExample="false"
enableUpdateByExample="false"
></table>
</context>
</generatorConfiguration>
运行后会生成mapper文件,但是在项目运行时该文件不会被打包,需要配置maven让maven将其打包
<!-- 在build中 -->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
开发持久层(Dao层接口及实现)
package com.xm.dao;
import com.xm.pojo.User;
public interface UserDao {
void addUser(User user);
void delUser(Long uid);
void updateUser(User user);
User findById(Long uid);
}
package com.xm.dao;
import com.xm.pojo.User;
import org.mybatis.spring.support.SqlSessionDaoSupport;
public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {
@Override
public void addUser(User user) {
this.getSqlSession().insert("com.xm.mapper.UserMapper.insertSelective",user);
}
@Override
public void delUser(Long uid) {
this.getSqlSession().delete("com.xm.mapper.UserMapper.deleteByPrimaryKey",uid);
}
@Override
public void updateUser(User user) {
this.getSqlSession().update("com.xm.mapper.UserMapper.updateByPrimaryKeySelective");
}
@Override
public User findById(Long uid) {
User user = this.getSqlSession().selectOne("com.xm.mapper.UserMapper.selectByPrimaryKey",uid);
return user;
}
开发服务层(接口及实现)
DTO用于对dao层进行拓展,例如增加关联属性等
package com.xm.dto;
import java.util.Arrays;
import java.util.Date;
/**
* 对实体类的拓展,用于有关联关系等
*/
public class UserDTO {
private Integer id;
private String username;
private String sex;
private Date birthday;
private String address;
private Long[] uids;
public UserDTO() {
}
public UserDTO(Integer id, String username, String sex, Date birthday, String address, Long[] uids) {
this.id = id;
this.username = username;
this.sex = sex;
this.birthday = birthday;
this.address = address;
this.uids = uids;
}
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 getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Long[] getUids() {
return uids;
}
public void setUids(Long[] uids) {
this.uids = uids;
}
@Override
public String toString() {
return "UserDTO{" +
"id=" + id +
", username='" + username + '\'' +
", sex='" + sex + '\'' +
", birthday=" + birthday +
", address='" + address + '\'' +
", uids=" + Arrays.toString(uids) +
'}';
}
}
package com.xm.service;
import com.xm.dto.UserDTO;
public interface UserService{
public void addUser(UserDTO dto);
public void deluser(Long uid);
public void updateUser(UserDTO dto);
public UserDTO findById(Long uid);
}
package com.xm.service;
import com.xm.dao.UserDao;
import com.xm.dto.UserDTO;
import com.xm.pojo.User;
import org.springframework.beans.BeanUtils;
public class UserServiceImpl implements UserService {
//依赖持久层:注入
private UserDao userDao;
public void setUserDao(UserDTO userDTO) {
this.userDao = userDao;
}
@Override
public void addUser(UserDTO dto) {
User user = new User();
//方式一
// user.setUsername(dto.getUsername());
// user.setId(dto.getId());
// user.setAddress(dto.getAddress());
// user.setBirthday(dto.getBirthday());
// user.setSex(dto.getSex());
//方式二
BeanUtils.copyProperties(dto,user);//对象之间复制(要求属性,类名名称需要一致)
userDao.addUser(user);
}
@Override
public void deluser(Long uid){
userDao.delUser(uid);
}
@Override
public void updateUser(UserDTO dto) {
User user = new User();
BeanUtils.copyProperties(dto,user);//对象之间复制(要求属性,类名名称需要一致)
userDao.addUser(user);
}
@Override
public UserDTO findById(Long uid) {
User user = userDao.findById(uid);
UserDTO dto = new UserDTO();
BeanUtils.copyProperties(user,dto);
return dto;
}
}
开发表现层
package com.xm.action;
import com.xm.dto.UserDTO;
import com.xm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
@Controller
public class UserAction {
//依赖服务层,自动注入
@Autowired
private UserService userService;
@RequestMapping("/addUser.do")
public String addUser(UserDTO dto){
userService.addUser(dto);
return "forward:/listUser.do";
}
@RequestMapping("/delUser.do")
public String delUser(Long uid){
userService.deluser(uid);
return "/listUser.do";
}
@RequestMapping("/updateUser.do")
public String updateUser(UserDTO dto){
userService.updateUser(dto);
return "/listUser.do";
}
@RequestMapping("/listUser.do")
public ModelAndView listUser(HttpServletRequest request){
ModelAndView mv = new ModelAndView();
String uid = request.getParameter("uid");
if(!StringUtils.isEmpty(uid)){
UserDTO byId = userService.findById(Long.parseLong(uid));
mv.addObject("dto",byId);
}
mv.setViewName("/userlist");
return mv;
}
}
整合持久层,表现层配置(applicationContext.xml+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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 加载配置文件 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 连接池 -->
<bean name="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}"/>
</bean>
<!-- mybatis的工厂 -->
<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!-- 指定读取mapper映射文件位置 -->
<property name="mapperLocations" value="classpath:com/xm/mapper/*.xml"/>
<!-- 注入mybatis配置文件 -->
<!-- <property name="configLocation" value="classpath:spring-mybatis.xml"></property>-->
</bean>
<!-- 注入sqlSessionFactory -->
<bean id="userDao" class="com.xm.dao.UserDaoImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactoryBean"></property>
</bean>
<!-- 注入服务层对象,注入DAO目标类对象 -->
<bean id="userService" class="com.xm.service.UserServiceImpl">
<property name="userDao" ref="userDao"/>
</bean>
<!-- 事务管理通知类对象 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入数据源 -->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 定义事务通知切面,让事务应用到具体的方法 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 可以对方法名使用通配符 -->
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="insert*" propagation="REQUIRED"/>
<tx:method name="create*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="del*" propagation="REQUIRED"/>
<tx:method name="find*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!-- Aop编程:让切入点与通知关联形成切面 -->
<aop:config>
<aop:pointcut id="myPoint" expression="execution(* com.xm.service.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="myPoint"></aop:advisor>
</aop:config>
<!-- 整合表现层配置 -->
<!-- 注解的处理器映射器和适配器 -->
<mvc:annotation-driven/>
<!-- 视图解析器:逻辑视图 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix" value="/"></property>
<!-- 后缀 -->
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 扫描action -->
<context:component-scan base-package="com.xm.action"></context:component-scan>
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!-- 配置过滤器 -->
<filter>
<filter-name>myfilter</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>myfilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>springmvc</servlet-name>
<!-- 关联中央处理器 -->
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 读取springmvc的配置文件 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-applicationContext.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
项目目录结构