多对多和 HQL
我上了一堂课:
@Entity
@Table(name="restaurants")
public class Restaurant {
@Id
@GeneratedValue
private int id;
private String name;
private String street;
(...)
@ManyToMany
@JoinTable(name="user_restaurant_owner",
joinColumns={@JoinColumn(name="restaurant_id")},
inverseJoinColumns={@JoinColumn(name="username")})
private List<User> owner;
如果我知道用户(“所有者”)用户名,如何获取餐厅?
Query q = session.createQuery("from Restaurant as r where r.owner = :username").setString("username", username);
它不起作用
I got class:
@Entity
@Table(name="restaurants")
public class Restaurant {
@Id
@GeneratedValue
private int id;
private String name;
private String street;
(...)
@ManyToMany
@JoinTable(name="user_restaurant_owner",
joinColumns={@JoinColumn(name="restaurant_id")},
inverseJoinColumns={@JoinColumn(name="username")})
private List<User> owner;
How to get Restaurant if I know User ("owner") username?
Query q = session.createQuery("from Restaurant as r where r.owner = :username").setString("username", username);
it doesn;t work
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果要选择集合中元素的属性,则需要加入 HQL 中的集合。
You need to join to a collection in HQL if you are selecting on properties of the element within the collection.
from Restaurant as r
应该是from Restaurant r
而不是as
(不确定 as 是否是可选的)。另外,您执行
r.owner = ...
这应该是r.owner.username = :username
from Restaurant as r
should befrom Restaurant r
noas
(not sure if as is optional).Also, you do
r.owner = ...
this should ber.owner.username = :username
r.owner
引用 Owners 表的 PRIMARY KEY。你想要的是一个子选择(为了简单起见,这里用 SQL 完成 - 我对 HQL 不太有信心):
这样,你可以将外键与其引用的字段而不是名称字段相匹配。
r.owner
references the PRIMARY KEY of the Owners table.what you want is a subselect (done in SQL here for simplicity - I'm not too confident with HQL):
this way, you match the foreign key with the field it references, rather than the name field.