整合SpringData JPA
一、SpringData简介
SpringData实际是对Hibernate进行再封装。
二、整合SpringData JPA
JPA:ORM(Object Relational Mapping)
依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>
spring-boot-starter-data-jpa</artifactId> </dependency>
或者:
1)、编写一个实体类(bean)和数据表进行映射,并且配置好映射关系;
//使用JPA注解配置映射关系 @Entity @Table(name = "tbl_user")
//@Table来指定和哪个数据表对应;如果省略默认表名就是user; public class User { @Id @GeneratedValue
(strategy = GenerationType.IDENTITY)//自增主键 private Integer id; @Column(name =
"last_name",length = 50) //这是和数据表对应的一个列 private String lastName; @Column
//省略默认列名就是属性名 private String email;
2)、编写一个Dao接口来操作实体类对应的数据表(Repository)
//继承JpaRepository来完成对数据库的操作 public interface UserRepository extends
JpaRepository<User,Integer> { }
3)、基本的配置JpaProperties
spring: jpa: hibernate: # 更新或者创建数据表结构 ddl-auto: update # 控制台显示SQL show-sql:
true
4)、Controller
@RestController public class UserController { @Autowired UserRepository
userRepository;@GetMapping("/user/{id}") public User getUser(@PathVariable
("id") Integer id){ User user = userRepository.findOne(id);return user; }
@GetMapping("/user") public User insertUser(User user){ User save =
userRepository.save(user);return save; }
完成!
更多SpringBoot整合示例
https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples
<https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples>
热门工具 换一换