springboot整合ssm

创建项目

aYtAr8

aYtkKf

推荐maven仓库:

1
2
3
4
5
6
<mirror>
<id>aliyunmaven</id>
<mirrorOf>*</mirrorOf>
<name>阿里云公共仓库</name>
<url>https://maven.aliyun.com/repository/public</url>
</mirror>

简单介绍pom

自带的 :

1
2
3
4
5
6
7
8
9
10
11
12
<!--springmvc tomcat-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>

当然不止这些,但是剩下的都容易看出来是什么

我们需要添加的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
   	通用mapper
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.1.5</version>
</dependency>

自带监控的连接池
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.17</version>
</dependency>
打印日志
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>

创建文件夹

aYtP2t

service:

UserService

1
2
3
4
5
6
7
8
9
package com.ls.service;

import com.ls.domain.User;

import java.util.List;

public interface UserService {
List<User> listUser();
}

UserServiceimpl

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.ls.service;

import com.ls.dao.UserMapper;
import com.ls.domain.User;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserServiceimpl implements UserService {
//@Autowired //这个根据类型匹配,与@Resource 作用一致
@Resource //这个默认是根据名称匹配,与@Autowired 作用一致
UserMapper userMapper;

@Override
public List<User> listUser() {
return userMapper.selectAll();
}
}

domain:

user

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
58
59
60
61
62
63
package com.ls.domain;

import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.format.annotation.DateTimeFormat;

import javax.persistence.Column;
import javax.persistence.Id;
import java.util.Date;

public class User {
@Id
@Column(name = "uid")
private Integer uid;

private String username;


@JsonFormat(pattern = "yyyy-MM-dd") //从后端接收这个格式的日期数据
@DateTimeFormat(pattern = "yyyy-MM-dd") //从前端接收数据
private Date birthday;

public User() {
}

public User(Integer uid, String username, Date birthday) {
this.uid = uid;
this.username = username;
this.birthday = birthday;
}

@Override
public String toString() {
return "User{" +
"uid=" + uid +
", username='" + username + '\'' +
", birthday=" + birthday +
'}';
}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public Date getBirthday() {
return birthday;
}

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

public Integer getUid() {
return uid;
}

public void setUid(Integer uid) {
this.uid = uid;
}
}

dao:

UserMapper:

1
2
3
4
5
6
7
8
9
10
package com.ls.dao;

import com.ls.domain.User;
import tk.mybatis.mapper.common.Mapper;

@org.apache.ibatis.annotations.Mapper
public interface UserMapper extends Mapper<User> {


}

controller:

UserController:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.ls.controller;

import com.ls.domain.User;
import com.ls.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping(path = "/user")
public class UserController {

@Autowired
UserService userService;

@GetMapping(value = "/all")
public List<User> listUser() {
return userService.listUser();
}
}

至此,项目完成,接下来是数据库数据

数据库

数据库 三个字段 uid主键数字类型 username 字符类型 bitrhday日期类型,自己去写吧,太简单了

德鲁伊连接池

这是一个更强的数据库链接工具,并且带着可视化窗口,配置也比较繁琐,所以独立来说

pom:

1
2
3
4
5
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.17</version>
</dependency>

这个我们刚刚导入过了

配置文件:

这个需要超多配置,我们分成两个文件存放

yml:

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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
spring:
datasource:
druid:
password: root
username: root
url: jdbc:mysql://127.0.0.1:3306/mybatis-01?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Hongkong
driver-class-name: com.mysql.cj.jdbc.Driver

#初始化时建立物理连接的个数,默认值0
initial-size: 1

#最大连接池数量,默认值8
max-active: 20

#最小连接池数量
min-idle: 1

#获取连接时最大等待时间,单位毫秒。配置了maxWait之后,
#缺省启用公平锁,并发效率会有所下降,
#如果需要可以通过配置useUnfairLock属性为true使用非公平锁。
max-wait: 60000

