多对多和 HQL

发布于 2024-11-30 04:47:20 字数 630 浏览 0 评论 0原文

我上了一堂课:

@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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

夏夜暖风 2024-12-07 04:47:20

如果要选择集合中元素的属性,则需要加入 HQL 中的集合。

from Restaurant r join r.owner o where o.username = :username

You need to join to a collection in HQL if you are selecting on properties of the element within the collection.

from Restaurant r join r.owner o where o.username = :username
笨笨の傻瓜 2024-12-07 04:47:20

from Restaurant as r 应该是 from Restaurant r 而不是 as (不确定 as 是否是可选的)。
另外,您执行 r.owner = ... 这应该是 r.owner.username = :username

from Restaurant as r should be from Restaurant r no as (not sure if as is optional).
Also, you do r.owner = ... this should be r.owner.username = :username

梦屿孤独相伴 2024-12-07 04:47:20

r.owner 引用 Owners 表的 PRIMARY KEY。

你想要的是一个子选择(为了简单起见,这里用 SQL 完成 - 我对 HQL 不太有信心):

select {r.*} from Restaurant as r where r.owner = ( select id from Owners as own where own = :username ).setString("username", username)

这样,你可以将外键与其引用的字段而不是名称字段相匹配。

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):

select {r.*} from Restaurant as r where r.owner = ( select id from Owners as own where own = :username ).setString("username", username)

this way, you match the foreign key with the field it references, rather than the name field.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文