官方文档:Spring Data JPA - Reference Documentation
1、继承类CrudRepository或者PagingAndSortingRepository
import org.springframework.data.repository.CrudRepository;
public interface CustomerRepository extends CrudRepository<Customer,Long> {
}
2、自定义
1.jpql语言
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;
public interface CustomerPagingAndSortingRepository extends PagingAndSortingRepository<Customer, Long> {
//查询:采用jpql语言
@Query("FROM Customer where customerName=?1")
Customer findCustomerByCustomerName(String customerName);
@Transactional //增删改都需要加上事务
@Modifying
@Query("UPDATE Customer c set c.customerName=:xxx where c.customerId=:id")
Customer updateCustomer(@Param("xxx") String customerName, @Param("id")Long id);
//原生的SQl语句
@Query(value = "select * FROM cst_customer where customerName=?1")
Customer findCustomerByCustomerNameBySql(String customerName);
}
2.命名规范
find...By
exists...By
count...By
...First<number>... 查找第一条或者前number条
谓词关键字:And Or Is/Equals Like NotLike Not In NotIn
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface CustomerRepositoryForName extends PagingAndSortingRepository<Customer, Long> {
List<Customer> findByCustomerName(String customerName);
boolean existsByCustomerNam(String customerName);
}
3.query by example 不推荐使用
只适用于字符串的匹配
public interface CustomerQBERepository extends PagingAndSortingRepository<Customer, Long>,QueryByExampleExecutor<Customer> {
}
使用
@ContextConfiguration(classes = SpringJPAConfig.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class SpringQBETest {
@Autowired
CustomerQBERepository repository;
@Test
public void test1(){
Customer customer = new Customer();
customer.setCustomerName("李四");
customer.setCustomerId(5L);
//匹配器
ExampleMatcher matcher=ExampleMatcher.matching().
withIgnorePaths("customerName").
withStringMatcher(ExampleMatcher.StringMatcher.ENDING). //全部匹配生效
withMatcher("",m->m.endsWith()) 单个条件匹配生效
;
//样例
Example<Customer> of = Example.of(customer,matcher);
List<Customer> xx = (List<Customer>) repository.findAll(of);
System.out.println(xx);
}
}
4.queryDSL 面向Q类
public interface CustomerQUERYDSLRepository extends CrudRepository<Customer,Long>, QuerydslPredicateExecutor<Customer> {
}
使用
// pom需要增加 这里会生成Q类,需要将生成的Q类在项目里面设置成source文件
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-jpa</artifactId>
<version>${querydsl.version}</version> // 采用最新版本即可
</dependency>
......
<build>
<plugins>
<plugin>
<groupId>com.mysema.maven</groupId>
<artifactId>apt-maven-plugin</artifactId>
<version>1.1.3</version>
<dependencies>
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-apt</artifactId>
<version>${querydsl.version}</version>
</dependency>
</dependencies>
<executions>
<execution>
<phase>generate-sources</phase>
<goals>
<goal>process</goal>
</goals>
<configuration>
<outputDirectory>target/generated-sources/queries</outputDirectory>
<processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
@ContextConfiguration(classes = SpringJPAConfig.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class SpringQUERYDSLTest {
@Autowired
CustomerQUERYDSLRepository repository;
@Test
public void test1(){
QCustomer qCustomer = QCustomer.customer;
BooleanExpression and = qCustomer.customerName.in("李四", "阿姆斯特威廉")
.and(qCustomer.customerId.gt(1L)) // 大于
.and(qCustomer.customerAddress.eq("三国"));
Optional<Customer> one = repository.findOne(and);
}
}
5.Specification
public interface CustomerSpecificationRepository extends PagingAndSortingRepository<Customer, Long>, JpaSpecificationExecutor<Customer> {
}
@ContextConfiguration(classes = SpringJPAConfig.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class SpringSpecificationTest {
@Autowired
CustomerSpecificationRepository repository;
@Test
public void test2() {
List<Customer> all = repository.findAll(new Specification<Customer>() {
@Override
public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
//获取类的参数
Path<Object> customerId = root.get("customerId");
Path<Object> customerName = root.get("customerName");
Path<Object> customerAddress = root.get("customerAddress");
Predicate p1 = criteriaBuilder.equal(customerAddress, "刑法课上"); //第一个条件
Predicate p2 = criteriaBuilder.equal(customerId, 3L); //第二个条件
CriteriaBuilder.In<Object> in = criteriaBuilder.in(customerName);
in.value("张三啊").value("李四");
Predicate and = criteriaBuilder.and(p1, p2, in); //与逻辑连接三个条件 ,参与也可以为Predicate数组
// return p1;
// return and;
//排序
Order desc = criteriaBuilder.desc(customerId);
return query.where(and).orderBy(desc).getRestriction();
}
});
}
}
6.原生
@ContextConfiguration(classes = SpringJPAConfig.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class SpringSpecificationTest {
@PersistenceContext //替代@Autowired,解决线程安全问题
EntityManager em;
@Test
public void test3() {
JPAQueryFactory factory = new JPAQueryFactory(em);
QCustomer customer = QCustomer.customer;
// 查询条件
JPAQuery<Customer> customerJPAQuery = factory.select(customer)
.from(customer)
.where(customer.customerId.gt(2L))
.orderBy(customer.customerId.desc());
// 执行查询
List<Customer> fetch = customerJPAQuery.fetch();
for (Customer fetch1 : fetch) {
System.out.println(fetch1);
}
}
}