【SpringBoot整合JPA框架(hibernate实现)详解】(附详细代码)
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
// 定义一个用户实体类
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
// 省略其他字段、构造函数、getter和setter方法
}
// 定义一个UserRepository接口继承JpaRepository
public interface UserRepository extends JpaRepository<User, Long> {
// 这里可以定义一些自定义查询方法,Spring Data JPA会自动生成实现
}
// 定义一个服务类
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public List<User> findAllUsers() {
return userRepository.findAll();
}
// 省略其他业务方法
}
// 定义一个控制器类
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping
public ResponseEntity<List<User>> getAllUsers() {
List<User> users = userService.findAllUsers();
if (users.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<>(users, HttpStatus.OK);
}
// 省略其他控制器方法
}
// 配置类
@Configuration
public class DatabaseConfig {
@Bean
public EntityManagerFactory entityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan("com.example.demo.model");
factory.setDataSource(dataSource());
factory.afterPropertiesSet();
return factory.getObject();
}
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory factory) {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(factory);
return t
评论已关闭