本文介绍了如何通过组合表使用 JpaSpecificationExecutor 创建规范?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 JpaSpecificationExecutor
来创建自定义查询.如何为以下 SQL 创建规范?
I am using JpaSpecificationExecutor
for creating custom queries. How do I create a Specification for the following SQL?
select * from employee e, address a where e.id=23415 and e.name="Foo" and a.city="London";
Java 类:
public static Specification<Employee> searchEmployee(final Map<String,String> myMap) {
return new Specification<Employee>(){
@Override
public Predicate toPredicate(Root<Employee> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
//Need to query two tables Employee and Address
}
}
推荐答案
这是一个有效的测试
@Test
public void test1() {
repository.save(makeEmployee("billy", "London"));
repository.save(makeEmployee("noby", "London"));
repository.save(makeEmployee("fred", "London"));
assertEquals(3, repository.count());
final Long id = 3l;
final String name = "noby";
final String city = "London";
Specification<Employee> specification = new Specification<Employee>() {
public Predicate toPredicate(Root<Employee> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
List<Predicate> predicates = new ArrayList<Predicate>();
predicates.add(builder.equal(root.get("id"), id));
predicates.add(builder.equal(root.get("name"), name));
predicates.add(builder.equal(root.get("address").get("city"), city));
return builder.and(predicates.toArray(new Predicate[predicates.size()]));
}
};
List<Employee> find = repository.findByIdAndNameAndAddressCity(id, name, city);
assertEquals(1, find.size());
find = repository.findAll(specification);
assertEquals(1, find.size());
}
private Employee makeEmployee(String name, String city) {
Address address = new Address();
address.setCity(city);
Employee employee = new Employee();
employee.setName(name);
employee.setAddress(address);
return employee;
}
}
存储库看起来像这样
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long>, JpaSpecificationExecutor<Employee> {
List<Employee> findByIdAndNameAndAddressCity(Long id, String name, String city);
}
实体看起来像这样
@Entity(name = "EMPLOYEE")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "NAME")
private String name;
@Column(name = "DATE_OF_BIRTH")
private Date dob;
@OneToOne(cascade=CascadeType.ALL)
@JoinColumn(name = "address_id", referencedColumnName = "id", nullable = false)
private Address address;
希望这会有所帮助.
这篇关于如何通过组合表使用 JpaSpecificationExecutor 创建规范?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!