Phase_1_User_Model Day1_配置清单
依赖
< dependency>
< groupId> org.springframework.boot</ groupId>
< artifactId> spring-boot-starter-web</ artifactId>
</ dependency>
< dependency>
< groupId> commons-fileupload</ groupId>
< artifactId> commons-fileupload</ artifactId>
< version> 1.4</ version>
</ dependency>
< dependency>
< groupId> org.mybatis.spring.boot</ groupId>
< artifactId> mybatis-spring-boot-starter</ artifactId>
< version> 2.0.1</ version>
</ dependency>
< dependency>
< groupId> mysql</ groupId>
< artifactId> mysql-connector-java</ artifactId>
< version> 5.1.47</ version>
</ dependency>
t_user.sql
DROP TABLE IF EXISTS t_user;
set character_set_results= utf8;
set character_set_client= utf8;
CREATE TABLE t_user (
id int primary key AUTO_INCREMENT ,
name varchar ( 32 ) unique ,
password varchar ( 128 ) ,
sex tinyint ( 1 ) ,
photo varchar ( 255 ) ,
birthDay date ,
email varchar ( 128 )
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8;
entities-User
package com. baizhi. entities;
import com. fasterxml. jackson. annotation. JsonFormat;
import org. springframework. format. annotation. DateTimeFormat;
import java. io. Serializable;
import java. util. Date;
public class User implements Serializable {
private Integer id;
private String name;
private boolean sex;
private String password;
@DateTimeFormat ( pattern = "yyyy-MM-dd" )
@JsonFormat ( pattern = "yyyy-MM-dd" , timezone = "GMT+8" )
private Date birthDay;
private String photo;
private String email;
public User ( ) {
}
public User ( String name, boolean sex, String password, Date birthDay, String photo, String email) {
this . name = name;
this . sex = sex;
this . password = password;
this . birthDay = birthDay;
this . photo = photo;
this . email = email;
}
@Override
public String toString ( ) {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", sex=" + sex +
", password='" + password + '\'' +
", birthDay=" + birthDay +
", photo='" + photo + '\'' +
", email='" + email + '\'' +
'}' ;
}
}
application.properties
#服务的基本配置
server. port= 8888
server. servlet. context- path= /
#文件上传
spring. servlet. multipart. max- file- size= 1 MB
spring. servlet. multipart. enabled= true
spring. servlet. multipart. location= D: / uploadfiles
#post表单乱码问题
spring. http. encoding. charset= utf- 8
server. tomcat. uri- encoding= utf- 8
#数据源
spring. datasource. username= root
spring. datasource. password= root
spring. datasource. driver- class - name= com. mysql. jdbc. Driver
spring. datasource. url= jdbc: mysql: / / CentOS: 3306 / test? useUnicode= true & characterEncoding= UTF8& serverTimezone= UTC& useSSL= false
## MyBatis 配置信息
mybatis. type- aliases- package = com. baizhi. entities
mybatis. mapper- locations= classpath* : mappers
mappers-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.baizhi.dao.IUserDao" >
< insert id = " saveUser" parameterType = " User" useGeneratedKeys = " true"
keyProperty = " id" >
insert into t_user(name,password,sex,birthDay,photo,email)values(#{name},#{password},#{sex},#{birthDay},#{photo},#{email})
</ insert>
< update id = " updateUser" parameterType = " User" >
update t_user set name=#{name},sex=#{sex},birthDay=#{birthDay},photo=#{photo},email=#{email} where id=#{id}
</ update>
< delete id = " deleteByUserId" parameterType = " int" >
delete from t_user where id=#{id}
</ delete>
< select id = " queryUserByPage" resultType = " User" >
select id,name,sex,birthDay,photo ,email from t_user
< if test = " column !=null" > where ${column} like '%${value}%'</ if> limit ${pageSize} offset ${(pageNow-1)*pageSize}
</ select>
< select id = " queryCount" resultType = " int" >
select count(*) from t_user
< if test = " column != null" > where ${column} like '%${value}%'</ if>
</ select>
< select id = " queryUserById" resultType = " User" >
select id,name,sex,birthDay,photo ,email from t_user where id=#{id}
</ select>
< select id = " queryUserByNameAndPassword" resultType = " User" >
select id,name,sex,birthDay,photo ,email from t_user where name=#{name} and password=#{password}
</ select>
</ mapper>
dao-IUserDao
package com. baizhi. dao;
import com. baizhi. entities. User;
import org. apache. ibatis. annotations. Param;
import java. util. List;
public interface IUserDao {
void saveUser ( User user) ;
User queryUserByNameAndPassword ( User user) ;
User queryUserById ( Integer id) ;
void deleteByUserId ( Integer id) ;
List< User> queryUserByPage (
@Param ( value = "pageNow" ) Integer pageNow,
@Param ( value = "pageSize" ) Integer pageSize,
@Param ( value = "column" ) String column,
@Param ( value = "value" ) Object value) ;
int queryCount (
@Param ( value = "column" ) String column,
@Param ( value = "value" ) Object value) ;
void updateUser ( User user) ;
}
service-IUserService
package com. baizhi. service;
import com. baizhi. entities. User;
import java. util. List;
public interface IUserService {
void saveUser ( User user) ;
User queryUserByNameAndPassword ( User user) ;
List< User> queryUserByPage ( Integer pageNow, Integer pageSize,
String column, Object value) ;
int queryUserCount ( String column, Object value) ;
User queryUserById ( Integer id) ;
void deleteByUserIds ( Integer[ ] ids) ;
void updateUser ( User user) ;
}
serviceImplements-IUserServiceImpl
package com. baizhi. service;
import com. baizhi. dao. IUserDao;
import com. baizhi. entities. User;
import org. springframework. beans. factory. annotation. Autowired;
import org. springframework. stereotype. Service;
import org. springframework. transaction. annotation. Propagation;
import org. springframework. transaction. annotation. Transactional;
import java. util. List;
@Service
@Transactional ( propagation = Propagation. SUPPORTS)
public class IUserServiceImpl implements IUserService {
@Autowired
private IUserDao userDAO;
@Transactional ( propagation = Propagation. REQUIRED, readOnly = false )
public void saveUser ( User user) {
userDAO. saveUser ( user) ;
}
public User queryUserByNameAndPassword ( User user) {
User u = userDAO. queryUserByNameAndPassword ( user) ;
return u;
}
public List< User> queryUserByPage ( Integer pageNow, Integer pageSize, String
column, Object value) {
return userDAO. queryUserByPage ( pageNow, pageSize, column, value) ;
}
@Override
public int queryUserCount ( String column, Object value) {
return userDAO. queryCount ( column, value) ;
}
public User queryUserById ( Integer id) {
return userDAO. queryUserById ( id) ;
}
@Transactional ( propagation = Propagation. REQUIRED, readOnly = false )
@Override
public void deleteByUserIds ( Integer[ ] ids) {
for ( int i = 0 ; i < ids. length; i++ ) {
userDAO. deleteByUserId ( ids[ i] ) ;
}
}
@Transactional ( propagation = Propagation. REQUIRED, readOnly = false )
public void updateUser ( User user) {
userDAO. updateUser ( user) ;
}
}
logback.xml
<?xml version="1.0" encoding="UTF-8"?>
< configuration scan = " true" scanPeriod = " 60 seconds" debug = " false" >
< appender name = " STDOUT" class = " ch.qos.logback.core.ConsoleAppender" >
< encoder>
< pattern> %p %c#%M %d{yyyy-MM-dd HH:mm:ss} %m%n</ pattern>
< charset> UTF-8</ charset>
</ encoder>
</ appender>
< appender name = " FILE" class = " ch.qos.logback.core.rolling.RollingFileAppender" >
< rollingPolicy class = " ch.qos.logback.core.rolling.TimeBasedRollingPolicy" >
< fileNamePattern> logs/userLoginFile-%d{yyyyMMdd}.log</ fileNamePattern>
< maxHistory> 30</ maxHistory>
</ rollingPolicy>
< encoder>
< pattern> %p %c#%M %d{yyyy-MM-dd HH:mm:ss} %m%n</ pattern>
< charset> UTF-8</ charset>
</ encoder>
</ appender>
< root level = " ERROR" >
< appender-ref ref = " STDOUT" />
</ root>
< logger name = " org.springframework.jdbc" level = " DEBUG" additivity = " false" >
< appender-ref ref = " STDOUT" />
</ logger>
< logger name = " com.baizhi.dao" level = " TRACE" additivity = " false" >
< appender-ref ref = " STDOUT" />
</ logger>
< logger name = " com.baizhi.controller" level = " DEBUG" additivity = " false" >
< appender-ref ref = " STDOUT" />
</ logger>
</ configuration>
UserModelApplication
package com. baizhi;
import org. mybatis. spring. annotation. MapperScan;
import org. mybatis. spring. annotation. MapperScans;
import org. springframework. boot. SpringApplication;
import org. springframework. boot. autoconfigure. SpringBootApplication;
@SpringBootApplication
@MapperScans ( value = { @MapperScan ( basePackages = "com.baizhi.dao" ) } )
public class UserModelApplication {
public static void main ( String[ ] args) {
SpringApplication. run ( UserModelApplication. class , args) ;
}
}
UserServiceTest
package com. baizhi;
import com. baizhi. entities. User;
import com. baizhi. service. IUserService;
import org. junit. Test;
import org. junit. runner. RunWith;
import org. springframework. beans. factory. annotation. Autowired;
import org. springframework. boot. test. context. SpringBootTest;
import org. springframework. test. context. junit4. SpringRunner;
import java. util. Date;
import static org. junit. Assert. *;
@SpringBootTest ( classes = { UserModelApplication. class } )
@RunWith ( SpringRunner. class )
public class UserServcieTest
{
@Autowired
private IUserService userService;
@Test
public void saveUserTest ( ) {
User user = new User ( "赵⼩六" , true , "123456" , new Date ( ) , "aa.png" , "qq.com" ) ;
userService. saveUser ( user) ;
assertNotNull ( "⽤户ID不为空" , user. getId ( ) ) ;
}
@Test
public void queryUserByNameAndPasswordTests ( ) {
User loginUser = new User ( ) ;
loginUser. setName ( "赵⼩六" ) ;
loginUser. setPassword ( "123456" ) ;
User queryUser = userService. queryUserByNameAndPassword ( loginUser) ;
assertNotNull ( "⽤户ID不为空" , queryUser. getId ( ) ) ;
}
@Test
public void queryUserByPageTests ( ) {
Integer pageNow= 1 ;
Integer pageSize= 10 ;
String column= "name" ;
String value= "⼩" ;
List< User> userList = userService. queryUserByPage ( pageNow, pageSize, column,
value) ;
assertFalse ( userList. isEmpty ( ) ) ;
}
@Test
public void queryUserCountTest ( ) {
String column= "name" ;
String value= "⼩" ;
Integer count = userService. queryUserCount ( column, value) ;
assertTrue ( count!= 0 ) ;
}
@Test
public void queryUserById ( ) {
Integer id= 2 ;
User u= userService. queryUserById ( id) ;
assertNotNull ( u. getName ( ) ) ;
}
@Test
public void deleteByUserIdsTests ( ) {
userService. deleteByUserIds ( new Integer [ ] { 1 , 4 , 3 } ) ;
}
@Test
public void updateUserTests ( ) {
Integer id= 2 ;
User u= userService. queryUserById ( id) ;
assertNotNull ( u. getName ( ) ) ;
u. setSex ( false ) ;
userService. updateUser ( u) ;
User newUser = userService. queryUserById ( 2 ) ;
assertEquals ( "⽤户sex" , false , newUser. isSex ( ) ) ;
}
}
测试接口
用自带的RESTFul测试工具测试
用postman测试
用springMVC的自带的一个rest客户端:
需要在UserModelApplication中添加如下代码:
@Bean
public RestTemplate restTemplate ( ) {
return new RestTemplate ( ) ;
}
package com. baizhi;
import com. baizhi. UserModelApplication;
import com. baizhi. entities. User;
import com. baizhi. service. IUserService;
import org. junit. Test;
import org. junit. runner. RunWith;
import org. springframework. beans. factory. annotation. Autowired;
import org. springframework. boot. test. context. SpringBootTest;
import org. springframework. core. io. FileSystemResource;
import org. springframework. test. context. junit4. SpringRunner;
import org. springframework. util. LinkedMultiValueMap;
import org. springframework. util. MultiValueMap;
import org. springframework. web. client. RestTemplate;
import java. util. Date;
import java. util. HashMap;
import java. util. Map;
import static org. junit. Assert. *;
@SpringBootTest ( classes = { UserModelApplication. class } )
@RunWith ( SpringRunner. class )
public class FormUserControllerTests {
@Autowired
private RestTemplate restTemplate;
private String prefix = "http://localhost:8888/formUserManager" ;
@Test
public void testRegisterUser ( ) {
String url = prefix+ "/registerUser" ;
MultiValueMap< String, Object> formData = new LinkedMultiValueMap < String, Object> ( ) ;
formData. add ( "name" , "王小五" ) ;
formData. add ( "password" , "123456" ) ;
formData. add ( "sex" , "true" ) ;
formData. add ( "birthDay" , "2018-01-26" ) ;
formData. add ( "photo" , "touxiang.jpg" ) ;
formData. add ( "email" , "1152926811@qq.com" ) ;
FileSystemResource fileSystemResource= new FileSystemResource ( "D:\\data\\img\\touxiang.jpg" ) ;
formData. add ( "multipartFile" , fileSystemResource) ;
User user = restTemplate. postForObject ( url, formData, User. class ) ;
assertNotEquals ( "⽤户ID" , user. getId ( ) ) ;
System. out. println ( user) ;
}
@Test
public void testUserLogin ( ) {
String url = prefix + "/userLogin" ;
MultiValueMap< String, Object> formData = new LinkedMultiValueMap < String, Object> ( ) ;
formData. add ( "name" , "王小五" ) ;
formData. add ( "password" , "123456" ) ;
User dbUser = restTemplate. postForObject ( url, formData, User. class ) ;
System. out. println ( dbUser) ;
}
@Test
public void testAddUser ( ) {
String url= prefix+ "/addUser" ;
MultiValueMap< String, Object> formData= new LinkedMultiValueMap < String, Object> ( ) ;
formData. add ( "name" , "赵晓丽" ) ;
formData. add ( "password" , "123456" ) ;
formData. add ( "sex" , "true" ) ;
formData. add ( "birthDay" , "2018-01-26" ) ;
formData. add ( "photo" , "touxiang.jpg" ) ;
formData. add ( "email" , "1152926811@qq.com" ) ;
FileSystemResource fileSystemResource= new FileSystemResource ( "D:\\data\\img\\touxiang.jpg" ) ;
formData. add ( "multipartFile" , fileSystemResource) ;
User user = restTemplate. postForObject ( url, formData, User. class ) ;
assertNotNull ( "⽤户ID" , user. getId ( ) ) ;
}
@Test
public void testUpdateUser ( ) {
String url= prefix+ "/updateUser" ;
MultiValueMap< String, Object> formData= new LinkedMultiValueMap < String, Object>
( ) ;
formData. add ( "id" , "6" ) ;
formData. add ( "name" , "赵铁锤" ) ;
formData. add ( "password" , "123456" ) ;
formData. add ( "sex" , "true" ) ;
formData. add ( "birthDay" , "2018-01-27" ) ;
formData. add ( "photo" , "user1.png" ) ;
formData. add ( "email" , "1152926811@qq.com" ) ;
FileSystemResource fileSystemResource= new FileSystemResource ( "D:\\data\\img\\touxiang.jpg" ) ;
formData. add ( "multipartFile" , fileSystemResource) ;
restTemplate. put ( url, formData) ;
}
@Test
public void testDeleteUser ( ) {
String url= prefix+ "/deleteUserByIds?ids={id}" ;
Map< String, Object> parameters= new HashMap < String, Object> ( ) ;
parameters. put ( "id" , "4,5,6" ) ;
restTemplate. delete ( url, parameters) ;
}
@Test
public void testQueryUserByPage ( ) {
String url= prefix+ "/queryUserByPage?page={page}&rows={rows}&column= {column}&value={value}" ;
Map< String, Object> params= new HashMap < String, Object> ( ) ;
params. put ( "page" , 1 ) ;
params. put ( "rows" , 10 ) ;
params. put ( "column" , "name" ) ;
params. put ( "value" , "⼩" ) ;
User[ ] users= restTemplate. getForObject ( url, User[ ] . class , params) ;
assertNotNull ( "⽤户数据" , users) ;
}
@Test
public void testQueryUserCount ( ) {
String url= prefix+ "/queryUserCount?column={column}&value={value}" ;
Map< String, Object> parameters= new HashMap < > ( ) ;
parameters. put ( "column" , "name" ) ;
parameters. put ( "value" , "晓" ) ;
Integer count = restTemplate. getForObject ( url, Integer. class , parameters) ;
assertNotNull ( count) ;
}
@Test
public void testQueryUserById ( ) {
String url= prefix+ "/queryUserById?id={id}" ;
Map< String, Object> parameters= new HashMap < > ( ) ;
parameters. put ( "id" , "2" ) ;
User user = restTemplate. getForObject ( url, User. class , parameters) ;
assertNotNull ( "⽤户ID" , user. getId ( ) ) ;
}
}
package com.baizhi;
import com.baizhi.entities.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.FileSystemResource;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.*;
/**
* @Author:Caijq
* 创建日期:2020/11/6
* 类的作用:RestUserControllerTests
*/
@SpringBootTest(classes = {UserModelApplication.class})
@RunWith(SpringRunner.class)
public class RestUserControllerTests {
@Autowired
private RestTemplate restTemplate;
private String prefix = "http://localhost:8888/restUserManager";
@Test
public void testRegisterUser(){
String url=prefix+"/registerUser";
//模拟表单数据
MultiValueMap<String,Object> formData=new LinkedMultiValueMap<String,Object>
();
User user =new User("张晓磊",true,"123456",new Date(),"aa.png","1152926811@qq.com");
formData.add("user",user);
//模拟⽂件上传
FileSystemResource fileSystemResource=new FileSystemResource("D:\\data\\img\\touxiang.jpg");
formData.add("multipartFile",fileSystemResource);
User registerUser = restTemplate.postForObject(url, formData, User.class);
assertNotEquals("⽤户ID",registerUser.getId());
}
@Test
public void testUserLogin(){
String url=prefix+"/userLogin";
//模拟表单数据
User user=new User();
user.setName("张晓磊");
user.setPassword("123456");
User loginUser = restTemplate.postForObject(url, user, User.class);
assertNotEquals("⽤户ID",loginUser.getId());
}
@Test
public void testAddUser(){
String url=prefix+"/addUser";
//模拟表单数据
MultiValueMap<String,Object> formData=new LinkedMultiValueMap<String,Object>
();
User user =new User("温晓琪",true,"123456",new
Date(),"aa.png","1152926811@qq.com");
formData.add("user",user);
//模拟⽂件上传
FileSystemResource fileSystemResource=new
FileSystemResource("/Users/admin/Desktop/head.png");
formData.add("multipartFile",fileSystemResource);
User dbUser = restTemplate.postForObject(url, formData, User.class);
assertNotNull("⽤户ID",dbUser.getId());
}
@Test
public void testUpdateUser(){
String url=prefix+"/updateUser";
//模拟表单数据
MultiValueMap<String,Object> formData=new LinkedMultiValueMap<String,Object>
();
User user =new User("温晓琪",false,"123456",new
Date(),"aa.png","1152926811@qq.com");
user.setId(9);
formData.add("user",user);
//模拟⽂件上传
FileSystemResource fileSystemResource=new
FileSystemResource("/Users/admin/Desktop/head.png");
formData.add("multipartFile",fileSystemResource);
restTemplate.put(url, formData);
}
@Test
public void testDeleteUser(){
String url=prefix+"/deleteUserByIds?ids={id}";
Map<String,Object> parameters=new HashMap<String,Object>();
parameters.put("id","4,5,6");
restTemplate.delete(url,parameters);
}
@Test
public void testQueryUserByPage(){
String url=prefix+"/queryUserByPage?page={page}&rows={rows}&column= {column}&value={value}";
Map<String, Object> params= new HashMap<String, Object>();
params.put("page",1);
params.put("rows",10);
params.put("column","name");
params.put("value","⼩");
User[] users=restTemplate.getForObject(url,User[].class,params);
assertNotNull("⽤户数据",users);
}
@Test
public void testQueryUserCount(){
String url=prefix+"/queryUserCount?column={column}&value={value}";
//模拟表单数据
Map<String,Object> parameters=new HashMap<>();
parameters.put("column","name");
parameters.put("value","晓");
Integer count = restTemplate.getForObject(url, Integer.class,parameters);
assertNotNull(count);
}
@Test
public void testQueryUserById(){
String url=prefix+"/queryUserById?id={id}";
//模拟表单数据
Map<String,Object> parameters=new HashMap<>();
parameters.put("id","2");
User user = restTemplate.getForObject(url, User.class,parameters);
assertNotNull("⽤户ID",user.getId());
}
}