一、SpringBootData JPA介绍
SpringData:是Spring提供了一个操作数据的框架。
SpringData JPA:是SpringData框架下的一个基于JPA标准操作数据的模块,简化操作持久层的代码,只需要编写接口就可以。
二、SpringBoot整合SpringData JPA
1、新建项目
2 、maven依赖配置(pom.xml)
(1)、postgresql 集成 配置
org.postgresql postgresql runtime
(2)、jpa 集成配置
org.springframework.boot spring-boot-starter-data-jpa
3、数据源配置(application.properties)
spring.datasource.driver-class-name=org.postgresql.Driver spring.datasource.url=jdbc:postgresql://127.0.0.1:5432/test spring.datasource.username=postgres spring.datasource.password=123456 spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true
注意:
url, username,password 等信息是否配置正确。
spring.jpa.hibernate.ddl-auto 指定为 update,这样框架会自动帮我们创建或更新表结构
写入完成后,org.postgresql.Driver会报错(可以不管)。原因是postgresql这个jar包依赖类型默认是runtime(运行时生效),所以并不影响代码的运行。
修改方法:
右键点击项目—>选择“open module settings”—>点击“Dependencies”,找到Maven:org.postgresql:postgresql:42.2.18 将runtime修改为Compile。
修改后效果:
4、编写实体类
这里,我们用了一系列的注解。
例如:@Table、@Column分别对应了数据库的表、列,@GeneratedValue 用于指定ID主键的生成方式。
package com.example.demo; import javax.persistence.*; import java.io.Serializable; /** * @DESC users表的实体类 * @author guchuang */ @Entity @Table(name="users") public class User implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "menuSeq") @SequenceGenerator(name = "menuSeq", initialValue = 100000, allocationSize = 1, sequenceName = "MENU_SEQUENCE") @Column(name="id")//数据库字段名 private int id; private int age; private String name; public User() { } public User(int id, int age, String name) { this.id = id; this.age = age; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "User [id=" + id + ", age=" + age + ", name=" + name + "]"; } }
5、编写Dao接口
/** * @DESC 实现jpa接口,拥有jpa提供的默认crud操作,无需自己写实现代码(除非要扩展功能) * @author guchuang * */ public interface UserRepository extends JpaRepository{ }
6、编写Service 接口
package com.example.demo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.bind.annotation.*; import java.sql.SQLException; import java.util.List; import java.util.Optional; @Service public class UserService { @Autowired private UserRepository userRepository; public ListgetUser() throws SQLException { System.out.println("userRepository: " + userRepository); List users = userRepository.findAll(); return users; } public User getUser(@PathVariable(value="id") int id) throws SQLException { Optional user = userRepository.findById(id); return user.get(); } public String saveUser(@RequestBody User user){ userRepository.save(user); return "success to add user"; } public String updateUser(@RequestBody User user){ userRepository.deleteById(user.getId()); userRepository.save(user); return "success to update user"; } public String deleteUser(@PathVariable(value="id") int id){ userRepository.deleteById(id); return "success to delete user"; } }
7、jpa实现数据库读写
package com.example.demo; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.sql.SQLException; import java.util.List; import java.util.Optional; @Api(value = "JPA 用户操作") @RestController @RequestMapping("/jpa") public class JpaUserController { @Autowired private UserService userService; @ApiOperation(value = "初始化", notes = "/init") @GetMapping("/init") public void init() { for (int id =1000;id<1010;id++) { User u = new User(); u.setName("name"+id); u.setAge(id % 10); saveUser(u); } } @ApiOperation(value = "获取用户列表", notes = "/list") @GetMapping("/list") public ListgetUser() throws SQLException { return userService.getUser(); } @ApiOperation(value = "获取用户", notes = "/user") @GetMapping("/user") public User getUser(@ApiParam(value = "获取单个用户", required = true) @RequestParam int id) throws SQLException { return userService.getUser(id); } @ApiOperation(value = "保存用户", notes = "/user") @PostMapping(value = "/user") public String saveUser(@RequestBody User user){ return userService.saveUser(user); } @PutMapping(value = "/user") public String updateUser(@RequestBody User user){ return userService.updateUser(user); } @DeleteMapping(value = "/user/{id}") public String deleteUser(@PathVariable(value="id") int id){ return userService.deleteUser(id); } }
创建好后,项目结构如下:
8、测试结果
在浏览器中运行
http://localhost:8080/jpa/init
数据库结果: