
JPA全称为Java Persistence API(Java持久层API),它是Sun公司在JavaEE 5中提出的Java持久化规范。它为Java开发人员提供了一种对象/关联映射工具,来管理Java应用中的关系数据,JPA吸取了目前Java持久化技术的优点,旨在规范、简化Java对象的持久化工作。很多ORM框架都是实现了JPA的规范,如:Hibernate、EclipseLink。
Spring Data JPA旨在通过减少实际需要的工作量来显著改善数据访问层的实现。它在JPA的基础上做了一些封装,可以轻松实现基于JPA的存储库。 此模块处理对基于JPA的数据访问层的增强支持。 它使构建使用数据访问技术的Spring驱动应用程序变得更加容易。
需要注意的是JPA统一了Java应用程序访问ORM框架的规范
JPA为我们提供了以下规范:
以上的定义引用自网络技术文章,我还在不断理解与学习中,我们先来Demo一个例子:
5分钟入手Spring Boot
http://127.0.0.1:8080/getLead?leadId=10xxxx46 或 http://127.0.0.1:8080/getLead/10xxxx46
其中第一条SQL是非nativeQuery的,第二、三条SQL是nativeQuery的,nativeQuery的SQL就是我们平常写的sql,而非nativeQuery的SQL,是Spring Boot JPA帮我们生成的。
新建Spring Boot项目,依赖选择JPA(spring-boot-starter-data-jpa)和Web(spring-bootstarter-web)。配置基本属性 在application.properties里配置数据源和jpa的相关属性
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot
spring.datasource.username=root
spring.datasource.password=123456
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jackson.serialization.indent_output=true
定义映射实体类
定义Controller类
@RestControllerpublic class PersonCtroller {
@AutowiredPersonServer personServer
@RequestMapping("/rollback")
public Person rollback(Person person){
return personServer.savePersonWithRollBack(person)
}
@RequestMapping("/norollback")
public Person noRollback(Person person){
return personServer.savePersonWithOutRollBack(person)
}
}
定义数据访问层
public interface PersonRepository extends JpaRepository<Person, Long>{}
定义Server层
@Servicepublic class PersonServerImp implements PersonServer {
@Autowired
PersonRepository personRepository
@Transactional(rollbackFor = {IllegalArgumentException.class})
@Override
public Person savePersonWithRollBack(Person person) {
Person p = personRepository.save(person)
if (p.getName().equals("xxx")){
throw new IllegalArgumentException("用户已存在,数据会回滚")
}
return p
}
}
在使用SpringBoot构建后台应用时,你可以使用@Entity注解定义表单数据库。根据查询相关公开信息,在@Entity中定义需要存储的实体对象名称、所属类以及每个字段的相关属性,另外,你还可以使用JPA来构建数据库,JPA会自动帮你生成表单数据库。欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)