1、项目目录
2、全部代码
2.1 pom.xml
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.6</version>
<relativePath/>
</parent>
<groupId>com.example</groupId>
<artifactId>jpademo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>jpademo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2.2 application.properties
server.port=8080
server.servlet.context-path=/demo
#com.mysql.jdbc.Driver过时
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://192.168.203.101:3306/test
spring.datasource.username=test_admin
spring.datasource.password=123
2.3 生成的Application代码
package com.example.jpademo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class JpademoApplication {
public static void main(String[] args) {
SpringApplication.run(JpademoApplication.class, args);
}
}
2.4 beans
package com.example.jpademo.beans;
import lombok.*;
import lombok.experimental.Accessors;
import org.springframework.format.annotation.DateTimeFormat;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
@Data
@NoArgsConstructor
@Accessors(chain = true)
@Entity
@Table(name = "users")
public class User implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date dt=new Date();
}
对应的数据库操作
mysql> create database test;
Query OK, 1 row affected (0.01 sec)
mysql> use test;
Database changed
mysql> create table users(
-> id int auto_increment primary key,
-> name varchar(45) ,
-> dt datetime default CURRENT_TIMESTAMP
-> );
Query OK, 0 rows affected (0.02 sec)
mysql> insert into users(name) values('test'),('abc'),('Hadron');
Query OK, 3 rows affected (0.01 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> commit;
Query OK, 0 rows affected (0.00 sec)
mysql>
2.5 Repository
package com.example.jpademo.dao;
import com.example.jpademo.beans.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import javax.transaction.Transactional;
@Repository
public interface UserRepository extends JpaRepository<User, Long>{
//默认提供了Optional<User> findById(Long id);
User findByName(String name);
@Query("select u from User u where u.id <= ?1")
Page<User> findMore(Long maxId, Pageable pageable);
@Modifying
@Transactional
@Query("update User u set u.name = ?1 where u.id = ?2")
int updateById(String name, Long id);
}
2.6 Service
package com.example.jpademo.service;
import com.example.jpademo.beans.User;
import com.example.jpademo.dao.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
@Service("userService")
public class UserService {
@Autowired
private UserRepository userRepository;
public User getUserByID(Long id){
return userRepository.findById(id).get();
}
public User getByName(String name){
return userRepository.findByName(name);
}
public Page<User> findPage(){
Pageable pageable = PageRequest.of(0, 10);
return userRepository.findAll(pageable);
}
public Page<User> find(Long maxId){
Pageable pageable = PageRequest.of(0, 10);
return userRepository.findMore(maxId,pageable);
}
public User save(User u){
return userRepository.save(u);
}
public User update(Long id,String name){
User user = userRepository.findById(id).get();
user.setName(name+"_update");
return userRepository.save(user);
}
public Boolean updateById(String name, Long id){
return userRepository.updateById(name,id)==1;
}
}
2.7 Controller
package com.example.jpademo.web;
import com.example.jpademo.beans.User;
import com.example.jpademo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Optional;
@RestController
@RequestMapping("/")
public class ApiController {
@Autowired
private UserService userService;
@GetMapping("/init")
public String init(){
User user = null;
for(int i=0;i<10;i++){
user = new User();
user.setName("test"+i);
userService.save(user);
}
return "初始化完成。";
}
@GetMapping("/userByName/{username}")
public User getUserByName(@PathVariable("username") String username){
return userService.getByName(username);
}
@GetMapping("/userById/{userid}")
public User getUserById(@PathVariable("userid") Long userid){
return userService.getUserByID(userid);
}
@GetMapping("/page")
public Page<User> getPage(){
return userService.findPage();
}
@GetMapping("/page/{maxID}")
public Page<User> getPageByMaxID(@PathVariable("maxID") Long maxID){
return userService.find(maxID);
}
@RequestMapping("/update/{id}/{name}")
public User update(@PathVariable Long id, @PathVariable String name){
return userService.update(id,name);
}
@RequestMapping("/update/{id}")
public Boolean updateById(@PathVariable Long id){
return userService.updateById("newName",id);
}
}
3、测试
3.1 测试初始化接口
http://localhost:8080/demo/init
mysql> select * from users;
+----+--------+---------------------+
| id | name | dt |
+----+--------+---------------------+
| 1 | test | 2021-11-15 23:45:05 |
| 2 | abc | 2021-11-15 23:45:05 |
| 3 | Hadron | 2021-11-15 23:45:05 |
| 4 | test0 | NULL |
| 5 | test1 | NULL |
| 6 | test2 | NULL |
| 7 | test3 | NULL |
| 8 | test4 | NULL |
| 9 | test5 | NULL |
| 10 | test6 | NULL |
| 11 | test7 | NULL |
| 12 | test8 | NULL |
| 13 | test9 | NULL |
+----+--------+---------------------+
13 rows in set (0.00 sec)
mysql>
发现dt字段没有值。 解决办法:修改User类
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date dt=new Date();
然后重启程序,再次调用初始化接口http://localhost:8080/demo/init,查询数据库,问题解决。
mysql> select * from users;
+----+--------+---------------------+
| id | name | dt |
+----+--------+---------------------+
| 1 | test | 2021-11-15 23:45:05 |
| 2 | abc | 2021-11-15 23:45:05 |
| 3 | Hadron | 2021-11-15 23:45:05 |
| 4 | test0 | NULL |
| 5 | test1 | NULL |
| 6 | test2 | NULL |
| 7 | test3 | NULL |
| 8 | test4 | NULL |
| 9 | test5 | NULL |
| 10 | test6 | NULL |
| 11 | test7 | NULL |
| 12 | test8 | NULL |
| 13 | test9 | NULL |
| 14 | test0 | 2021-11-16 19:07:56 |
| 15 | test1 | 2021-11-16 19:07:56 |
| 16 | test2 | 2021-11-16 19:07:56 |
| 17 | test3 | 2021-11-16 19:07:56 |
| 18 | test4 | 2021-11-16 19:07:56 |
| 19 | test5 | 2021-11-16 19:07:56 |
| 20 | test6 | 2021-11-16 19:07:56 |
| 21 | test7 | 2021-11-16 19:07:56 |
| 22 | test8 | 2021-11-16 19:07:56 |
| 23 | test9 | 2021-11-16 19:07:56 |
+----+--------+---------------------+
23 rows in set (0.00 sec)
mysql>
3.2 测试查询接口
http://localhost:8080/demo/userById/1
http://localhost:8080/demo/userByName/abc
3.3 测试分页查询接口
http://localhost:8080/demo/page http://localhost:8080/demo/page/5
3.4 测试更新接口
mysql> select * from users where id=1;
+----+---------+---------------------+
| id | name | dt |
+----+---------+---------------------+
| 1 | newName | 2021-11-15 23:45:05 |
+----+---------+---------------------+
1 row in set (0.00 sec)
mysql>
mysql> select * from users where id=1;
+----+----------------+---------------------+
| id | name | dt |
+----+----------------+---------------------+
| 1 | newName_update | 2021-11-15 23:45:05 |
+----+----------------+---------------------+
1 row in set (0.00 sec)
mysql>
|