Spring Boot深入学习数据访问之Spring Data JPA与Hibernate的应用
什么是Spring Data JPA?
Spring Data JPA 是 Spring Data 一个子数据访问项目,该项目基于Spring框架为开发人员提供了一个基于JPA的工具包,方便开发人员使用JPA来访问数据库。
Spring Boot 中使用Spring Data JPA
在Spring Boot中使用Spring Data JPA非常简单,只需要通过添加Maven依赖或Gradle依赖来实现。在spring-boot-starter-data-jpa
模块中已经集成了Spring Data JPA,不需要额外的配置,只需要在应用程序的配置文件中配置数据源即可。
Hibernate 的使用
Hibernate是一种ORM框架,它允许开发人员在使用Java对象时,直接映射到数据库表中。Hibernate通过对象关系映射(ORM)方式,将Java对象自动映射到数据库表上,提供了完整的CRUD操作,极大的提高了开发效率。
Spring Data JPA和Hibernate的结合使用
Spring Data JPA基于Hibernate来操作ORM,可以通过配置Spring Data JPA和Hibernate的配置来控制Hibernate的特性,实现对数据库的操作。
添加Maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
配置数据源
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&useSSL=false
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
创建实体类
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
// getters and setters
}
创建Repository接口
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
在Controller中使用Repository
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping("/{id}")
public User getUserById(@PathVariable Long id) {
Optional<User> user = userRepository.findById(id);
return user.orElse(null);
}
}
示例一:使用Spring Data JPA和Hibernate进行增删改查操作
添加依赖
<!-- mysql JDBC driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- Spring Boot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- Spring Data JPA -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
编写配置文件
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&useSSL=false
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
hibernate:
ddl-auto: update
show-sql: true
编写实体类
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true, length = 15)
private String username;
@Column(nullable = false, length = 64)
private String password;
@Column(nullable = false, unique = true, length = 32)
private String email;
@Column(nullable = false)
private Integer activateCode;
// getters and setters
}
编写Repository接口
public interface UserRepository extends JpaRepository<User, Long> {
User findByUsernameAndPassword(String username, String password);
User findByActivateCode(Integer activateCode);
}
编写Controller
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping("/all")
public List<User> getAll() {
return userRepository.findAll();
}
@GetMapping("/{id}")
public User getById(@PathVariable Long id) {
return userRepository.findById(id).orElse(null);
}
@PostMapping("/add")
public User add(@RequestBody User user) {
return userRepository.save(user);
}
@PostMapping("/update")
public User update(@RequestBody User user) {
User oldUser = userRepository.findById(user.getId()).orElse(null);
if (oldUser != null) {
oldUser.setUsername(user.getUsername());
oldUser.setPassword(user.getPassword());
oldUser.setEmail(user.getEmail());
oldUser.setActivateCode(user.getActivateCode());
return userRepository.save(oldUser);
}
return null;
}
@DeleteMapping("/{id}")
public void delete(@PathVariable Long id) {
userRepository.deleteById(id);
}
}
示例二:使用Spring Boot和Hibernate搭建RESTful API服务
添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
添加配置文件
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&useSSL=false
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
server:
port: 8080
jpa:
database: MYSQL
show-sql: true
hibernate:
ddl-auto: update
创建实体类
@Entity
@Table(name = "Book")
public class Book {
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String bookName;
private String authorName;
public Book() {}
public Book(String bookName, String authorName) {
this.bookName = bookName;
this.authorName = authorName;
}
// getters and setters
}
创建Repository接口
public interface BookRepository extends JpaRepository<Book, Long> {}
创建Controller
@RestController
@RequestMapping("/books")
public class BookController {
@Autowired
private BookRepository bookRepository;
@GetMapping("")
public ResponseEntity<List<Book>> getAllBooks() {
List<Book> books = bookRepository.findAll();
return new ResponseEntity<List<Book>>(books, HttpStatus.OK);
}
@GetMapping("/{id}")
public ResponseEntity<Book> getBookById(@PathVariable("id") Long id) {
Optional<Book> book = bookRepository.findById(id);
if (!book.isPresent()) {
return new ResponseEntity<Book>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<Book>(book.get(), HttpStatus.OK);
}
@PostMapping("")
public ResponseEntity<Book> addBook(@Validated @RequestBody Book book) {
Book newBook = bookRepository.save(book);
return new ResponseEntity<Book>(newBook, HttpStatus.CREATED);
}
@PutMapping("/{id}")
public ResponseEntity<Book> updateBook(
@PathVariable("id") Long id, @Validated @RequestBody Book book) {
Optional<Book> optionalBook = bookRepository.findById(id);
if (!optionalBook.isPresent()) {
return new ResponseEntity<Book>(HttpStatus.NOT_FOUND);
}
Book existingBook = optionalBook.get();
existingBook.setBookName(book.getBookName());
existingBook.setAuthorName(book.getAuthorName());
bookRepository.save(existingBook);
return new ResponseEntity<Book>(existingBook, HttpStatus.OK);
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteBook(@PathVariable("id") Long id) {
Optional<Book> book = bookRepository.findById(id);
if (!book.isPresent()) {
return new ResponseEntity<Void>(HttpStatus.NOT_FOUND);
}
bookRepository.deleteById(id);
return new ResponseEntity<Void>(HttpStatus.OK);
}
}
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Spring Boot深入学习数据访问之Spring Data JPA与Hibernate的应用 - Python技术站