如何在Hibernate中自定义类型上添加where

mm5n2pyu  于 2023-04-21  发布在  其他
关注(0)|答案(1)|浏览(166)

EmployeeRepository类

CriteriaQuery<Employee> query = criteriaBuilder.createQuery(Employee.class);
Root<Employee> employee = query.from(Employee.class);
query.select(employee)
.where(employee.get("address.city").in("pune","Mumbai","Delhi"));// getting error here

员工类

class Employee {
private Long empId;
@Type(employeeCustomType)
private Address address; //this is custom type 
// setter and getter
}

地址类

class Address{
private String city;
private Integer zipCode;
}

请假设我们有employeeCustomType类
有没有人有任何想法。我只是试图添加在城市参数的地址对象的where子句。使用CriteriaBuilder。

在hibernate中实现此场景的其他建议

gr8qqesn

gr8qqesn1#

如果将Addresscity:zipCode的形式存储在varchar字段中(例如:Delhi:110001),则以下解决方案可能会有所帮助。

CriteriaQuery<Employee> query = criteriaBuilder.createQuery(Employee.class);
Root<Employee> employee = query.from(Employee.class);
query.select(employee).where(
    criteriaBuilder.or(
        criteriaBuilder.like(employee.get("address").as(String.class), "Delhi:%"),
        criteriaBuilder.like(employee.get("address").as(String.class), "Mumbai:%")
    )
);

注意:这里的主要思想是,在构建条件时,您应该将address字段表示为普通字符串。

相关问题