dev
Spring - Spring JPA
Spring - JPA
Spring Data JPA focuses on using JPA to store data in a relational database. Its most compelling feature is the ability to create repository implementations automatically, at runtime, from a repository interface.
Spring Data JPA is a library / framework that adds an extra layer of abstraction on the top of our JPA provider.

Dependencies
- JDBC Driver
- Datasource (MySQL)
- JPA Provider (Hibernate)
Why use Spring Data JPA
它的核心价值是减少样板代码。很多常见的增删改查不需要手写大量 DAO 实现,只需要定义实体和 Repository 接口,就可以先把数据访问层搭起来。
Configuration
applicationContext.xml
Github spring-data-jpa-examples
- DataSource
- entityManagerFactory
- transactionManager
- hibernateProperties
CRUD Example
Create an interface that extends the CrudRepository interface
import org.springframework.data.repository.CrudRepository;
interface TodoRepository extends CrudRepository<TypeOfEntity, TypeOfEntityId> {
}
Create Query from Method Name
import org.springframework.data.jpa.repository.JpaRepository;
public interface PersonRepository extends JpaRepository<Person, Long> {
/**
* Finds persons by using the last name as a search criteria.
* @param lastName
* @return A list of persons which last name is an exact match with the given last name.
* If no persons is found, this method returns an empty list.
*/
public List<Person> findByLastName(String lastName);
}
Using Created Query Methods
@Service
public class someServices() {
@Resource
private PersonRepository personRepository;
public List<Person> search(String searchTerm) {
return personRepository.findAll(lastNameIsLike(searchTerm));
}
}
Spring Data JPA, Hibernate
Spring Data JPA 通常运行在 Hibernate 这样的 JPA Provider 之上。可以把它理解成:
- JPA:一套规范
- Hibernate:常见实现
- Spring Data JPA:在实现之上再封装一层更方便的 Repository 模型
参考:https://baijiahao.baidu.com/s?id=1661937038552348304&wfr=spider&for=pc