Spring boot 中自定義JpaRepository使用

普通JpaRepository類

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface EmployeeRepository extends JpaRepository<Employee,Long>{
}

JpaRepository通常的篩選查詢,都可以經過findBy的形式解決,總的很好用,可是總有一部分的業務查詢是須要JpaRepository不能解決的。這個時候,就須要在此基礎上面增長自定義的Repository類了。html

自定義Repository類

接口類

import java.util.List;
public interface EmployeeRepositoryCustom {
    List<Employee> getFirstNamesLike(String firstName);
}

實現類

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

@Repository
public class EmployeeRepositoryImpl implements EmployeeRepositoryCustom {
    @PersistenceContext
    private EntityManager entityManager;
    @Override
    public List<Employee> getFirstNamesLike(String firstName) {
        Query query = entityManager.createNativeQuery("SELECT em.* FROM spring_data_jpa_example.employee as em " +
                "WHERE em.firstname LIKE ?", Employee.class);
        query.setParameter(1, firstName + "%");
        return query.getResultList();
    }
}

**Note:**實現類的命名必須是這裏實現類的命名bean名+RepositoryImpl;這裏注入了EntityManager,關於它的標準查詢,使用我放在後面再提。java

使用自定義類Repository類

@Repository
public interface EmployeeRepository extends JpaRepository<Employee,Long>, EmployeeRepositoryCustom {
}

依舊按照JpaRepository的使用方式,只要簡單繼承就能夠了。spring

EntityManager的標準查詢

若是不想在java代碼裏面涉及太多的sql字符串,應該按照EntityManager的標準查詢方式,進行數據庫查詢,以下:sql

@Repository
public class EmployeeRepositoryImpl implements EmployeeRepositoryCustom {
    @PersistenceContext
    private EntityManager entityManager;
    @Override
    public List<Employee> getFirstNamesLike(String firstName) {
        // Query query = entityManager.createNativeQuery("SELECT em.* FROM spring_data_jpa_example.employee as em " +
        //         "WHERE em.firstname LIKE ?", Employee.class);
        // query.setParameter(1, firstName + "%");
		// return query.getResultList();
		
		CriteriaBuilder builder = entityManager.getCriteriaBuilder();
		CriteriaQuery<Employee> query = builder.createQuery(Employee.class);
		Root<Employee> root = query.from(Employee.class);
		Predicate predicate = builder.conjunction();

		predicate = builder.and(predicate,  builder.like(root.get("firstname"), "張三"));
		query.where(predicate);

		return entityManager.createQuery(query).getResultList();
    }
}

參考:

REST Query Language with Spring and JPA Criteria數據庫

1. Working with Spring Data Repositorieside

Add Custom Functionality to a Spring Data Repositoryui

相關文章
相關標籤/搜索