文章目录
SSM(spring+springMVC+Mybatis)整合流程简介
项目基础结构搭建
- 创建项目,项目结构
- 创建表与实体类
- 创建三层架构对应的模块、接口与实体类,建立关联关系
- 数据层接口(代理自动创建实现类)
- 业务层接口 + 业务层实现类
- 表现层类
创建项目
创建数据表
CREATE TABLE `user` (
`uuid` int(10) NOT NULL AUTO_INCREMENT,
`userName` varchar(100) DEFAULT NULL,
`password` varchar(100) DEFAULT NULL,
`realName` varchar(100) DEFAULT NULL,
`gender` int(1) DEFAULT NULL,
`birthday` date DEFAULT NULL,
PRIMARY KEY (`uuid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
CREATE TABLE `student` (
`uuid` int(10) NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
`age` int(3) DEFAULT NULL,
`birthday` date DEFAULT NULL,
PRIMARY KEY (`uuid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
创建实体类
student
package com.zs.domain;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
@Data
public class Student implements Serializable {
private static final long serialVersionUID = 207360847718257908L;
private Integer uuid;
private String name;
private Integer age;
private Date birthday;
}
user
package com.zs.domain;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
@Data
public class User implements Serializable {
private static final long serialVersionUID = -7584152384912091175L;
private Integer uuid;
private String userName;
private String password;
private String realName;
private Integer gender;
private Date birthday;
}
数据层接口(代理自动创建实现类)
package com.zs.dao;
import com.zs.domain.Student;
import java.util.List;
public interface StudentDao {
boolean save(Student student);
boolean update(Student student);
boolean delete(Integer uuid);
Student get(Integer uuid);
List<Student> getAll();
}
package com.zs.dao;
import com.zs.domain.User;
import java.util.List;
public interface UserDao {
boolean save(User user);
boolean update(User user);
boolean delete(Integer uuid);
User get(Integer uuid);
List<User> getAll();
User getByUserNameAndPassword(String userName,String password);
}
业务层接口 + 实现类
package com.zs.service;
import com.zs.domain.Student;
import java.util.List;
public interface StudentService {
boolean save(Student student);
boolean update(Student student);
boolean delete(Integer uuid);
Student get(Integer uuid);
List<Student> getAll();
}
package com.zs.service;
import com.zs.domain.User;
import java.util.List;
public interface UserService {
boolean save(User user);
boolean update(User user);
boolean delete(Integer uuid);
User get(Integer uuid);
List<User> getAll();
User login(String userName,String password);
}
package com.zs.service.impl;
import com.zs.domain.Student;
import com.zs.service.StudentService;
import java.util.List;
public class StudentServiceImpl implements StudentService {
@Override
public boolean save(Student student) {
return false;
}
@Override
public boolean update(Student student) {
return false;
}
@Override
public boolean delete(Integer uuid) {
return false;
}
@Override
public Student get(Integer uuid) {
return null;
}
@Override
public List<Student> getAll() {
return null;
}
}
package com.zs.service.impl;
import com.zs.domain.User;
import com.zs.service.UserService;
import java.util.List;
public class UserServiceImpl implements UserService {
@Override
public boolean save(User user) {
return false;
}
@Override
public boolean update(User user) {
return false;
}
@Override
public boolean delete(Integer uuid) {
return false;
}
@Override
public User get(Integer uuid) {
return null;
}
@Override
public List<User> getAll() {
return null;
}
@Override
public User login(String userName, String password) {
return null;
}
}
spring 整合mybatis
<?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>org.example</groupId>
<artifactId>springmvc_ssm</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
</dependency>
<!--spring环境-->
<!--spring环境-->
<!--spring环境-->
<!--springMVC依赖于spring-context-->
<!--<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>-->
<!--mybatis环境-->
<!--mybatis环境-->
<!--mybatis环境-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.3</version>
</dependency>
<!--mysql环境-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--spring整合jdbc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!--spring整合mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.3</version>
</dependency>
<!--druid连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.16</version>
</dependency>
<!--分页插件坐标-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.2</version>
</dependency>
<!--springmvc环境-->
<!--springmvc环境-->
<!--springmvc环境-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!--jackson相关坐标3个-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
<!--上面的jackson-databind 依赖于下面的-->
<!--<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>-->
<!--servlet环境-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!--其他组件-->
<!--其他组件-->
<!--其他组件-->
<!--junit单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--spring整合junit-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>aliyun-maven</id>
<name>aliyun maven</name>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>aliyun-maven</id>
<name>aliyun maven</name>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
</pluginRepository>
</pluginRepositories>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
创建MyBatis映射文件
<?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.zs.dao.UserDao">
<!--添加-->
<insert id="save" parameterType="user">
insert into user(userName,password,realName,gender,birthday)values(#{userName},#{password},#{realName},#{gender},#{birthday})
</insert>
<!--删除-->
<delete id="delete" parameterType="int">
delete from user where uuid = #{uuid}
</delete>
<!--修改-->
<update id="update" parameterType="user">
update user set userName=#{userName},password=#{password},realName=#{realName},gender=#{gender},birthday=#{birthday} where uuid=#{uuid}
</update>
<!--查询单个-->
<select id="get" resultType="user" parameterType="int">
select * from user where uuid= #{uuid}
</select>
<!--分页查询-->
<select id="getAll" resultType="user">
select * from user
</select>
<!--登录-->
<select id="getByUserNameAndPassword" resultType="user" >
select * from user where userName=#{userName} and password=#{password}
</select>
</mapper>
创建Spring配置文件、整合Mybatis到Spring环境中
-
组件扫描
-
SqlSessionFactoryBean
-
数据源(druid + jdbc.properties)
-
映射扫描
-
注解事务
-
分页插件
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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.zs">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--整合mybatis-->
<!--整合mybatis-->
<!--整合mybatis-->
<!--整合mybatis-->
<tx:annotation-driven transaction-manager="txManager"/>
<!--加载properties文件-->
<context:property-placeholder location="classpath*:jdbc.properties"/>
<!--数据源-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--整合mybatis到spring中-->
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="typeAliasesPackage" value="com.zs.domain"/>
<!--分页插件-->
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageInterceptor">
<property name="properties">
<props>
<!--方言-->
<prop key="helperDialect">mysql</prop>
<!--合理化配置-->
<prop key="reasonable">true</prop>
</props>
</property>
</bean>
</array>
</property>
</bean>
<!--映射扫描-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.zs.dao"/>
</bean>
<!--事务-->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
创建单元测试
package com.zs.service;
import com.github.pagehelper.PageInfo;
import com.zs.domain.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.Date;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class UserServiceTest {
@Autowired
private UserService userService;
@Test
public void testSave(){
User user = new User();
user.setUserName("Jock");
user.setPassword("root");
user.setRealName("Jockme");
user.setGender(1);
user.setBirthday(new Date(333333000000L));
userService.save(user);
}
@Test
public void testDelete(){
User user = new User();
userService.delete(3);
}
@Test
public void testUpdate(){
User user = new User();
user.setUuid(1);
user.setUserName("Jockme");
user.setPassword("root");
user.setRealName("JockIsMe");
user.setGender(1);
user.setBirthday(new Date(333333000000L));
userService.update(user);
}
@Test
public void testGet(){
User user = userService.get(1);
System.out.println(user);
}
@Test
public void testGetAll(){
PageInfo<User> all = userService.getAll(2, 2);
System.out.println(all);
System.out.println(all.getList().get(0));
System.out.println(all.getList().get(1));
}
@Test
public void testLogin(){
User user = userService.login("Jockme", "root");
System.out.println(user);
}
}
package com.zs.service.impl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zs.dao.UserDao;
import com.zs.domain.User;
import com.zs.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public boolean save(User user) {
return userDao.save(user);
}
@Override
public boolean update(User user) {
return userDao.update(user);
}
@Override
public boolean delete(Integer uuid) {
return userDao.delete(uuid);
}
@Override
public User get(Integer uuid) {
return userDao.get(uuid);
}
//分页查询
@Override
public PageInfo<User> getAll(int page,int size) {
PageHelper.startPage(page,size);
List<User> all = userDao.getAll();
return new PageInfo<User>(all);
}
@Override
public User login(String userName, String password) {
return userDao.getByUserNameAndPassword(userName, password);
}
}
package com.zs.service;
import com.github.pagehelper.PageInfo;
import com.zs.domain.User;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Transactional(readOnly = true)
public interface UserService {
@Transactional(readOnly = false)
boolean save(User user);
@Transactional(readOnly = false)
boolean update(User user);
@Transactional(readOnly = false)
boolean delete(Integer uuid);
User get(Integer uuid);
PageInfo<User> getAll(int page, int size);
User login(String userName,String password);
}
整合SpringMVC
- web.xml加载SpringMVC
- rest风格
- 数据封装为json数据
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<!--加载spring容器-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<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>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<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>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.zs.controller"/>
<mvc:annotation-driven/>
</beans>
userController
package com.zs.controller;
import com.zs.domain.User;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/user")
public class UserController {
/**
* 新增
* @param user
* @return
*/
@PostMapping
public boolean save(User user){
System.out.println("save ..." + user);
return true;
}
/**
* 修改
* @param user
* @return
*/
@PutMapping
public boolean update(User user){
System.out.println("update ..." + user);
return true;
}
/**
* 删除
* @param uuid
* @return
*/
@DeleteMapping("/{uuid}")
public boolean delete(@PathVariable Integer uuid){
System.out.println("delete ..." + uuid);
return true;
}
@GetMapping("/{uuid}")
public User get(@PathVariable Integer uuid){
System.out.println("get ..." + uuid);
return null;
}
/**
* 分页查
* @param page
* @param size
* @return
*/
@GetMapping("/{page}/{size}")
public List getAll(@PathVariable Integer page, @PathVariable Integer size){
System.out.println("getAll ..." + page+","+size);
return null;
}
/**
* 登录
* @param userName
* @param password
* @return
*/
@PostMapping("/login")
public User login(String userName,String password){
System.out.println("login ..." + userName + " ," +password);
return null;
}
}
<!--加载spring容器-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
package com.zs.controller;
import com.github.pagehelper.PageInfo;
import com.zs.domain.User;
import com.zs.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@PostMapping
public boolean save(User user){
return userService.save(user);
}
@PutMapping
public boolean update(User user){
return userService.update(user);
}
@DeleteMapping("/{uuid}")
public boolean delete(@PathVariable Integer uuid){
return userService.delete(uuid);
}
@GetMapping("/{uuid}")
public User get(@PathVariable Integer uuid){
return userService.get(uuid);
}
@GetMapping("/{page}/{size}")
public PageInfo<User> getAll(@PathVariable Integer page, @PathVariable Integer size){
return userService.getAll(page,size);
}
@PostMapping("/login")
public User login(String userName,String password){
return userService.login(userName,password);
}
}
数据封装(定义数据交换中间件)
Result
package com.zs.controller.results;
import com.zs.domain.User;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
public class Result {
// 操作结果编码
private Integer code;
// 操作数据结果
private Object data;
// 消息
private String message;
public Result(Integer code) {
this.code = code;
}
public Result(Integer code, Object data) {
this.code = code;
this.data = data;
}
public Result(Integer code, String message) {
this.code = code;
this.message = message;
}
//
// public Result(Integer code, Object data) {
// this.code = code;
// this.data = data;
// }
//
// @Override
// public String toString() {
// return "Result{" +
// "code=" + code +
// ", data=" + data +
// ", message='" + message + '\'' +
// '}';
// }
//
// public Integer getCode() {
// return code;
// }
//
// public void setCode(Integer code) {
// this.code = code;
// }
//
// 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;
// }
}
Code
package com.zs.controller.results;
public class Code {
// 操作结果编码
public static final Integer SAVE_OK = 20011;
public static final Integer UPDATE_OK = 20021;
public static final Integer DELETE_OK = 20031;
public static final Integer GET_OK = 20041;
public static final Integer SAVE_ERROR = 20010;
public static final Integer UPDATE_ERROR = 20020;
public static final Integer DELETE_ERROR = 20030;
public static final Integer GET_ERROR = 20040;
// 系统错误编码
// 操作权限编码
// 校验结果编码
}
统一异常处理
@Component
@ControllerAdvice
public class ProjectExceptionAdivce {
@ExceptionHandler(BusinessException.class)
@ResponseBody
//对出现异常的情况进行拦截,并将其处理成统一的页面数据结果格式
public Result doBusinessException(BusinessException e){
return new Result(e.getCode(),e.getMessage());
}
}
package com.zs.system.exception;
public class BusinessException extends RuntimeException {
//自定义异常中封装对应的错误编码,用于异常处理时获取对应的操作编码
private Integer code;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public BusinessException(Integer code) {
this.code = code;
}
public BusinessException(String message, Integer code) {
super(message);
this.code = code;
}
public BusinessException(String message, Throwable cause,Integer code) {
super(message, cause);
this.code = code;
}
public BusinessException(Throwable cause,Integer code) {
super(cause);
this.code = code;
}
public BusinessException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace,Integer code) {
super(message, cause, enableSuppression, writableStackTrace);
this.code = code;
}
}
package com.zs.system.exception;
public class SystemException extends RuntimeException {
public SystemException() {
}
public SystemException(String message) {
super(message);
}
public SystemException(String message, Throwable cause) {
super(message, cause);
}
public SystemException(Throwable cause) {
super(cause);
}
public SystemException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
表现层业务方法处理
package com.zs.controller;
import com.github.pagehelper.PageInfo;
import com.zs.controller.results.Code;
import com.zs.controller.results.Result;
import com.zs.domain.User;
import com.zs.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@PostMapping
public Result save(User user){
boolean flag = userService.save(user);
return new Result(flag ? Code.SAVE_OK:Code.SAVE_ERROR);
}
@PutMapping
public Result update(User user){
boolean flag = userService.update(user);
return new Result(flag ? Code.UPDATE_OK:Code.UPDATE_ERROR);
}
@DeleteMapping("/{uuid}")
public Result delete(@PathVariable Integer uuid){
boolean flag = userService.delete(uuid);
return new Result(flag ? Code.DELETE_OK:Code.DELETE_ERROR);
}
@GetMapping("/{uuid}")
public Result get(@PathVariable Integer uuid){
User user = userService.get(uuid);
return new Result(null != user ?Code.GET_OK: Code.GET_ERROR,user);
}
@GetMapping("/{page}/{size}")
public Result getAll(@PathVariable Integer page, @PathVariable Integer size){
PageInfo<User> all = userService.getAll(page, size);
return new Result(null != all ?Code.GET_OK: Code.GET_ERROR,all);
}
@PostMapping("/login")
public Result login(String userName,String password){
User user = userService.login(userName,password);
return new Result(null != user ?Code.GET_OK: Code.GET_ERROR,user);
}
}
注解整合
userDao.xml
public interface UserDao {
/**
* 添加用户
* @param user
* @return
*/
@Insert("insert into user(userName,password,realName,gender,birthday)values(#{userName},#{password},#{realName},#{gender},#{birthday})")
public boolean save(User user);
/**
* 修改用户
* @param user
* @return
*/
@Update("update user set userName=#{userName},password=#{password},realName=#{realName},gender=#{gender},birthday=#{birthday} where uuid=#{uuid}")
public boolean update(User user);
/**
* 删除用户
* @param uuid
* @return
*/
@Delete("delete from user where uuid = #{uuid}")
public boolean delete(Integer uuid);
/**
* 查询单个用户信息
* @param uuid
* @return
*/
@Select("select * from user where uuid = #{uuid}")
public User get(Integer uuid);
/**
* 查询全部用户信息
* @return
*/
@Select("select * from user")
public List<User> getAll();
/**
* 根据用户名密码查询个人信息
* @param userName 用户名
* @param password 密码信息
* @return
*/
@Select("select * from user where userName=#{userName} and password=#{password}")
//注意:数据层操作不要和业务层操作的名称混淆,通常数据层仅反映与数据库间的信息交换,不体现业务逻辑
public User getByUserNameAndPassword(@Param("userName") String userName,@Param("password") String password);
}
web.xml
public class ServletContainersInitConfig extends AbstractDispatcherServletInitializer {
//创建Servlet容器时,使用注解的方式加载SPRINGMVC配置类中的信息,并加载成WEB专用的ApplicationContext对象
//该对象放入了ServletContext范围,后期在整个WEB容器中可以随时获取调用
@Override
protected WebApplicationContext createServletApplicationContext() {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(SpringMvcConfig.class);
return ctx;
}
//注解配置映射地址方式,服务于SpringMVC的核心控制器DispatcherServlet
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
@Override
//基本等同于<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
protected WebApplicationContext createRootApplicationContext() {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(SpringConfig.class);
return ctx;
}
//乱码处理作为过滤器,在servlet容器启动时进行配置,相关内容参看Servlet零配置相关课程
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
//触发父类的onStartup
super.onStartup(servletContext);
//1.创建字符集过滤器对象
CharacterEncodingFilter cef = new CharacterEncodingFilter();
//2.设置使用的字符集
cef.setEncoding("UTF-8");
//3.添加到容器(它不是ioc容器,而是ServletContainer)
FilterRegistration.Dynamic registration = servletContext.addFilter("characterEncodingFilter", cef);
//4.添加映射
registration.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE), false, "/*");
}
}
applicationContext.xml
SpringConfig
@Configuration
//等同于<context:component-scan base-package="com.itheima">
@ComponentScan(value = "com.itheima",excludeFilters =
//等同于<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
@ComponentScan.Filter(type= FilterType.ANNOTATION,classes = {Controller.class}))
//等同于<context:property-placeholder location="classpath*:jdbc.properties"/>
@PropertySource("classpath:jdbc.properties")
//等同于<tx:annotation-driven />,bean的名称默认取transactionManager
@EnableTransactionManagement
@Import({MyBatisConfig.class,JdbcConfig.class})
public class SpringConfig {
//等同于<bean id="txManager"/>
@Bean("transactionManager")
//等同于<bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
public DataSourceTransactionManager getTxManager(@Autowired DataSource dataSource){
DataSourceTransactionManager tm = new DataSourceTransactionManager();
//等同于<property name="dataSource" ref="dataSource"/>
tm.setDataSource(dataSource);
return tm;
}
}
JdbcConfig
package com.itheima.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import javax.sql.DataSource;
public class JdbcConfig {
//使用注入的形式,读取properties文件中的属性值,等同于<property name="*******" value="${jdbc.driver}"/>
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String userName;
@Value("${jdbc.password}")
private String password;
//定义dataSource的bean,等同于<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
@Bean("dataSource")
public DataSource getDataSource(){
//创建对象
DruidDataSource ds = new DruidDataSource();
//手工调用set方法,等同于set属性注入<property name="driverClassName" value="******"/>
ds.setDriverClassName(driver);
ds.setUrl(url);
ds.setUsername(userName);
ds.setPassword(password);
return ds;
}
}
MyBatisConfig
public class MyBatisConfig {
//定义MyBatis的核心连接工厂bean,等同于<bean class="org.mybatis.spring.SqlSessionFactoryBean">
@Bean
//参数使用自动装配的形式加载dataSource,为set注入提供数据,dataSource来源于JdbcConfig中的配置
public SqlSessionFactoryBean getSqlSessionFactoryBean(@Autowired DataSource dataSource,@Autowired Interceptor interceptor){
SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
//等同于<property name="typeAliasesPackage" value="com.itheima.domain"/>
ssfb.setTypeAliasesPackage("com.itheima.domain");
//等同于<property name="dataSource" ref="dataSource"/>
ssfb.setDataSource(dataSource);
// //等同于<bean class="com.github.pagehelper.PageInterceptor">
// Interceptor interceptor = new PageInterceptor();
// Properties properties = new Properties();
// properties.setProperty("helperDialect","mysql");
// properties.setProperty("reasonable","true");
// //等同于<property name="properties">
// interceptor.setProperties(properties);
ssfb.setPlugins(interceptor);
return ssfb;
}
//定义MyBatis的映射扫描,等同于<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
@Bean
public MapperScannerConfigurer getMapperScannerConfigurer(){
MapperScannerConfigurer msc = new MapperScannerConfigurer();
//等同于<property name="basePackage" value="com.itheima.dao"/>
msc.setBasePackage("com.itheima.dao");
return msc;
}
@Bean("pageInterceptor")
public Interceptor getPageInterceptor(){
Interceptor interceptor = new PageInterceptor();
Properties properties = new Properties();
properties.setProperty("helperDialect","mysql");
properties.setProperty("reasonable","true");
//等同于<property name="properties">
interceptor.setProperties(properties);
return interceptor;
}
}
spring -mvc.xml
@Configuration
//等同于<context:component-scan base-package="com.itheima.controller"/>
@ComponentScan("com.itheima.controller")
//等同于<mvc:annotation-driven/>,还不完全相同
@EnableWebMvc
public class SpringMvcConfig {
}