# jpa **Repository Path**: zhai_huabing/jpa ## Basic Information - **Project Name**: jpa - **Description**: API、JPQL查询语言、SpringData JPA - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 1 - **Forks**: 0 - **Created**: 2021-12-04 - **Last Updated**: 2023-11-06 ## Categories & Tags **Categories**: Uncategorized **Tags**: 框架 ## README ### 概念 #### JPA 的API 用来操作实体对象,执行CRUD操作,框架在后台替我们完成所有的事情,开发者从繁琐的JDBC和SQL代码中解脱出来。 如:entityManager.merge(T t) #### JPQL查询语言 通过面向对象而非面向数据库的查询语言查询数据,避免程序的SQL语句紧密耦合。 ``` String sql = "from Student where id =?1 "; Query query = entityManager.createQuery(sql); ``` #### jpa、springDataJpa、Hibernate的关系 jpa是抽象类和接口、Hibernate是对jpa的实现,springDataJpa是对jpa规范的进一步封装。 Spring Data JPA是在实现了JPA规范的基础上封装的一套 JPA 应用框架,虽然ORM框架都实现了JPA规范,但是在不同的ORM框架之间切换仍然需要编写不同的代码,而使用Spring Data JPA能够方便大家在不同的ORM框架之间进行切换而不需要更改代码。Spring Data JPA旨在通过将统一ORM框架的访问持久层的操作,来提高开发人的效率。 #### 优点 能够以面向对象的方式进行持久化操作,减少SQL的书写。 #### 原理 基本的增删改查操作的实现依赖于,动态代理机制帮助我们生成了dao接口的实现类对象(org.springframework.data.jpa.repository.support.SimpleJpaRepository)。 自定义dao接口的时候并没有实现所继承的接口: ``` public interface StudentDao extends JpaRepository, JpaSpecificationExecutor ``` SimpleJpaRepository帮我们实现了dao所继承的两个接口(借助JPA完成数据库的增删改查操作): ``` public class SimpleJpaRepository implements JpaRepository, JpaSpecificationExecutor ``` 如:根据ID查询的方法 ``` public T findOne(ID id) { Assert.notNull(id, "The given id must not be null!"); Class domainType = this.getDomainClass(); if (this.metadata == null) { return this.em.find(domainType, id); } else { LockModeType type = this.metadata.getLockModeType(); Map hints = this.getQueryHints(); return type == null ? this.em.find(domainType, id, hints) : this.em.find(domainType, id, type, hints); } } ``` #### 操作数据库的方式 接口中定义好的方法 在dao接口中借助于JPQL语句 在dao接口中借助原生SQL语句 借助dao接口方法命名规则 Specification接口查询