spring boot(2) 连接数据库
使用国产数据库连接池Druid
maven添加:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.21</version>
</dependency>
maven中有一个问题,自动生成项目的时候没有版本号,这里是报错的,说找不到依赖:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.5.3</version>
</plugin>
</plugins>
</build>
在resources目录下新建application.yml:
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
druid:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test_crm?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8
username: root
password: root123456
initial-size: 5
min-idle: 5
max-active: 20
max-wait: 30000
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 300000
validation-query: select '1' from dual
test-while-idle: true
test-on-borrow: false
test-on-return: false
pool-prepared-statements: true
max-open-prepared-statements: 20
max-pool-prepared-statement-per-connection-size: 20
filters: stat,wall
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
web-stat-filter:
enabled: true
url-pattern: /*
exclusions: '*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*'
stat-view-servlet:
enabled: true
url-pattern: /druid/*
reset-enable: false
login-username: root
login-password: 123456
filter:
stat:
log-slow-sql: true
启动项目,访问 http://localhost:8080/druid 用配置里的账号密码登入说明成功
使用MyBatis
不使用xml
maven
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
流程(不使用xml):
- 先编写数据库表的类
- 编写表操作的接口(使用@Mapper不需要写实现类了,使用@Repository注册到IOC)
- 编写服务接口
- 编写服务接口实现类(使用@Service注册注册到IOC,因为这里需要调用Mapper接口实现类实例,使用@Autowired获取实例)
- 接口去调用服务接口实现类获取数据(这里也使用@Autowired获取服务接口实现类的实例)
目录:
- java
- com.example.springboot01
- controller
- HelloController.java
- GetPlayController.java(修改)
- PostPlayController.java
- ret
- RetCode.java
- RetResult.java
- RetResponse.java
- GlobalExceptionHandler.java
- validation
- dto(数据库表对应类,新建)
- mapper(表操作接口与实现类,新建)
- PlayerMapper.java(表操作接口与实现类,新建)
- service(服务接口与实现类,新建)
- PlayerService.java(服务接口,新建)
- PlayerServiceImpl.java(服务接口实现类,新建)
- Springboot01Application.java
Player.java 数据库表对应类:
package com.example.springboot01.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Player {
private int player_id;
private int team_id;
private String player_name;
private float height;
}
PlayerMapper.java 表操作接口与实现类:
package com.example.springboot01.mapper;
import com.example.springboot01.dto.Player;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface PlayerMapper {
@Select("SELECT * FROM player WHERE player_id = #{id}")
List<Player> selectPlayer(int id);
}
PlayerService.java 服务接口:
package com.example.springboot01.service;
import com.example.springboot01.dto.Player;
import java.util.List;
public interface PlayerService {
List<Player> selectPlayer(int id);
}
PlayerServiceImpl.java 服务接口实现类:
package com.example.springboot01.service;
import com.example.springboot01.dto.Player;
import com.example.springboot01.mapper.PlayerMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class PlayerServiceImpl implements PlayerService{
@Autowired
PlayerMapper playerMapper;
@Override
public List<Player> selectPlayer(int id) {
return playerMapper.selectPlayer(id);
}
}
GetPlayController.java 修改:
package com.example.springboot01.controller;
import com.example.springboot01.dto.Player;
import com.example.springboot01.ret.RetResponse;
import com.example.springboot01.ret.RetResult;
import com.example.springboot01.service.PlayerServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/play")
public class GetPlayController {
@GetMapping("/")
public String getPlays(){
return "这是get请求";
}
@GetMapping("/{id}")
public String getPlay(@PathVariable("id") int id){
return "id: "+id;
}
@GetMapping("")
public String getPlay2(@RequestParam("id") int id){
return "id2: "+id;
}
@GetMapping("/user")
public String getPlayUser(@RequestParam Map<String, Object> params){
return "name: "+params.get("name")+" id: "+params.get("id");
}
@GetMapping("/users")
public String getPlayUser2(@RequestParam int[] ids){
String str = "";
for(int id: ids){
System.out.println(id);
str = str + "id"+id+": "+id+" ";
}
return str;
}
@Autowired
PlayerServiceImpl playerServiceImpl;
@GetMapping("/player")
public RetResult<Object> getPlayers(@RequestParam int id){
List<Player> players= playerServiceImpl.selectPlayer(id);
return RetResponse.success(players);
}
}
URL是 http://127.0.0.1:8080/play/player?id=10001
结果:
{
"code": 200,
"msg": "success",
"data": [
{
"player_id": 10001,
"team_id": 1001,
"player_name": "韦恩-艾灵顿",
"height": 1.93
}
]
}
使用xml
流程(使用xml):
- 添加yaml配置
- 先编写数据库表的类
- 编写表操作的接口(使用@Mapper不需要写实现类了,使用@Repository注册到IOC)
- 编写表操作的xml文件
- 编写服务接口
- 编写服务接口实现类(使用@Service注册注册到IOC,因为这里需要调用Mapper接口实现类实例,使用@Autowired获取实例)
- 接口去调用服务接口实现类获取数据(这里也使用@Autowired获取服务接口实现类的实例)
步骤一:application.yml 添加如下内容:
mybatis:
type-aliases-package: com.example.springboot01.dto
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
mapper-locations:
- classpath:mapper/*.xml
logging:
level:
com.example.springboot01.mapper: DEBUG
步骤二已经有了还是用Player类
步骤三:修改PlayerMapper.java 添加一个新的查询:
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface PlayerMapper {
@Select("SELECT * FROM player WHERE player_id = #{id}")
List<Player> selectPlayer(int id);
List<Player> selectPlayerList(@Param("ids") int[] ids);
}
步骤四:添加表操作的xml: 在 resources 目录下新建 mapper 目录,然后新建 PlayerMapper.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.example.springboot01.mapper.PlayerMapper">
<select id = "selectPlayerList" resultType = "com.example.springboot01.dto.Player">
SELECT * FROM player
WHERE player_id IN
<foreach item="item" index="index" collection="ids"
open="(" separator="," close=")">
#{item}
</foreach>
</select>
</mapper>
步骤五和六:修改服务接口和实现类 PlayerService.java:
package com.example.springboot01.service;
import com.example.springboot01.dto.Player;
import java.util.List;
public interface PlayerService {
List<Player> selectPlayer(int id);
List<Player> selectPlayerList(int[] ids);
}
PlayerServiceImpl.java:
package com.example.springboot01.service;
import com.example.springboot01.dto.Player;
import com.example.springboot01.mapper.PlayerMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class PlayerServiceImpl implements PlayerService{
@Autowired
PlayerMapper playerMapper;
@Override
public List<Player> selectPlayer(int id) {
return playerMapper.selectPlayer(id);
}
@Override
public List<Player> selectPlayerList(int[] ids) {
return playerMapper.selectPlayerList(ids);
}
}
步骤七:修改请求,GetPlayController.java:
package com.example.springboot01.controller;
import com.example.springboot01.dto.Player;
import com.example.springboot01.ret.RetResponse;
import com.example.springboot01.ret.RetResult;
import com.example.springboot01.service.PlayerServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/play")
public class GetPlayController {
@GetMapping("/")
public String getPlays(){
return "这是get请求";
}
@GetMapping("/{id}")
public String getPlay(@PathVariable("id") int id){
return "id: "+id;
}
@GetMapping("")
public String getPlay2(@RequestParam("id") int id){
return "id2: "+id;
}
@GetMapping("/user")
public String getPlayUser(@RequestParam Map<String, Object> params){
return "name: "+params.get("name")+" id: "+params.get("id");
}
@GetMapping("/users")
public String getPlayUser2(@RequestParam int[] ids){
String str = "";
for(int id: ids){
System.out.println(id);
str = str + "id"+id+": "+id+" ";
}
return str;
}
@Autowired
PlayerServiceImpl playerServiceImpl;
@GetMapping("/player")
public RetResult<Object> getPlayers(@RequestParam int id){
List<Player> players= playerServiceImpl.selectPlayer(id);
return RetResponse.success(players);
}
@GetMapping("/playlist")
public RetResult<Object> getPlayerList(@RequestParam int[] ids){
List<Player> players= playerServiceImpl.selectPlayerList(ids);
return RetResponse.success(players);
}
}
URL是 http://127.0.0.1:8080/play/playlist?ids=10001&ids=10002
结果:
{
"code": 200,
"msg": "success",
"data": [
{
"player_id": 10001,
"team_id": 1001,
"player_name": "韦恩-艾灵顿",
"height": 1.93
},
{
"player_id": 10002,
"team_id": 1001,
"player_name": "雷吉-杰克逊",
"height": 1.91
}
]
}
开启事务
在服务接口中需要事务的方法上添加 @Transactional
写一个新增的例子: 流程:
- 因为post请求验证,先给表类的字段加上验证
- mapper接口增加表操作方法
- xml添加表操作sql
- 服务接口添加方法,给方法添加 @Transactional,开启事务
- 服务实现类方法重写
- post请求修改
第一步:给表的字段添加验证: Player.java:
package com.example.springboot01.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.*;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Player {
private int player_id;
@NotNull(message = "球队ID不能为空")
private int team_id;
@Length(max = 3, message = "队员名字长度不能超过3")
@NotBlank(message = "队员名字不能为空")
private String player_name;
@Min(value = 1, message = "身高不能小于1")
@Max(value = 3, message = "身高不能超过3")
@NotNull(message = "身高不能为空")
private float height;
}
第二步:mapper编写: PlayerMapper.java:
package com.example.springboot01.mapper;
import com.example.springboot01.dto.Player;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface PlayerMapper {
@Select("SELECT * FROM player WHERE player_id = #{id}")
List<Player> selectPlayer(int id);
List<Player> selectPlayerList(@Param("ids") int[] ids);
int addPlayers(Player player);
}
第三步:添加xml的sql: PlayerMapper.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.example.springboot01.mapper.PlayerMapper">
<select id = "selectPlayerList" resultType = "com.example.springboot01.dto.Player">
SELECT * FROM player
WHERE player_id IN
<foreach item="item" index="index" collection="ids"
open="(" separator="," close=")">
#{item}
</foreach>
</select>
<insert id="addPlayers" useGeneratedKeys="true" keyProperty="player_id" parameterType="com.example.springboot01.dto.Player">
INSERT INTO player VALUES(null,#{team_id},#{player_name},#{height})
</insert>
</mapper>
第四步:编写服务接口,并在需要开启事务的方法上使用@Transactional开启事务: PlayerService.java:
package com.example.springboot01.service;
import com.example.springboot01.dto.Player;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
public interface PlayerService {
List<Player> selectPlayer(int id);
List<Player> selectPlayerList(int[] ids);
@Transactional
int addPlayers(Player player);
}
第五步:服务接口实现类编写: PlayerServiceImpl.java:
package com.example.springboot01.service;
import com.example.springboot01.dto.Player;
import com.example.springboot01.mapper.PlayerMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class PlayerServiceImpl implements PlayerService{
@Autowired
PlayerMapper playerMapper;
@Override
public List<Player> selectPlayer(int id) {
return playerMapper.selectPlayer(id);
}
@Override
public List<Player> selectPlayerList(int[] ids) {
return playerMapper.selectPlayerList(ids);
}
@Override
public int addPlayers(Player player) {
return playerMapper.addPlayers(player);
}
}
第六步:post请求: PostPlayController.java:
package com.example.springboot01.controller;
import com.example.springboot01.dto.Player;
import com.example.springboot01.service.PlayerServiceImpl;
import com.example.springboot01.validation.PlayUserValidation;
import com.example.springboot01.ret.RetResponse;
import com.example.springboot01.ret.RetResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
@RestController
@RequestMapping("/postplay")
public class PostPlayController {
@PostMapping("")
public String postPlay(@RequestParam Map<String, Object> params){
return "id: "+params.get("id")+" name: "+params.get("name");
}
@PostMapping("/")
public String postPlay1(@RequestBody Map<String, Object> params){
return "id: "+params.get("id")+" name: "+params.get("name");
}
@PostMapping("/user")
public RetResult<Object> postPlayUser(@RequestBody @Validated PlayUserValidation user){
return RetResponse.success(user);
}
@Autowired
PlayerServiceImpl playerServiceImpl;
@PostMapping("/addplayer")
public RetResult<Object> addPlayer(@RequestBody @Validated Player player){
int playNum = playerServiceImpl.addPlayers(player);
if(playNum>0){
return RetResponse.success("添加成功");
}else{
return RetResponse.error("添加失败");
}
}
}
URL是 http://127.0.0.1:8080/postplay/addplayer 参数是:
{
"team_id":"1001",
"player_name":"SSS",
"height":1.98
}
|