如何在hibernate中编写连接查询

时间:2009-06-04 11:36:39

标签: java hibernate

我创建了两个具有多对多关系的bean和UserDomain

@Entity
@Table(name = "tblUser")
public class User implements Serializable {
    private Long id;
    private String username;
    private Set<VirtualDomain> virtualdomainset;
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

@Column(name = "username", length = 50, nullable = false)
public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}
   @ManyToMany(targetEntity = VirtualDomain.class, cascade = {CascadeType.PERSIST},fetch=FetchType.EAGER)
    @JoinTable(name = "tblUserDomainRel", joinColumns = @JoinColumn(name = "userid"), inverseJoinColumns = @JoinColumn(name = "domainid"))
    public Set<VirtualDomain> getVirtualdomainset() {
        return virtualdomainset;
    }

    public void setVirtualdomainset(Set<VirtualDomain> virtualdomainset) {
        this.virtualdomainset = virtualdomainset;
    }

}

@Entity
@Table(name = "tblVirtualDomain")
public class VirtualDomain  {
    private Long id;
    private String domainname;
    private Set<User> userset;
@Id
@JoinColumn(name = "id")
@GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

@Column(name = "domain_name")
public String getDomainname() {
    return domainname;
}

public void setDomainname(String domainname) {
    this.domainname = domainname;
}
@ManyToMany(cascade = {CascadeType.ALL},fetch=FetchType.EAGER, mappedBy = "virtualdomainset", targetEntity = User.class)

public Set<User> getUserset() {
    return userset;
}

public void setUserset(Set<User> userset) {
    this.userset = userset;
}
}

如何通过hibernate获取用户的数据,如与特定域相关的用户名。

2 个答案:

答案 0 :(得分:10)

要添加到上帝的答案,如果由于某种原因你需要急切地获取实体关系,那么连接语法将是连接提取。

from VirtualDomain vd join fetch vd.usersset u 
   where vd.domainname = 'example.com' and u.username like 'foo%'

答案 1 :(得分:2)

总是让HQL与测试系统不同......但是我们走了:

select u from VirtualDomain vd join User vd.usersset u 
       where vd.domainname = 'example.com' and u.username like 'foo%'

让我知道你是怎么过的。

我在购买Intellji之前经常做的一个提示是在调试器中停止应用程序,然后使用即时窗口来试验HQL。

在我看来,hibernate documentation加入一直有点神秘。