我有三个实体,例如:
@Entity
@Table(name = "product")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
@Expose
private long id;
@ManyToOne
@JoinColumn(name = "users_id")
@Expose
private User user;
}
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
@Expose
private long id;
}
@Entity
@Table(name = "users_phone")
public class UserPhone {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
@Expose
private int id;
@ManyToOne
@JoinColumn(name = "users_id")
@Expose
private User user;
}
现在,我想从基于三个表的产品表中获取结果。因此,我制定了规范,以便可以将其传递到存储库中。这是规范的代码。
Specification<ProductPost> productSpecification = new Specification<ProductPost>() {
@Override
public Predicate toPredicate(Root<ProductPost> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
List<Predicate> predicates = new ArrayList<>();
criteriaQuery = criteriaBuilder.createQuery();
if (userName.length() > 0) {
predicates.add(criteriaBuilder.like(root.join("user").<String>get("fullName"), "%" + userName + "%"));
}
if (phoneNumber.length() > 0) {
// Below line isn't working actually as join("UserPhone") - 'user' table has no reference for 'userPhone'. But 'userPhone' has 'user'.
predicates.add(criteriaBuilder.like(root.join("user").join("UserPhone").<String>get("phoneNumber"), "%" + postType + "%"));
}
return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
}
};
是的,如果我在“用户”表中有“ userPhone”引用(例如-
product -> user -> userPhone
而不是product -> user, userPhone -> user
),这将很容易。但是我的模式就是这样。现在,我很难加入3个表并获取结果。 最佳答案
如果使用cross-join
代替join
,则可以尝试此解决方案
if (phoneNumber.length() > 0) {
Root<UserPhone> userPhone = query.from(UserPhone.class);
predicates.add(criteriaBuilder.equal(
root.join("user").get("id"),
userPhone.get("user").get("id")
));
predicates.add(criteriaBuilder.like(
userPhone.get("phoneNumber"),
"%" + postType + "%"
));
}