我正在使用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”的代码记录绑定的所有User对象?
答案 0 :(得分: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
对象设置其值。