目录
配套资料,免费下载
链接:https://pan.baidu.com/s/1gsHGUjRI8nPe_Gv1bZ7BMg
提取码:5la2
复制这段内容后打开百度网盘手机App,操作更方便哦
第十章 ORM整合
数据库脚本:以下整合共用此脚本
DROP DATABASE IF EXISTS `test`;
CREATE DATABASE `test`;
USE `test`;
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
`uid` INT(11) NOT NULL AUTO_INCREMENT,
`uname` VARCHAR(20) NOT NULL,
`ugender` VARCHAR(20) NOT NULL,
`uage` INT(11) NOT NULL,
PRIMARY KEY (`uid`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO `test`.`t_user` (`uname`, `ugender`, `uage`) VALUES ('张三', '男', '18');
INSERT INTO `test`.`t_user` (`uname`, `ugender`, `uage`) VALUES ('李四', '女', '19');
INSERT INTO `test`.`t_user` (`uname`, `ugender`, `uage`) VALUES ('王五', '男', '20');
10.1、SSJ整合
技术要点: Spring MVC 5.3.2 + Spring 5.3.2 + JdbcTemplate 5.3.2
其他方面: 数据库连接池、注解事务管理、常用增删改查、全局异常处理、解决跨域问题、统一使用VO.Result对象封装数据
项目名称: ssj-demo,完整代码,请参考配套资料
修改 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">
<!--Spring IOC-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-ioc.xml</param-value>
</context-param>
<!--Spring MVC-->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--注册字符集过滤器-->
<filter>
<filter-name>characterEncodingFilter</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>
<!--强制Request使用字符集encoding-->
<init-param>
<param-name>forceRequestEncoding</param-name>
<param-value>true</param-value>
</init-param>
<!--强制Response使用字符集encoding-->
<init-param>
<param-name>forceResponseEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
修改 pom.xml
<?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>com.caochenlei</groupId>
<artifactId>ssj-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<!--项目配置信息-->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<!--自定义版本-->
<spring.version>5.3.2</spring.version>
<jackson.version>2.12.0</jackson.version>
<log4j.version>2.14.0</log4j.version>
</properties>
<dependencies>
<!--Spring Core-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!--Spring AOP-->
<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>
<!--Spring TX-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<!--Spring MVC-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!--JSON依赖-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
<!--Servlet依赖-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
<scope>provided</scope>
</dependency>
<!--JSP标签依赖-->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--文件上传依赖-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<!--Spring ORM-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!--数据库驱动包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
</dependency>
<!--数据库连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.4</version>
</dependency>
<!--整合日志框架-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>${log4j.version}</version>
</dependency>
</dependencies>
<build>
<!--资源拷贝-->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
<include>**/*.conf</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
<include>**/*.conf</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>
src\main\webapp\WEB-INF\error.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>error page</title>
</head>
<body>
<p><strong>错误描述:</strong>${msg}</p>
<p><strong>错误提示:</strong>${ex.message}</p>
</body>
</html>
src\main\resources\log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--日志级别:OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL-->
<Configuration status="info">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="info">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>
src\main\resources\spring-mvc.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: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 http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--开启组件扫描-->
<context:component-scan base-package="com.caochenlei.controller,com.caochenlei.handler"/>
<!--开启MVC注解-->
<mvc:annotation-driven/>
<!--过滤静态资源-->
<mvc:default-servlet-handler/>
<!--配置视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--配置媒体解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--设定文件默认编码-->
<property name="defaultEncoding" value="UTF-8"></property>
<!--设定文件的最大值(5*1024*1024=5M)-->
<property name="maxUploadSize" value="5242880"></property>
</bean>
<!--配置CORS跨域-->
<mvc:cors>
<mvc:mapping path="/**" allowed-origins="https://localhost:8080" allowed-methods="GET, POST"/>
</mvc:cors>
</beans>
src\main\resources\spring-ioc.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--开启组件扫描-->
<context:component-scan base-package="com.caochenlei">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
</context:component-scan>
<!--配置Druid数据库连接池-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<!--配置JdbcTemplate模板-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--开启事务注解-->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
com.caochenlei.vo.Result
public class Result implements Serializable {
private static final long serialVersionUID = 6785657555819824255L;
private Boolean success;
private Object data;
private String message;
public Result() {
super();
}
public Result(Boolean success, Object data, String message) {
this.success = success;
this.data = data;
this.message = message;
}
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
com.caochenlei.entity.User
public class User implements Serializable {
private static final long serialVersionUID = -445352327778902151L;
private Integer uid;
private String uname;
private String ugender;
private Integer uage;
public User() {
}
public User(Integer uid, String uname, String ugender, Integer uage) {
this.uid = uid;
this.uname = uname;
this.ugender = ugender;
this.uage = uage;
}
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getUgender() {
return ugender;
}
public void setUgender(String ugender) {
this.ugender = ugender;
}
public Integer getUage() {
return uage;
}
public void setUage(Integer uage) {
this.uage = uage;
}
}
com.caochenlei.dao.UserDao
public interface UserDao {
//查找一个用户
public User findOne(Integer id);
//查找所有用户
public List<User> findAll();
//添加一个用户
public Integer save(User user);
//删除一个用户
public Integer delete(Integer id);
//修改一个用户
public Integer update(User user);
}
com.caochenlei.dao.impl.UserDaoImpl
@Repository
public class UserDaoImpl implements UserDao {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public User findOne(Integer id) {
String sql = "select * from t_user where uid = ?";
return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), id);
}
@Override
public List<User> findAll() {
String sql = "select * from t_user";
return jdbcTemplate.query(sql, new BeanPropertyRowMapper<User>(User.class));
}
@Override
public Integer save(User user) {
String sql = "insert into t_user values(?,?,?,?)";
return jdbcTemplate.update(sql, null, user.getUname(), user.getUgender(), user.getUage());
}
@Override
public Integer delete(Integer id) {
String sql = "delete from t_user where uid=?";
return jdbcTemplate.update(sql, id);
}
@Override
public Integer update(User user) {
String sql = "update t_user set uname=?,ugender=?,uage=? where uid=?";
return jdbcTemplate.update(sql, user.getUname(), user.getUgender(), user.getUage(), user.getUid());
}
}
com.caochenlei.service.UserService
public interface UserService {
//查找一个用户
public User findOne(Integer id);
//查找所有用户
public List<User> findAll();
//添加一个用户
public Integer save(User user);
//删除一个用户
public Integer delete(Integer id);
//修改一个用户
public Integer update(User user);
}
com.caochenlei.service.impl.UserServiceImpl
@Service
@Transactional
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public User findOne(Integer id) {
return userDao.findOne(id);
}
@Override
public List<User> findAll() {
return userDao.findAll();
}
@Override
public Integer save(User user) {
return userDao.save(user);
}
@Override
public Integer delete(Integer id) {
return userDao.delete(id);
}
@Override
public Integer update(User user) {
return userDao.update(user);
}
}
com.caochenlei.controller.UserController
@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
//查找一个用户
@GetMapping("/findOne/{id}")
public Result findOne(@PathVariable Integer id) {
User user = userService.findOne(id);
return new Result(true, user, "操作成功");
}
//查找所有用户
@GetMapping("/findAll")
public Result findAll() {
List<User> users = userService.findAll();
return new Result(true, users, "操作成功");
}
//添加一个用户
@PostMapping("/save")
public Result save(@RequestBody User user) {
Integer rows = userService.save(user);
if (rows > 0) {
return new Result(true, rows, "操作成功");
} else {
return new Result(false, rows, "操作失败");
}
}
//删除一个用户
@PostMapping("/delete/{id}")
public Result delete(@PathVariable Integer id) {
Integer rows = userService.delete(id);
if (rows > 0) {
return new Result(true, rows, "操作成功");
} else {
return new Result(false, rows, "操作失败");
}
}
//修改一个用户
@PostMapping("/update")
public Result update(@RequestBody User user) {
Integer rows = userService.update(user);
if (rows > 0) {
return new Result(true, rows, "操作成功");
} else {
return new Result(false, rows, "操作失败");
}
}
}
com.caochenlei.handler.GlobalExceptionHandler
@ControllerAdvice
public class GlobalExceptionHandler {
//处理系统未知异常
@ExceptionHandler
public ModelAndView doOtherException(Exception exception) {
ModelAndView mv = new ModelAndView();
mv.addObject("msg", "系统发生错误,请通知管理员!");
mv.addObject("ex", exception);
mv.setViewName("error");
return mv;
}
}
10.2、SSH整合
技术要点: Spring MVC 5.3.2 + Spring 5.3.2 + Hibernate 5.4.27.Final
其他方面: 数据库连接池、注解事务管理、常用增删改查、全局异常处理、解决跨域问题、统一使用VO.Result对象封装数据
项目名称: ssh-demo,完整代码,请参考配套资料
修改 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">
<!--Spring IOC-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-ioc.xml</param-value>
</context-param>
<!--Spring MVC-->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--注册字符集过滤器-->
<filter>
<filter-name>characterEncodingFilter</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>
<!--强制Request使用字符集encoding-->
<init-param>
<param-name>forceRequestEncoding</param-name>
<param-value>true</param-value>
</init-param>
<!--强制Response使用字符集encoding-->
<init-param>
<param-name>forceResponseEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
修改 pom.xml
<?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>com.caochenlei</groupId>
<artifactId>ssh-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<!--项目配置信息-->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<!--自定义版本-->
<spring.version>5.3.2</spring.version>
<jackson.version>2.12.0</jackson.version>
<hibernate.version>5.4.27.Final</hibernate.version>
<log4j.version>2.14.0</log4j.version>
</properties>
<dependencies>
<!--Spring Core-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!--Spring AOP-->
<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>
<!--Spring TX-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<!--Spring MVC-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!--JSON依赖-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
<!--Servlet依赖-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
<scope>provided</scope>
</dependency>
<!--JSP标签依赖-->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--文件上传依赖-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<!--Spring ORM-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!--数据库驱动包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
</dependency>
<!--数据库连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.4</version>
</dependency>
<!--整合日志框架-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>${log4j.version}</version>
</dependency>
</dependencies>
<build>
<!--资源拷贝-->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
<include>**/*.conf</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
<include>**/*.conf</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>
src\main\webapp\WEB-INF\error.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>error page</title>
</head>
<body>
<p><strong>错误描述:</strong>${msg}</p>
<p><strong>错误提示:</strong>${ex.message}</p>
</body>
</html>
src\main\resources\log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--日志级别:OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL-->
<Configuration status="info">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="info">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>
src\main\resources\spring-mvc.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: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 http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--开启组件扫描-->
<context:component-scan base-package="com.caochenlei.controller,com.caochenlei.handler"/>
<!--开启MVC注解-->
<mvc:annotation-driven/>
<!--过滤静态资源-->
<mvc:default-servlet-handler/>
<!--配置视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--配置媒体解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--设定文件默认编码-->
<property name="defaultEncoding" value="UTF-8"></property>
<!--设定文件的最大值(5*1024*1024=5M)-->
<property name="maxUploadSize" value="5242880"></property>
</bean>
<!--配置CORS跨域-->
<mvc:cors>
<mvc:mapping path="/**" allowed-origins="https://localhost:8080" allowed-methods="GET, POST"/>
</mvc:cors>
</beans>
src\main\resources\spring-ioc.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--开启组件扫描-->
<context:component-scan base-package="com.caochenlei">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
</context:component-scan>
<!--配置Druid数据库连接池-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<!--配置SessionFactory-->
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<!--注入连接池-->
<property name="dataSource" ref="dataSource"/>
<!--注入常用属性-->
<property name="hibernateProperties">
<props>
<prop key="hibernate.show_sql">true</prop><!--是否显示sql语句-->
<prop key="hibernate.format_sql">true</prop><!--是否格式化sql语句-->
<prop key="hibernate.hbm2ddl.auto">update</prop><!--是否自动创建表结构-->
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL55Dialect</prop>
</props>
</property>
<!--引入映射文件-->
<property name="mappingLocations">
<list>
<value>classpath:com/caochenlei/entity/*.hbm.xml</value>
</list>
</property>
</bean>
<!--配置HibernateTemplate模板-->
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!--配置事务管理器-->
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!--开启事务注解-->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
com.caochenlei.vo.Result
public class Result implements Serializable {
private static final long serialVersionUID = 6785657555819824255L;
private Boolean success;
private Object data;
private String message;
public Result() {
super();
}
public Result(Boolean success, Object data, String message) {
this.success = success;
this.data = data;
this.message = message;
}
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
com.caochenlei.entity.User
public class User implements Serializable {
private static final long serialVersionUID = -445352327778902151L;
private Integer uid;
private String uname;
private String ugender;
private Integer uage;
public User() {
}
public User(Integer uid, String uname, String ugender, Integer uage) {
this.uid = uid;
this.uname = uname;
this.ugender = ugender;
this.uage = uage;
}
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getUgender() {
return ugender;
}
public void setUgender(String ugender) {
this.ugender = ugender;
}
public Integer getUage() {
return uage;
}
public void setUage(Integer uage) {
this.uage = uage;
}
}
src\main\resources\com\caochenlei\entity\User.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.caochenlei.entity.User" table="t_user">
<!-- 设置主键字段映射 -->
<id name="uid" column="uid">
<generator class="native"/>
</id>
<!-- 设置普通字段映射 -->
<property name="uname" column="uname"/>
<property name="ugender" column="ugender"/>
<property name="uage" column="uage"/>
</class>
</hibernate-mapping>
com.caochenlei.dao.UserDao
public interface UserDao {
//查找一个用户
public User findOne(Integer id);
//查找所有用户
public List<User> findAll();
//添加一个用户
public Integer save(User user);
//删除一个用户
public Integer delete(Integer id);
//修改一个用户
public Integer update(User user);
}
com.caochenlei.dao.impl.UserDaoImpl
@Repository
public class UserDaoImpl implements UserDao {
@Autowired
private HibernateTemplate hibernateTemplate;
@Override
public User findOne(Integer id) {
return hibernateTemplate.load(User.class, id);
}
@Override
public List<User> findAll() {
return hibernateTemplate.loadAll(User.class);
}
@Override
public Integer save(User user) {
hibernateTemplate.save(user);
return 1;
}
@Override
public Integer delete(Integer id) {
User user = hibernateTemplate.get(User.class, id);
hibernateTemplate.delete(user);
return 1;
}
@Override
public Integer update(User user) {
hibernateTemplate.update(user);
return 1;
}
}
com.caochenlei.service.UserService
public interface UserService {
//查找一个用户
public User findOne(Integer id);
//查找所有用户
public List<User> findAll();
//添加一个用户
public Integer save(User user);
//删除一个用户
public Integer delete(Integer id);
//修改一个用户
public Integer update(User user);
}
com.caochenlei.service.impl.UserServiceImpl
@Service
@Transactional
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public User findOne(Integer id) {
return userDao.findOne(id);
}
@Override
public List<User> findAll() {
return userDao.findAll();
}
@Override
public Integer save(User user) {
return userDao.save(user);
}
@Override
public Integer delete(Integer id) {
return userDao.delete(id);
}
@Override
public Integer update(User user) {
return userDao.update(user);
}
}
com.caochenlei.controller.UserController
@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
//查找一个用户
@GetMapping("/findOne/{id}")
public Result findOne(@PathVariable Integer id) {
User user = userService.findOne(id);
return new Result(true, user, "操作成功");
}
//查找所有用户
@GetMapping("/findAll")
public Result findAll() {
List<User> users = userService.findAll();
return new Result(true, users, "操作成功");
}
//添加一个用户
@PostMapping("/save")
public Result save(@RequestBody User user) {
Integer rows = userService.save(user);
if (rows > 0) {
return new Result(true, rows, "操作成功");
} else {
return new Result(false, rows, "操作失败");
}
}
//删除一个用户
@PostMapping("/delete/{id}")
public Result delete(@PathVariable Integer id) {
Integer rows = userService.delete(id);
if (rows > 0) {
return new Result(true, rows, "操作成功");
} else {
return new Result(false, rows, "操作失败");
}
}
//修改一个用户
@PostMapping("/update")
public Result update(@RequestBody User user) {
Integer rows = userService.update(user);
if (rows > 0) {
return new Result(true, rows, "操作成功");
} else {
return new Result(false, rows, "操作失败");
}
}
}
com.caochenlei.handler.GlobalExceptionHandler
@ControllerAdvice
public class GlobalExceptionHandler {
//处理系统未知异常
@ExceptionHandler
public ModelAndView doOtherException(Exception exception) {
ModelAndView mv = new ModelAndView();
mv.addObject("msg", "系统发生错误,请通知管理员!");
mv.addObject("ex", exception);
mv.setViewName("error");
return mv;
}
}
10.3、SSM整合
技术要点: Spring MVC 5.3.2 + Spring 5.3.2 + MyBatis 3.5.6
其他方面: 数据库连接池、注解事务管理、常用增删改查、全局异常处理、解决跨域问题、统一使用VO.Result对象封装数据
项目名称: ssm-demo,完整代码,请参考配套资料
修改 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">
<!--Spring IOC-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-ioc.xml</param-value>
</context-param>
<!--Spring MVC-->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--注册字符集过滤器-->
<filter>
<filter-name>characterEncodingFilter</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>
<!--强制Request使用字符集encoding-->
<init-param>
<param-name>forceRequestEncoding</param-name>
<param-value>true</param-value>
</init-param>
<!--强制Response使用字符集encoding-->
<init-param>
<param-name>forceResponseEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
修改 pom.xml
<?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>com.caochenlei</groupId>
<artifactId>ssm-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<!--项目配置信息-->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<!--自定义版本-->
<spring.version>5.3.2</spring.version>
<jackson.version>2.12.0</jackson.version>
<mybatis.version>3.5.6</mybatis.version>
<mybatis.spring.version>2.0.6</mybatis.spring.version>
<log4j.version>2.14.0</log4j.version>
</properties>
<dependencies>
<!--Spring Core-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!--Spring AOP-->
<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>
<!--Spring TX-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<!--Spring MVC-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!--JSON依赖-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
<!--Servlet依赖-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
<scope>provided</scope>
</dependency>
<!--JSP标签依赖-->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--文件上传依赖-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<!--Spring ORM-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis.spring.version}</version>
</dependency>
<!--数据库驱动包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
</dependency>
<!--数据库连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.4</version>
</dependency>
<!--整合日志框架-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>${log4j.version}</version>
</dependency>
</dependencies>
<build>
<!--资源拷贝-->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
<include>**/*.conf</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
<include>**/*.conf</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>
src\main\webapp\WEB-INF\error.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>error page</title>
</head>
<body>
<p><strong>错误描述:</strong>${msg}</p>
<p><strong>错误提示:</strong>${ex.message}</p>
</body>
</html>
src\main\resources\log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--日志级别:OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL-->
<Configuration status="info">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="info">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>
src\main\resources\spring-mvc.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: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 http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--开启组件扫描-->
<context:component-scan base-package="com.caochenlei.controller,com.caochenlei.handler"/>
<!--开启MVC注解-->
<mvc:annotation-driven/>
<!--过滤静态资源-->
<mvc:default-servlet-handler/>
<!--配置视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--配置媒体解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--设定文件默认编码-->
<property name="defaultEncoding" value="UTF-8"></property>
<!--设定文件的最大值(5*1024*1024=5M)-->
<property name="maxUploadSize" value="5242880"></property>
</bean>
<!--配置CORS跨域-->
<mvc:cors>
<mvc:mapping path="/**" allowed-origins="https://localhost:8080" allowed-methods="GET, POST"/>
</mvc:cors>
</beans>
src\main\resources\spring-ioc.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--开启组件扫描-->
<context:component-scan base-package="com.caochenlei">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
</context:component-scan>
<!--配置Druid数据库连接池-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<!--配置SqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--设置连接池-->
<property name="dataSource" ref="dataSource"/>
<!--设置别名包-->
<property name="typeAliasesPackage" value="com.caochenlei.entity"/>
<!--配置映射包-->
<property name="mapperLocations" value="classpath:com/caochenlei/mapper/*.xml"/>
</bean>
<!--配置MapperScannerConfigurer-->
<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.caochenlei.mapper"/>
</bean>
<!--配置事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--开启事务注解-->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
com.caochenlei.vo.Result
public class Result implements Serializable {
private static final long serialVersionUID = 6785657555819824255L;
private Boolean success;
private Object data;
private String message;
public Result() {
super();
}
public Result(Boolean success, Object data, String message) {
this.success = success;
this.data = data;
this.message = message;
}
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
com.caochenlei.entity.User
public class User implements Serializable {
private static final long serialVersionUID = -445352327778902151L;
private Integer uid;
private String uname;
private String ugender;
private Integer uage;
public User() {
}
public User(Integer uid, String uname, String ugender, Integer uage) {
this.uid = uid;
this.uname = uname;
this.ugender = ugender;
this.uage = uage;
}
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getUgender() {
return ugender;
}
public void setUgender(String ugender) {
this.ugender = ugender;
}
public Integer getUage() {
return uage;
}
public void setUage(Integer uage) {
this.uage = uage;
}
}
src\main\resources\com\caochenlei\mapper\UserMapper.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.caochenlei.mapper.UserMapper">
<!--查找一个用户-->
<select id="findOne" resultType="user">
select * from t_user where uid=#{id}
</select>
<!--查找所有用户-->
<select id="findAll" resultType="user">
select * from t_user
</select>
<!--添加一个用户-->
<insert id="save" useGeneratedKeys="true" keyProperty="uid">
insert into t_user(uname,ugender,uage)
values(#{uname},#{ugender},#{uage})
</insert>
<!--删除一个用户-->
<delete id="delete">
delete from t_user where uid=#{id}
</delete>
<!--修改一个用户-->
<update id="update">
update t_user
set uname=#{uname},ugender=#{ugender},uage=#{uage}
where uid=#{uid}
</update>
</mapper>
com.caochenlei.mapper.UserMapper
public interface UserMapper {
//查找一个用户
public User findOne(Integer id);
//查找所有用户
public List<User> findAll();
//添加一个用户
public Integer save(User user);
//删除一个用户
public Integer delete(Integer id);
//修改一个用户
public Integer update(User user);
}
com.caochenlei.service.UserService
public interface UserService {
//查找一个用户
public User findOne(Integer id);
//查找所有用户
public List<User> findAll();
//添加一个用户
public Integer save(User user);
//删除一个用户
public Integer delete(Integer id);
//修改一个用户
public Integer update(User user);
}
com.caochenlei.service.impl.UserServiceImpl
@Service
@Transactional
public class UserServiceImpl implements UserService {
@Autowired(required = false)
private UserMapper userMapper;
@Override
public User findOne(Integer id) {
return userMapper.findOne(id);
}
@Override
public List<User> findAll() {
return userMapper.findAll();
}
@Override
public Integer save(User user) {
return userMapper.save(user);
}
@Override
public Integer delete(Integer id) {
return userMapper.delete(id);
}
@Override
public Integer update(User user) {
return userMapper.update(user);
}
}
com.caochenlei.controller.UserController
@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
//查找一个用户
@GetMapping("/findOne/{id}")
public Result findOne(@PathVariable Integer id) {
User user = userService.findOne(id);
return new Result(true, user, "操作成功");
}
//查找所有用户
@GetMapping("/findAll")
public Result findAll() {
List<User> users = userService.findAll();
return new Result(true, users, "操作成功");
}
//添加一个用户
@PostMapping("/save")
public Result save(@RequestBody User user) {
Integer rows = userService.save(user);
if (rows > 0) {
return new Result(true, rows, "操作成功");
} else {
return new Result(false, rows, "操作失败");
}
}
//删除一个用户
@PostMapping("/delete/{id}")
public Result delete(@PathVariable Integer id) {
Integer rows = userService.delete(id);
if (rows > 0) {
return new Result(true, rows, "操作成功");
} else {
return new Result(false, rows, "操作失败");
}
}
//修改一个用户
@PostMapping("/update")
public Result update(@RequestBody User user) {
Integer rows = userService.update(user);
if (rows > 0) {
return new Result(true, rows, "操作成功");
} else {
return new Result(false, rows, "操作失败");
}
}
}
com.caochenlei.handler.GlobalExceptionHandler
@ControllerAdvice
public class GlobalExceptionHandler {
//处理系统未知异常
@ExceptionHandler
public ModelAndView doOtherException(Exception exception) {
ModelAndView mv = new ModelAndView();
mv.addObject("msg", "系统发生错误,请通知管理员!");
mv.addObject("ex", exception);
mv.setViewName("error");
return mv;
}
}