Brief introduction:
JPA is the Java Persistence API (Java Persistence Layer API)5.0Annotations or XML describe the object-relational table mapping and persist run-time entity objects to the database.Copy the code
Step 1: Import the POM files we need
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> <version>1.51..RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.018.</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.21..RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.22..RELEASE</version>
</dependency>
</dependencies>
Copy the code
Step 2: Configure the application.yml file
server:
port: 8080
spring:
jpa:
database-platform: org.hibernate.dialect.MySQL5Dialect
show-sql: true
datasource:
url: jdbc:mysql://localhost:3306/test? useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
driver-class-name: com.mysql.jdbc.Driver
username: root
password: root
Copy the code
Step 3: Create a simple utility class called ResponseResult
package com.feicheng.common;
/** * Result returns set *@author Lenovo
*/
public class ResponseResult {
private Integer code;
private String msg;
public void setCode(Integer code) {
this.code = code;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Integer getCode(a) {
return code;
}
public String getMsg(a) {
return msg;
}
public ResponseResult(Integer code, String msg) {
this.code = code;
this.msg = msg; }}Copy the code
Create a test database and create a user table (id, username).
CREATE DATABASE / *! 32312 IF NOT EXISTS*/`test` / *! 40100 DEFAULT CHARACTER SET latin1 */;
USE `test`;
/*Table structure for table `user` */
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL.`password` varchar(64) DEFAULT NULL,
PRIMARY KEY (`id`))ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8;
Copy the code
Step 5: Create the entity class User
package com.feicheng.entity;
import javax.persistence.*;
/ * * *@author Lenovo
*/
@Table(name = "user")
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String name;
private String password;
public Integer getId(a) {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName(a) {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword(a) {
return password;
}
public void setPassword(String password) {
this.password = password; }}Copy the code
Step 6: Create the UserController
package com.feicheng.controller;
import com.feicheng.common.ResponseResult;
import com.feicheng.entity.User;
import com.feicheng.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Collections;
import java.util.List;
/ * * *@author Lenovo
*/
@Controller
@RequestMapping("user")
public class UserController {
@Autowired
private UserService userService;
/** * Query all users **@return* /
@GetMapping("list")
public ResponseEntity<List<User>> list() {
List<User> users = this.userService.select();
if (CollectionUtils.isEmpty(users)) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(users);
}
/** * Query user ** based on user name@param userName
* @return* /
@GetMapping("select/{userName}")
public ResponseEntity<User> selectUserByName(@PathVariable("userName") String userName) {
User user = this.userService.selectUserByName(userName);
if (user == null) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
}
return ResponseEntity.ok(user);
}
/** * Modify user ** according to id@param user
* @return* /
@PostMapping("edit")
public ResponseEntity<ResponseResult> edit(User user) {
ResponseResult responseResult = this.userService.edit(user);
return ResponseEntity.ok(responseResult);
}
/** * Delete user ** based on id@param id
* @return* /
@PostMapping("delete/{id}")
public ResponseEntity<ResponseResult> delete(@PathVariable("id") Integer id) {
ResponseResult responseResult = this.userService.delete(id);
returnResponseEntity.ok(responseResult); }}Copy the code
Step 7: Create UserService
package com.feicheng.service;
import com.feicheng.common.ResponseResult;
import com.feicheng.entity.User;
import java.util.List;
/ * * *@author Lenovo
*/
public interface UserService {
// Query all users
List<User> select(a);
// Query user information based on the user name
User selectUserByName(String userName);
// Modify the user based on the user ID
ResponseResult edit(User user);
// Delete the user based on the ID
ResponseResult delete(Integer id);
}
Copy the code
Step 8: Create UserServiceImpl
package com.feicheng.service.impl;
import com.feicheng.common.ResponseResult;
import com.feicheng.entity.User;
import com.feicheng.repository.UserRepository;
import com.feicheng.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import java.util.List;
import java.util.Optional;
/ * * *@author Lenovo
*/
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
/** * Query all users **@return* /
@Override
public List<User> select(a) {
List<User> users = this.userRepository.findAll();
if (CollectionUtils.isEmpty(users)) {
return null;
}
return users;
}
/** * Query user information by user name **@param userName
* @return* /
@Override
public User selectUserByName(String userName) {
User user = new User();
user.setName(userName);
Example<User> example = Example.of(user);
Optional<User> one = this.userRepository.findOne(example);
user = one.get();
return user;
}
/** * Modify user information based on the user ID **@param user
* @return* /
@Override
public ResponseResult edit(User user) {
Integer count = this.userRepository.edit(user.getName(), user.getPassword(), user.getId());
if (count > 0) {
return new ResponseResult(200."Modified successfully");
}
return new ResponseResult(500."Modification failed");
}
/** * Delete user ** based on id@param id
* @return* /
@Override
@Transactional
public ResponseResult delete(Integer id) {
try {
this.userRepository.deleteById(id);
return new ResponseResult(200."Deleted successfully");
} catch (Exception e) {
e.printStackTrace();
return new ResponseResult(500."Delete failed"); }}}Copy the code
Step 9: Create UserRepository
package com.feicheng.repository;
import com.feicheng.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
/ * * *@author Lenovo
*/
@Repository
public interface UserRepository extends JpaRepository<User.Integer> {
@Modifying
@Transactional
@Query("update User u set u.name = :name, u.password = :password where u.id = :id")
Integer edit(@Param("name") String name, @Param("password") String password, @Param("id") Integer id);
}
Copy the code
Conclusion:
Using JPA to operate the database is more convenient, we want to encapsulate the code is relatively simple, quick, easy to useCopy the code