springboot jpa hibernate 配置实例
时间: 2023-10-20 12:08:35 浏览: 130
SpringBoot整合JPA的实例代码
这里提供一个简单的 Spring Boot + JPA + Hibernate 配置实例,步骤如下:
1. 在 `pom.xml` 中添加以下依赖:
```xml
<!-- Spring Boot Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- Spring Boot Starter Data JPA -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- Hibernate Entity Manager -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.4.32.Final</version>
</dependency>
<!-- MySQL Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
```
2. 在 `application.properties` 中配置数据源和 JPA 相关属性:
```properties
# 数据源配置
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
# JPA 配置
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
```
3. 创建实体类,例如:
```java
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "age")
private Integer age;
// 省略 getter 和 setter
}
```
4. 创建 Repository 接口,例如:
```java
public interface UserRepository extends JpaRepository<User, Long> {
List<User> findByName(String name);
}
```
5. 创建 Service 类,例如:
```java
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public List<User> findByName(String name) {
return userRepository.findByName(name);
}
public User save(User user) {
return userRepository.save(user);
}
public void deleteById(Long id) {
userRepository.deleteById(id);
}
}
```
6. 创建 Controller 类,例如:
```java
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/{name}")
public List<User> findByName(@PathVariable("name") String name) {
return userService.findByName(name);
}
@PostMapping
public User save(@RequestBody User user) {
return userService.save(user);
}
@DeleteMapping("/{id}")
public void deleteById(@PathVariable("id") Long id) {
userService.deleteById(id);
}
}
```
这样就完成了 Spring Boot + JPA + Hibernate 的配置和使用。
阅读全文