在了解了Hibernate后,进一步将Hibernate和Springboot整合。
目录
- 引入依赖
- 配置文件
- 代码
- Bean
- Dao层
- Service层
- Controller层
- 测试
- JpaRepository接口
引入依赖
<!--引入hibernate-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.12</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
配置文件
server:
port: 8080
spring:
application:
name: springboot-hibernate
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
url : jdbc:mysql://local:3306/test?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=UTF-8&useSSL=false
jpa:
database: mysql
show-sql: true # 是否打印 sql 语句
hibernate:
ddl-auto: update
properties:
hibernate:
dialect: org.hibernate.dialect.MySQL5Dialect
代码
Bean
@Entity
@Data
@Builder
@Table(name = "t_user")
public class UserBean {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private String id;
@Column
private String username;
@Column
private String password;
}
Dao层
@Repository
public interface UserRepository extends JpaRepository<UserBean,String> {
}
Service层
public interface UserService {
UserBean add(UserBean userBean);
List<UserBean> queryAll();
}
实现类
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Override
public UserBean add(UserBean userBean) {
UserBean user = userRepository.save(userBean);
return user;
}
@Override
public List<UserBean> queryAll() {
List<UserBean> userBeans = userRepository.findAll();
return userBeans;
}
}
Controller层
@RestController
@RequestMapping("user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("findAll")
public List<UserBean> findAll(){
return userService.queryAll();
}
}
测试
访问/user/findAll,当前数据库没有对应的表,返回为空
、
查看数据库已经创建对应的表
JpaRepository接口
通过JpaRepository泛型类,里面已经封装了集成的数据库操作方法