Springboot中实现Hibernate的代码实例
时间: 2023-05-28 15:05:25 浏览: 92
Hibernate实例代码
4星 · 用户满意度95%
1. 添加Hibernate的依赖
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
```
2. 配置数据源和Hibernate
```properties
# 数据源配置
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# Hibernate配置
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
```
3. 定义实体类
```java
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private Integer age;
// getter and setter
}
```
4. 定义Repository
```java
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
```
5. 编写业务逻辑
```java
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public User save(User user) {
return userRepository.save(user);
}
public List<User> findAll() {
return userRepository.findAll();
}
}
```
6. 编写测试类
```java
@SpringBootTest
class UserServiceTest {
@Autowired
private UserService userService;
@Test
void testSave() {
User user = new User();
user.setName("张三");
user.setAge(20);
userService.save(user);
List<User> users = userService.findAll();
Assert.assertEquals(users.size(), 1);
Assert.assertEquals(users.get(0).getName(), "张三");
Assert.assertEquals(users.get(0).getAge(), Integer.valueOf(20));
}
}
```
阅读全文