SpringDataJPA整合postgreSQL实现简单的crud

  • Post author:
  • Post category:其他




创建项目



我们使用springboot来快速创建项目

在这里插入图片描述

我们选择lombok、springweb、spingdatajpa、postgresql驱动等模块来快速创建项目

我们配置一下yml文件,设置postgre的数据库地址、用户名、密码等。

spring:
  datasource:
    driver-class-name: org.postgresql.Driver
    url: jdbc:postgresql://127.0.0.1:5432/billetsdoux
    username: postgres
    password: 930726
  jpa:
    properties:
      hibernate:
        temp.use_jdbc_metadata_defaults: false

    hibernate:
      ddl-auto: update

我们来创建一个用户类

@Data
@Entity
@Table(name = "t_user")
public class User implements Serializable {
    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private Integer id;
    @Column(name = "username")
    private String userName;

    @Column(name = "sex")
    private String sex;

    @Column(name = "age")
    private Integer age;
}

dao层

public interface UserDao extends JpaRepository<User,Integer> {
    
    
}

service层接口

public interface UserService {
    User addUser(User user);

    User getUser(Integer id);

    void deleteUser(Integer id);


    User updateUser(User user);


}

service实现类

@Transactional
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Override
    public User addUser(User user) {
         user = userDao.save(user);
        return user;
    }

    @Override
    public User getUser(Integer id) {
        return userDao.getOne(id);
    }

    @Override
    public void deleteUser(Integer id) {
        userDao.deleteById(id);
    }


    @Override
    public User updateUser(User user) {
        return userDao.save(user);
    }


}

controller层


@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/add")
    public User add(@RequestBody User user){
        userService.addUser(user);
        return user;
    }

    @GetMapping("/get/{id}}")
    public User get(@PathVariable Integer id){
        return userService.getUser(id);
    }


    @PutMapping("/update")
    public User updateUser(@RequestBody User user){
        
        return userService.updateUser(user);
    }
    
    @DeleteMapping("/del/{id}")
    public String delUser(@PathVariable Integer id){
        userService.deleteUser(id);
        return "ok";
    }

}



版权声明:本文为weixin_43818603原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。