Spring Data Jpa方法定义的规则: findBy+属性+(关键字)
(1)简单条件查询
简单条件查询:查询某一个实体类或者集合。
按照Spring Data的规范的规定,查询方法以find | read | get开头,涉及查询条件时,条件的属性用条件关键字连接,要注意的是:条件属性以首字母大写。
例如:定义一个Entity实体类:
classPeople{
private String firstName;
private String lastName;
}
以上使用and条件查询时,应这样写:findByLastNameAndFirstName(StringlastName,String firstName);
注意:条件的属性名称与个数要与参数的位置与个数一一对应
(2)支持的关键字
直接在接口中定义查询方法,如果是符合规范的,可以不用写实现,目前支持的关键字写法如下:
###例如用springboot方式在ProductCategory中按categoryType查所有数据
package com.lbl.dataObject;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.DynamicUpdate;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
/**
* 类目
* Created by 李柏霖
* 2020-10-09 20:41
* product_category
*/
@Entity
@DynamicUpdate
@Data //生成getter,setter等函数
@AllArgsConstructor //生成全参数构造函数
@NoArgsConstructor //生成无参构造函数
public class ProductCategory {
/** 类目id. */
@Id
@GeneratedValue
private Integer categoryId;
/** 类目名字. */
private String categoryName;
/** 类目编号. */
private Integer categoryType;
public ProductCategory(String categoryName, Integer categoryType) {
this.categoryName = categoryName;
this.categoryType = categoryType;
}
}
ProductCategoryRepository中方法命名为findByCategoryTypeIn
package com.lbl.repository;
import com.lbl.dataObject.ProductCategory;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
/**
* Created by 李柏霖
* 2020-10-09 21:34
* 继承JpaRepository这个接口,就具备了CRUD操作
*/
public interface ProductCategoryRepository extends JpaRepository<ProductCategory, Integer> {
List<ProductCategory> findByCategoryTypeIn(List<Integer> categoryTypeList);
}
ProductCategoryRepositoryTest
package com.lbl.repository;
import com.lbl.dataObject.ProductCategory;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import java.util.Arrays;
import java.util.List;
/**
* Created by 李柏霖
* 2020-10-09 21:35
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class ProductCategoryRepositoryTest {
@Autowired
private ProductCategoryRepository repository;
@Test
public void findByCategoryTypeIn() {
List<Integer> list = Arrays.asList(2, 3, 4);
List<ProductCategory> result = repository.findByCategoryTypeIn(list);
Assert.assertNotEquals(0,result);
}
}