springBoot小练习(增删改查)

练习增删改查业务

创建一个用户表,对表中的内容实现增删改查业务,限时30分钟

相关配置文件

建表语句

1
2
3
4
5
6
7
8
9
DROP TABLE IF EXISTS `user`;

CREATE TABLE `user` (
`ID` INT(11) NOT NULL AUTO_INCREMENT,
`NAME` VARCHAR(30) DEFAULT NULL,
`BIRTHDAY` DATETIME DEFAULT NULL,
`ADDRESS` VARCHAR(200) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;

插入数据

1
insert  into `user`(`ID`,`NAME`,`BIRTHDAY`,`ADDRESS`) values (1,'夏言','1573-01-01 00:00:00','桂州村'),(2,'严嵩','1587-01-01 00:00:00','分宜县城介桥村'),(3,'徐阶','1580-01-01 00:00:00','明松江府华亭县'),(4,'高拱','1566-01-01 00:00:00','河南省新郑市高老庄村'),(5,'张居正','1558-01-01 00:00:00','江陵');

配置文件

注意修改数据库配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
server:
port: 8070

spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/andrewdb
username: root
password: 123456

mybatis:
typeAliasesPackage: com.ypjiao.pojo
mapperLocations: classpath:mappers/*.xml

logging:
level:
cn.tedu.mapper: debug
  • 相关依赖包
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<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>cn.ypjiao</groupId>
<artifactId>sc-mybatis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>sc-mybatis</name>
<url>http://maven.apache.org</url>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.4.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.0</version>
</dependency>
</dependencies>
</project>

参考答案

实体类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.ypjiao.pojo;
import org.springframework.format.annotation.DateTimeFormat;

import java.util.Date;


public class User {
private Integer id;
private String name;
//用于限定识别传入的字符串日期格式
@DateTimeFormat(pattern="yyyy-MM-dd")
//用于格式化Date类型时间输出的格式
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date birthday;
private String address;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
public Date getBirthday() {
return birthday;
}

public void setBirthday(Date birthday) {
this.birthday = birthday;
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", birthday=" + birthday +
", id=" + id +
", address='" + address + '\'' +
'}';
}
}

Mapper接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com.ypjiao.mapper;

import com.ypjiao.pojo.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

public interface UserMapper {
@Select("select * from user")
List<User> getAll();
@Select("select * from user where id=#{id}")
User getById(@Param("id")Integer id);
@Insert("insert into user(name,birthday,address) " +
"values(#{user.name},#{user.birthday},#{user.address})")
void insertUser(@Param("user") User user);
@Update("update user set name=#{user.name},birthday=#{user.birthday},address=#{user.birthday}" + "where id=#{user.id}")
void updateUser(@Param("user") User user);

/**
* 如果只有一个参数值则可以不需要@Param注解
* @param id
* @return
*/
@Delete("delete from user where id=#{id}")
User delete(Integer id);
}

servic接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.ypjiao.service;

import com.ypjiao.pojo.User;

import java.util.List;

public interface UserService {
List<User> getAll();
User getById(Integer id);
void insertUser(User user);
User deleteUser(Integer id);
void updateUser(User user);

}

service实现类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package com.ypjiao.service;

import com.ypjiao.mapper.UserMapper;
import com.ypjiao.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class UserServiceImpl implements UserService{
@Autowired
UserMapper mapper;
public List<User> getAll(){
List<User> list = mapper.getAll();
System.out.println(list);
return list;
}
public User getById(Integer id){
return mapper.getById(id);
}
public void insertUser(User user){
mapper.insertUser(user);
}
public void updateUser(User user){
mapper.updateUser(user);
}
public User deleteUser(Integer id){
return mapper.delete(id);
}
}

Controller实现类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.ypjiao.Controller;

import com.ypjiao.pojo.User;
import com.ypjiao.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/User/")
public class UserController {
@Autowired
public UserService userService;
@RequestMapping("getAll")
public List<User> getAll(){
return userService.getAll();
}
@RequestMapping("getById/{id}")
public User getById(@PathVariable Integer id){
return userService.getById(id);
}
/**
*springMVC支持restful风格封装对象,可以不需要@PathVariable注解
*/
@RequestMapping("insert/{name}/{birthday}/{address}")
public String insertUser(User user){
try{
userService.insertUser(user);
return "insert success";
}catch (Exception e){
e.printStackTrace();
return "insert error";
}
}
@RequestMapping("update/{name}/{birthday}/{address}/{id}")
public String updateUser(User user){
try {
userService.updateUser(user);
return "update success";
} catch (Exception e) {
e.printStackTrace();
return "delete success";
}
}
@RequestMapping("deleteUser/{id}")
public User deleteUser(@PathVariable Integer id){
try {
return userService.deleteUser(id);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}

Application启动类

1
2
3
4
5
6
7
8
9
10
11
12
package com.ypjiao;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.ypjiao.mapper") //扫描Mapper包路径获取mapper对象
public class RunApplication {
public static void main(String[] args) {
SpringApplication.run(RunApplication.class,args);
}
}

springBoot小练习(增删改查)
https://andrewjiao.github.io/2019/07/26/springBoot项目练习/
作者
Andrew_Jiao
发布于
2019年7月26日
许可协议