【发布时间】:2015-09-29 13:11:22
【问题描述】:
我有这种情况:
User及其相关的UserRole实体类,如下:
@Entity
@Table(name="USER")
public class User implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="ID", unique=true, nullable=false)
private int id;
@Column(name="USERNAME", unique=true, nullable=false, length=255)
private String username;
@OneToMany(mappedBy="user")
private List<UserRole> userRoles;
}
和
@Entity
@Table(name="user_roles")
public class UserRole implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="user_role_id", unique=true, nullable=false)
private int userRoleId;
@Column(nullable=false, length=45)
private String role;
@ManyToOne
@JoinColumn(name="username", nullable=false)
private User user;
}
现在,我需要查询所有具有特定角色的用户。我正在尝试加入 JPA 规范,就像这样:
Join<User, UserRole> join = root.join(User_.userRoles);
Expression<String> match = join.get(UserRole_.role);
Predicate predicate = builder.equal(match, "ROLE_USER");
问题是生成的联接将在 User.id 和 UserRole.username 之间,查询显然没有结果。
select count(user0_.ID) as col_0_0_ from USER user0_ inner join
user_roles userroles1_ on user0_.ID=userroles1_.username where
userroles1_.role='ROLE_USER'
我需要在 username 字段上都有 on 子句:
... from USER user0_ inner join
user_roles userroles1_ on user0_.USERNAME=userroles1_.username ...
我注意到 Join 类有 .on 方法:
根据指定的ON修改join限制结果 健康)状况。替换之前的 ON 条件(如果有)。返回加入 对象
这是正确的方法吗?如果是这样,我该如何实现?
Join<User, UserRole> join = root.join(User_.userRoles).on(????);
提前谢谢你。
更新:
UserRole_元模型类
@StaticMetamodel(UserRole.class)
public class UserRole_ {
public static volatile SingularAttribute<UserRole, Integer> userRoleId;
public static volatile SingularAttribute<UserRole, String> role;
public static volatile SingularAttribute<UserRole, User> user;
}
User_元模型类:
@StaticMetamodel(User.class)
public class User_ {
public static volatile SingularAttribute<User, Integer> id;
public static volatile SingularAttribute<User, String> username;
public static volatile ListAttribute<User, UserRole> userRoles;
}
【问题讨论】:
-
您可以使用 JPA 2.1
ON子句(EclipseLink 在其最新版本中支持此功能),但您必须使用 JPQL 而不是 Criteria。只要我担心,我不明白为什么您的 Critera 请求不起作用,因为表user_roles的列username将包含用户 ID 而不是其名称(因为用户 ID 是@Id列User) -
谢谢@clapsus 你能发一个例子吗?
-
@clapsus
user_roles的列username包含用户的用户名,因此on 子句应该在两个表的username列之间 -
如何填满你的桌子?使用 JPA,还是手动(sql 脚本...等)?
-
使用 JPA,它是一种用户配置应用程序@clapsus
标签: java hibernate jpa join specifications