第一步,引入pom
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<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>
<!-- springBoot JPA的起步依赖 -->
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- MySQL连接驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.35</version>
</dependency>
</dependencies>
第二步,创建User的pojo
数据库
package com.hikktn.entity;
import javax.persistence.*;
import java.io.Serializable;
/**
* @ClassName UserEntity
* @Description TODO
* @Author lisonglin
* @Date 2021/4/2 15:41
* @Version 1.0
*/
@Entity
@Table(name = "user", schema = "test")
public class UserEntity implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String username;
private String password;
@Id
@Column(name = "id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Basic
@Column(name = "username")
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Basic
@Column(name = "password")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserEntity that = (UserEntity) o;
if (id != that.id) return false;
if (username != null ? !username.equals(that.username) : that.username != null) return false;
if (password != null ? !password.equals(that.password) : that.password != null) return false;
return true;
}
@Override
public int hashCode() {
int result = id;
result = 31 * result + (username != null ? username.hashCode() : 0);
result = 31 * result + (password != null ? password.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "UserEntity{" + "id=" + id + ", username='" + username + '\'' + ", password='" + password + '\'' + '}';
}
}
第三步,实现接口
package com.hikktn.repository;
import com.hikktn.entity.UserEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import java.util.List;
/**
* @ClassName UserRepository
* @Description TODO
* @Author lisonglin
* @Date 2021/4/2 16:00
* @Version 1.0
*/
public interface UserRepository extends JpaRepository<UserEntity, Integer>, JpaSpecificationExecutor<UserEntity> {
// 查询全部
List<UserEntity> findAll();
}
第四步,测试
package com.hikktn.test;
import com.hikktn.MySpringBootApplication;
import com.hikktn.entity.UserEntity;
import com.hikktn.repository.UserRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;
/**
* @ClassName JpaTest
* @Description TODO
* @Author lisonglin
* @Date 2021/4/2 16:02
* @Version 1.0
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes= MySpringBootApplication.class)
public class JpaTest {
@Autowired
private UserRepository userRepository;
@Test
public void testGetUserAll(){
List<UserEntity> users = userRepository.findAll();
System.out.println(users);
}
@Test
public void testAddUser(){
UserEntity userEntity =new UserEntity();
userEntity.setUsername("tom");
userEntity.setPassword("123");
userRepository.save(userEntity);
}
@Test
public void testFindOneUser(){
Optional<UserEntity> byId = userRepository.findById(1);
System.out.println(byId.get());
}
@Test
public void testDeleteUser() {
userRepository.deleteById(5);
}
@Test
@Transactional(rollbackFor = Exception.class)
// @Rollback(value = false)//发生异常不回滚
public void update(){
Optional<UserEntity> optional = userRepository.findById(1);
System.out.println(optional.orElseGet(UserEntity::new));
}
}
第五步,增删改查
package com.hikktn.controller;
import com.hikktn.entity.UserEntity;
import com.hikktn.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;
import java.util.Optional;
/**
* @ClassName UserController
* @Description TODO
* @Author lisonglin
* @Date 2021/4/2 22:01
* @Version 1.0
*/
@RestController
@RequestMapping(path = "/user")
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping(path = "/all")
@ResponseBody
public Iterable<UserEntity> getAllUsers(){
return userRepository.findAll();
}
/*
增加用户
*/
@PostMapping()
public UserEntity saveUser(@RequestBody UserEntity user) {
return userRepository.save(user);
}
/*
删除用户
*/
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable("id") int userId) {
userRepository.deleteById(userId);
}
/*
修改用户
*/
@PutMapping("/{id}")
public UserEntity updateUser(@PathVariable("id") int userId, @RequestBody UserEntity user) {
user.setId(userId);
return userRepository.saveAndFlush(user);
}
/*
查询用户
*/
@GetMapping("/{id}")
public UserEntity getUserInfo(@PathVariable("id") int userId) {
Optional<UserEntity> optional = userRepository.findById(userId);
return optional.orElseGet(UserEntity::new);
}
/*
分页查询多个用户
*/
@GetMapping("/list")
public Page<UserEntity> pageQuery(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
@RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
return userRepository.findAll(PageRequest.of(pageNum - 1, pageSize));
}
}