1

我正在使用 JPA 2.0、Hibernate 4.1.0.Final 和 Spring 3.1.1.RELEASE。我有两个实体:

@Entity
@Table(name = "user",
    uniqueConstraints = { @UniqueConstraint(columnNames = { "USER_NAME" }) }
)
public class User implements Comparable<User>, Serializable
{
    ...
    @Column(name = "first_name")
    @NotNull
    /* the first name of the User */
    private String firstName;

@Entity
@Table(name="code_user",
    uniqueConstraints = { 
        @UniqueConstraint(columnNames = { "SAMPLE_WORD_ID", "USER_ID" }) }
)
public class CodeUser 
{

    @Id
    @NotNull
    @GeneratedValue(generator = "uuid-strategy")
    @Column(name = "ID")
    private String id;

    @ManyToOne
    @JoinColumn(name = "CODE_ID", nullable = false, updatable = true)
    private Code code;

    @ManyToOne
    @JoinColumn(name = "USER_ID", nullable = false, updatable = true)
    private User user;

如何编写 JPA/CriteriaBuilder 查询来查找名字与“Dave”匹配且与代码为“abode”的代码记录相关联的所有用户对象?

4

1 回答 1

1

我可能错过了 HQL 语法元素

SELECT user FROM CodeUser codeUser 
    JOIN FETCH codeUser.user user
    JOIN FETCH codeUser.code code 
        WHERE user.firstName = 'Dave' AND code.value = 'abode'

假设Code有一个字段value保存值"abode"。您可能不需要FETCH.

您始终可以用占位符?或命名占位符替换文字值,:name并从Query对象设置它们的值。

于 2013-09-12T20:59:13.573 回答