#是否缓存preparedStatement,也就是PSCache。
#PSCache对支持游标的数据库性能提升巨大,比如说oracle。
#在mysql5.5以下的版本中没有PSCache功能,建议关闭掉。
#5.5及以上版本有PSCache,建议开启。默认false不开启
pool-prepared-statements: true

#要启用PSCache,必须配置大于0,当大于0时,
#poolPreparedStatements自动触发修改为true。
#在Druid中,不会存在Oracle下PSCache占用内存过多的问题,
#可以把这个数值配置大一些,比如说100 ,默认值 -1
max-open-prepared-statements: 20

#用来检测连接是否有效的sql,要求是一个查询语句。
#如果validationQuery为null,testOnBorrow、testOnReturn、
#testWhileIdle都不会其作用。在mysql中通常为select 'x',在oracle中通常为
#select 1 from dual
validation-query: SELECT 'x'

#申请连接时执行validationQuery检测连接是否有效,
#做了这个配置会降低性能。默认false关闭
test-on-borrow: false

#归还连接时执行validationQuery检测连接是否有效,
#做了这个配置会降低性能,默认false关闭
test-on-return: false

# 建议配置为true,不影响性能,并且保证安全性。
# 申请连接的时候检测,如果空闲时间大于
# timeBetweenEvictionRunsMillis,
# 执行validationQuery检测连接是否有效。默认false
test-while-idle: true

# 有两个含义:
# 1) Destroy线程会检测连接的间隔时间
# 2) testWhileIdle的判断依据,详细看testWhileIdle属性的说明
time-between-eviction-runs-millis: 60000

#Destory线程中如果检测到当前连接的最后活跃时间和当前时间的差值大于
#minEvictableIdleTimeMillis,则关闭当前连接。
min-evictable-idle-time-millis: 300000

#属性类型是字符串,通过别名的方式配置扩展插件,
#常用的插件有:
#监控统计用的filter:stat
#日志用的filter:log4j
#防御sql注入的filter:wall
filters: stat,wall,log4j #配置多个英文逗号分隔

# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# 合并多个DruidDataSource的监控数据
useGlobalDataSourceStat: true

properties:

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
# WebStatFilter配置,说明请参考Druid Wiki,配置_配置WebStatFilter
#是否启用StatFilter默认值false 第二个表示是否拦截请求,只有拦截到请求才会执行操作,选择了都拦截。第三个是放行的静态资源,比如最后的druid是可视化web界面
spring.datasource.druid.web-stat-filter.enabled= true
spring.datasource.druid.web-stat-filter.url-pattern= /*
spring.datasource.druid.web-stat-filter.exclusions= *.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*
#身份标识 从session中获取
#spring.datasource.druid.web-stat-filter.session-stat-enable=
#spring.datasource.druid.web-stat-filter.session-stat-max-count=
#身份标识 从cookie中获取
#spring.datasource.druid.web-stat-filter.principal-session-name=
#spring.datasource.druid.web-stat-filter.principal-cookie-name=
#spring.datasource.druid.web-stat-filter.profile-enable=

# StatViewServlet配置,说明请参考Druid Wiki,配置_StatViewServlet配置
#是否启用StatViewServlet(监控页面)默认值为false(考虑到安全问题默认并未启动,如需启用建议设置密码或白名单以保障安全)
# reset 开放监控清空按钮,,选择false就不会出现删除掉所有监控的可能 allow表示允许访问的 deny 表示禁止访问的
spring.datasource.druid.stat-view-servlet.enabled= true
spring.datasource.druid.stat-view-servlet.url-pattern= /druid/*
spring.datasource.druid.stat-view-servlet.reset-enable= false
spring.datasource.druid.stat-view-servlet.login-username= admin
spring.datasource.druid.stat-view-servlet.login-password= admin123
spring.datasource.druid.stat-view-servlet.allow= 127.0.0.1
spring.datasource.druid.stat-view-servlet.deny= 192.168.16.200

# Spring监控配置,说明请参考Druid Github Wiki,配置_Druid和Spring关联监控配置
#spring.datasource.druid.aop-patterns= # Spring监控AOP切入点,如x.y.z.service.*,配置多个英文逗号分隔

注入

显然那么多配置文件,是需要配合着具体的类(数据源)来实现的。

这个是配置类注入,但是我们的springbootapplication其实就是一个配置类,所以可以把代码直接放在启动类中,当然独立出来也没关系

1
2
3
4
5
6
7
8
@Configuration
public class DataSourceConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource.druid")
public DataSource dataSourceOne() {
return DruidDataSourceBuilder.create().build();
}
}

启动项目,浏览器访问 http://localhost:8080/druid/login.html

至此,完毕,两个配置文件,一个注入

springbootssm项目练习

数据库数据

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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/*
SQLyog Ultimate v8.32
MySQL - 8.0.20 : Database - ssm
*********************************************************************
*/

/*!40101 SET NAMES utf8 */;

/*!40101 SET SQL_MODE=''*/;

/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`ssm` /*!40100 DEFAULT CHARACTER SET utf8 */ /*!80016 ;

USE `ssm`;

/*Table structure for table `tab_category` */

DROP TABLE IF EXISTS `tab_category`;

CREATE TABLE `tab_category` (
`category_id` int NOT NULL AUTO_INCREMENT COMMENT '分类ID',
`category_name` varchar(50) DEFAULT NULL COMMENT '分类名称',
PRIMARY KEY (`category_id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

/*Data for the table `tab_category` */

insert into `tab_category`(`category_id`,`category_name`) values (1,'高级洗护'),(2,'车内饰品'),(3,'清洁美容');

/*Table structure for table `tab_product` */

DROP TABLE IF EXISTS `tab_product`;

CREATE TABLE `tab_product` (
`product_id` int NOT NULL AUTO_INCREMENT COMMENT '商品ID',
`product_name` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '商品名称',
`sale_price` decimal(10,2) DEFAULT NULL COMMENT '商品售价',
`commission` varchar(6) DEFAULT NULL COMMENT '销售提成',
`stock` int DEFAULT NULL COMMENT '商品库存',
`is_sale` tinyint DEFAULT NULL COMMENT '是否上架:1上架 -1下架',
`category_id` int DEFAULT NULL COMMENT '分类ID',
`product_desc` text CHARACTER SET utf8 COLLATE utf8_general_ci COMMENT '商品描述',
`create_time` datetime DEFAULT NULL COMMENT '添加时间',
PRIMARY KEY (`product_id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;

/*Data for the table `tab_product` */

insert into `tab_product`(`product_id`,`product_name`,`sale_price`,`commission`,`stock`,`is_sale`,`category_id`,`product_desc`,`create_time`) values (1,'香百年(Carori)z291 汽车香水 ','65.00','0.05',100,1,2,'香百年(Carori)z291 汽车香水 车载香薰 车用创意可乐瓶藤条进口摆件 车用除异味车家装饰品孕妇婴儿可用品','2020-06-30 12:16:29'),(2,'尚朴高档车载香水','270.00','0.06',500,1,2,'尚朴高档车载香水车内装饰摆件车用饰品汽车用品大全持久淡香男士香薰 一鹿平安-星光银','2020-06-15 08:22:51'),(3,'亿力 YILI 家用洗车机','309.00','0.1',50,1,3,'亿力 YILI 家用洗车机 高压清洗机 洗车神器 多功能清洗机 洗车水枪 汽车用品 YLQ4435C','2020-06-16 10:36:10'),(4,'刷鑫宝(SHUAXINBAO)汽车内饰清洗','32.00','0.6',200,1,3,'刷鑫宝(SHUAXINBAO)汽车内饰清洗剂泡沫清洁剂车内清洁免洗多功能泡沫洗车用品','2020-06-21 15:12:39'),(5,'龟牌(Turtle Wax)汽车蜡','69.00','0.5',600,1,3,'龟牌(Turtle Wax)汽车蜡新车蜡上光镀膜蜡镀晶镀膜漆面防护保养蜡打腊汽车用品黑白色','2020-06-29 11:32:29'),(6,'巴孚(BAFU)G17 plus养护型 燃油清净剂','109.00','0.03',160,1,1,'巴孚(BAFU)G17 plus养护型 燃油清净剂 汽油添加剂 燃油宝 10支装 汽车用品','2020-06-16 18:15:12');

/*Table structure for table `tab_sale` */

DROP TABLE IF EXISTS `tab_sale`;

CREATE TABLE `tab_sale` (
`sale_id` int NOT NULL AUTO_INCREMENT COMMENT '自增ID',
`uid` int DEFAULT NULL COMMENT '用户ID',
`pid` int DEFAULT NULL COMMENT '商品ID',
`sale_num` int DEFAULT NULL COMMENT '销售数量',
`sale_time` date DEFAULT NULL COMMENT '销售时间',
PRIMARY KEY (`sale_id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;

/*Data for the table `tab_sale` */

insert into `tab_sale`(`sale_id`,`uid`,`pid`,`sale_num`,`sale_time`) values (1,3,1,3,'2020-06-05'),(2,3,1,8,'2020-07-01'),(3,3,2,10,'2020-07-02'),(4,1,1,2,'2020-06-20'),(5,1,1,15,'2020-07-10'),(6,1,2,5,'2020-07-11'),(7,2,6,10,'2020-07-05');

/*Table structure for table `tab_user` */

DROP TABLE IF EXISTS `tab_user`;

CREATE TABLE `tab_user` (
`uid` int NOT NULL AUTO_INCREMENT COMMENT '用户ID',
`username` varchar(50) DEFAULT NULL COMMENT '用户名',
`password` varchar(50) DEFAULT NULL COMMENT '密码',
`sex` varchar(4) DEFAULT NULL COMMENT '性别',
`birthday` date DEFAULT NULL COMMENT '生日',
PRIMARY KEY (`uid`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

/*Data for the table `tab_user` */

insert into `tab_user`(`uid`,`username`,`password`,`sex`,`birthday`) values (1,'张杰','123','男','1997-10-12'),(2,'小梦','123','女','1999-02-16'),(3,'李丽','123','女','1998-12-16');

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

演示一个逆向工程

aYtC8I我前面的博客说过逆向工程,所以这里不再说了,首先找到上面的目录。然后打开cmd,java -jar mybatis-generator-gui.jar ,就完事了。

aYtixP

生成界面的左上角需要自己指定添加数据库,然后双击你添加的东西,你就可以看到数据库下的表了。

然后双击一个表,选择你的项目位置,看找我上图的勾选,没问题的。

生成好了之后:

dao中的接口自带方法删掉,并且实现通用mapper,加上@mapper注解

domain实体类中的id加上@id,表明映射用@table

删除mapper.xml 中的初始化方法,我们使用通用mapper

之后如法炮制,把剩余四个都弄出来

put请求(插入数据)

dao:

1
2
3
4
5
6
7
8
9
package com.ls.dao;

import com.ls.domain.Category;
import tk.mybatis.mapper.common.Mapper;

@org.apache.ibatis.annotations.Mapper
public interface CategoryDAO extends Mapper<Category> {

}

domain:

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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package com.ls.domain;

import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;

/**
* @author
*/
@Table(name = "tab_category")
public class Category implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 分类ID
*/
@Id
private Integer categoryId;
/**
* 分类名称
*/
private String categoryName;

public Integer getCategoryId() {
return categoryId;
}

public void setCategoryId(Integer categoryId) {
this.categoryId = categoryId;
}

public String getCategoryName() {
return categoryName;
}

public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}

@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (that == null) {
return false;
}
if (getClass() != that.getClass()) {
return false;
}
Category other = (Category) that;
return (this.getCategoryId() == null ? other.getCategoryId() == null : this.getCategoryId().equals(other.getCategoryId()))
&& (this.getCategoryName() == null ? other.getCategoryName() == null : this.getCategoryName().equals(other.getCategoryName()));
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((getCategoryId() == null) ? 0 : getCategoryId().hashCode());
result = prime * result + ((getCategoryName() == null) ? 0 : getCategoryName().hashCode());
return result;
}

@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", categoryId=").append(categoryId);
sb.append(", categoryName=").append(categoryName);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}

service:

1
2
3
4
5
6
7
8
9
package com.ls.service;

import com.ls.domain.Category;

public interface CategoryService {

Integer insert(Category category);
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.ls.service;

import com.ls.dao.CategoryDAO;
import com.ls.domain.Category;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
@Transactional
public class CategoryServiceImpl implements CategoryService {

@Resource
CategoryDAO categoryDAO;

@Override
public Integer insert(Category category) {
return categoryDAO.insert(category);
}
}

@Transactional 解决事物问题的注解与@Service 都在service的实现类上添加,抽象只是为了解决耦合

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
package com.ls.controller;

import com.ls.domain.Category;
import com.ls.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("category")
public class CategoryController {
@Autowired
CategoryService categoryService;


//表单提交,实体类接收参数
@PutMapping("put01")
public String put01(Category category) {
Integer insert = categoryService.insert(category);
return insert.toString();
}

//前端传递json过来,用requestBody接收
@PutMapping("put02")
public String put02(@RequestBody Category category) {
Integer insert = categoryService.insert(category);
return insert.toString();
}
}

postman:

表单提交方式:

aYtEqS传递json方式:

aYtZVg

使用了rest风格的之后,接收返回都是json格式,rest风格的不同请求对应着不同的请求方式,只有对的请求方式,才会成功响应

PUT请求:如果两个请求相同,后一个请求会把第一个请求覆盖掉。(所以PUT用来改资源)

post请求(更新数据)

dao:

1
2
3
4
5
6
7
8
9
package com.ls.dao;

import com.ls.domain.Product;
import tk.mybatis.mapper.common.Mapper;

@org.apache.ibatis.annotations.Mapper
public interface ProductDAO extends Mapper<Product> {

}

domain:

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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
package com.ls.domain;

import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;

/**
* @author
*/
@Table(name = "tab_product")
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 商品ID
*/
@Id
private Integer productId;
/**
* 商品名称
*/
private String productName;
/**
* 商品售价
*/
private BigDecimal salePrice;
/**
* 销售提成
*/
private String commission;
/**
* 商品库存
*/
private Integer stock;
/**
* 是否上架:1上架 -1下架
*/
private Byte isSale;
/**
* 分类ID
*/
private Integer categoryId;
/**
* 添加时间
*/
private Date createTime;
/**
* 商品描述
*/
private String productDesc;

public Integer getProductId() {
return productId;
}

public void setProductId(Integer productId) {
this.productId = productId;
}

public String getProductName() {
return productName;
}

public void setProductName(String productName) {
this.productName = productName;
}

public BigDecimal getSalePrice() {
return salePrice;
}

public void setSalePrice(BigDecimal salePrice) {
this.salePrice = salePrice;
}

public String getCommission() {
return commission;
}

public void setCommission(String commission) {
this.commission = commission;
}

public Integer getStock() {
return stock;
}

public void setStock(Integer stock) {
this.stock = stock;
}

public Byte getIsSale() {
return isSale;
}

public void setIsSale(Byte isSale) {
this.isSale = isSale;
}

public Integer getCategoryId() {
return categoryId;
}

public void setCategoryId(Integer categoryId) {
this.categoryId = categoryId;
}

public Date getCreateTime() {
return createTime;
}

public void setCreateTime(Date createTime) {
this.createTime = createTime;
}

public String getProductDesc() {
return productDesc;
}

public void setProductDesc(String productDesc) {
this.productDesc = productDesc;
}

@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (that == null) {
return false;
}
if (getClass() != that.getClass()) {
return false;
}
Product other = (Product) that;
return (this.getProductId() == null ? other.getProductId() == null : this.getProductId().equals(other.getProductId()))
&& (this.getProductName() == null ? other.getProductName() == null : this.getProductName().equals(other.getProductName()))
&& (this.getSalePrice() == null ? other.getSalePrice() == null : this.getSalePrice().equals(other.getSalePrice()))
&& (this.getCommission() == null ? other.getCommission() == null : this.getCommission().equals(other.getCommission()))
&& (this.getStock() == null ? other.getStock() == null : this.getStock().equals(other.getStock()))
&& (this.getIsSale() == null ? other.getIsSale() == null : this.getIsSale().equals(other.getIsSale()))
&& (this.getCategoryId() == null ? other.getCategoryId() == null : this.getCategoryId().equals(other.getCategoryId()))
&& (this.getCreateTime() == null ? other.getCreateTime() == null : this.getCreateTime().equals(other.getCreateTime()))
&& (this.getProductDesc() == null ? other.getProductDesc() == null : this.getProductDesc().equals(other.getProductDesc()));
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((getProductId() == null) ? 0 : getProductId().hashCode());
result = prime * result + ((getProductName() == null) ? 0 : getProductName().hashCode());
result = prime * result + ((getSalePrice() == null) ? 0 : getSalePrice().hashCode());
result = prime * result + ((getCommission() == null) ? 0 : getCommission().hashCode());
result = prime * result + ((getStock() == null) ? 0 : getStock().hashCode());
result = prime * result + ((getIsSale() == null) ? 0 : getIsSale().hashCode());
result = prime * result + ((getCategoryId() == null) ? 0 : getCategoryId().hashCode());
result = prime * result + ((getCreateTime() == null) ? 0 : getCreateTime().hashCode());
result = prime * result + ((getProductDesc() == null) ? 0 : getProductDesc().hashCode());
return result;
}

@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", productId=").append(productId);
sb.append(", productName=").append(productName);
sb.append(", salePrice=").append(salePrice);
sb.append(", commission=").append(commission);
sb.append(", stock=").append(stock);
sb.append(", isSale=").append(isSale);
sb.append(", categoryId=").append(categoryId);
sb.append(", createTime=").append(createTime);
sb.append(", productDesc=").append(productDesc);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}

service:

1
2
3
4
5
6
7
8
9
package com.ls.service;

import com.ls.domain.Product;

public interface ProductService {

public void updateProduct(Product product);
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.ls.service;

import com.ls.dao.ProductDAO;
import com.ls.domain.Product;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
@Transactional
public class ProductServiceImpl implements ProductService {
@Resource
ProductDAO productDAO;


@Override
public void updateProduct(Product product) {
productDAO.updateByPrimaryKeySelective(product);
}
}

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
package com.ls.controller;

import com.ls.domain.Product;
import com.ls.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(path = "/product")
public class ProductController {

@Autowired
ProductService productService;


@PostMapping(value = "/update01")
public void update01(@RequestBody Product product) {
System.out.println(product);
productService.updateProduct(product);
}

}

post拥有请求体,信息放在请求体内

Post请求:后一个请求不会把第一个请求覆盖掉。(所以Post用来增资源)

get请求(查询):

dao:

不变,还是什么都不加

domain:

不变,还是什么都不加

service:

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

import com.ls.domain.Product;

import java.util.List;

public interface ProductService {

public void updateProduct(Product product);

public List<Product> SearchToList01(Product product);
}

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
package com.ls.service;

import com.alibaba.druid.util.StringUtils;
import com.ls.dao.ProductDAO;
import com.ls.domain.Product;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.StringUtil;

import javax.annotation.Resource;
import java.util.List;

@Service
@Transactional
public class ProductServiceImpl implements ProductService {
@Resource
ProductDAO productDAO;


@Override
public void updateProduct(Product product) {
productDAO.updateByPrimaryKeySelective(product);
}

@Override
public List<Product> SearchToList01(Product product) {
Example example = new Example(Product.class);
Example.Criteria criteria = example.createCriteria();

if (!StringUtils.isEmpty(product.getProductName())) {
criteria.andLike("productName", product.getProductName());
}
if (StringUtil.isEmpty(product.getSalePrice().toString())) {
criteria.andGreaterThan("salePrice", product.getSalePrice().toString());
}

List<Product> products = productDAO.selectByExample(example);
return products;
}
}

这里是查询一个动态拼接的模糊查询+动态拼接的大于某个价格的多个结果的题