Hibernate Composite key Criteria Join

时间:2016-03-18 21:43:06

标签: java hibernate jpa

我正在尝试在复合键上执行多个连接。我正在使用别名强制创建连接,但似乎连接不是由Hibernate生成的。我不知道为什么会这样。我可以使用本机SQL查询,但不能使用标准。

我怀疑它可能与复合键定义的映射方式有关(参见BusinessServiceUser上的associationOverrides)

以下是我的域模型类和查询信息。 欢迎任何想法:)

的BusinessService

@Entity
@Table(name = "business_services")
public class BusinessService extends AbstractEntity implements Serializable {
  @Column(name = "name", unique = true, nullable = false, length = 255)
  private String name;

  @OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.businessService", cascade = CascadeType.ALL)
  @ForeignKey(name = "FK_BUSINESS_SERVICE_USERS")
  private Set<BusinessServiceUser> businessServiceUsers = new HashSet<BusinessServiceUser>();
...
}

BusinessServiceUser

@Entity
@Table(name = "REL_BUSINESS_SERVICE_USER")
@AssociationOverrides({
    @AssociationOverride(name = "pk.businessService", joinColumns = @JoinColumn(name = "BUSINESS_SERVICE_ID")),
    @AssociationOverride(name = "pk.user", joinColumns = @JoinColumn(name = "USER_ID")) })
public class BusinessServiceUser implements Serializable {

  private BusinessServiceUserId pk = new BusinessServiceUserId();
  private Boolean master;

  public BusinessServiceUser() {

  }

  @EmbeddedId
  public BusinessServiceUserId getPk() {
    return pk;
  }

  public void setPk(BusinessServiceUserId pk) {
    this.pk = pk;
  }

  @Transient
  public User getUser() {
    return getPk().getUser();
  }

  public void setUser(User user) {
    getPk().setUser(user);
  }

  @Transient
  public BusinessService getBusinessService() {
    return getPk().getBusinessService();
  }

  public void setBusinessService(BusinessService businessService) {
    getPk().setBusinessService(businessService);
  }

  public boolean isMaster() {
    return master;
  }

  public void setMaster(boolean master) {
    this.master = master;
  }
...
}

BusinessServiceUserId

@Embeddable
public class BusinessServiceUserId implements Serializable {

  private User user;
  private BusinessService businessService;

  @ManyToOne
  public User getUser() {
    return user;
  }

  public void setUser(User user) {
    this.user = user;
  }

  @ManyToOne
  public BusinessService getBusinessService() {
    return businessService;
  }

  public void setBusinessService(BusinessService businessService) {
    this.businessService = businessService;
  }
...
}

用户

@Entity
@Table(name = "USERS")
public class User extends AbstractEntity implements Serializable {

  @Column(name = "first_name", nullable = false, length = 50)
  private String firstName;

  @Column(name = "last_name", nullable = false, length = 100)
  private String lastName;

  @Column(name = "email_address", unique = true, nullable = false, length = 150)
  private String emailAddress;

  @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.DETACH, targetEntity = Role.class)
  @JoinTable(name = "REL_USER_ROLE", joinColumns = @JoinColumn(name = "USER_ID", nullable = false) , inverseJoinColumns = @JoinColumn(name = "ROLE_ID", nullable = false) )
  @ForeignKey(name = "FK_USER_ROLE")
  private Set<Role> roles = new HashSet<Role>(0);

  @OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.user")
  @ForeignKey(name = "FK_USER_BUSINESS_SERVICE")
  private Set<BusinessServiceUser> businessServiceUsers = new HashSet<BusinessServiceUser>(0);

...
}

角色

@Entity
@Table(name = "role")
public class Role extends AbstractEntity implements Serializable {

  @Enumerated(EnumType.STRING)
  @Column(name = "name", unique = true, nullable = false)
  private RoleType name;

  @Column(name = "code", unique = true, nullable = false)
  private String code;

  @ManyToMany(fetch = FetchType.LAZY, mappedBy = "roles")
  @ForeignKey(name = "FK_ROLE_USERS")
  private List<User> users = new ArrayList<User>(0);
...
}

DAO条件查询

Criteria criteria = getSession().createCriteria(
            BusinessServiceUser.class);

criteria.setFetchMode("pk.user", FetchMode.JOIN);
criteria.createAlias("pk.user", "userAlias", Criteria.LEFT_JOIN);

criteria.setFetchMode("pk.businessService", FetchMode.JOIN);
criteria.createAlias("pk.businessService", "bsAlias", Criteria.LEFT_JOIN);

criteria.setFetchMode("userAlias.roles", FetchMode.JOIN);
criteria.createAlias("userAlias.roles", "roleAlias");

criteria.add(Restrictions.eq("bsAlias.name", businessService.getName()));
criteria.add(Restrictions.eq("roleAlias.name", RoleType.ROLE1));

criteria.addOrder(Order.asc("master"));
return criteria.list();

SQL生成的查询

DEBUG org.hibernate.SQL - 
select
    this_.BUSINESS_SERVICE_ID as BUSINESS2_3_0_,
    this_.USER_ID as USER3_3_0_,
    this_.master as master3_0_ 
from
    REL_BUSINESS_SERVICE_USER this_ 
where
    bsalias2_.name=? 
    and rolealias3_.name=? 
order by
    this_.master asc
Hibernate: 
select
    this_.BUSINESS_SERVICE_ID as BUSINESS2_3_0_,
    this_.USER_ID as USER3_3_0_,
    this_.master as master3_0_ 
from
    REL_BUSINESS_SERVICE_USER this_ 
where
    bsalias2_.name=? 
    and rolealias3_.name=? 
order by
    this_.master asc

错误

java.sql.SQLException: ORA-00904: "ROLEALIAS3_"."NAME": invalid identifier

使用本机SQL查询

 List<Object[]> result = getSession()
     .createSQLQuery(
     "select "
     + "  bsu.BUSINESS_SERVICE_ID as bsId, "
     + "  bsu.USER_ID as userId, "
     + "  bsu.master as master, "
     + "  bs.name as business_service, "
     + "  u.first_name as first_name, "
     + "  u.last_name as last_name, "
     + "  u.email_address as email, "
     + "  r.name as role "
     + "from "
     + "  REL_BUSINESS_SERVICE_USER bsu "
     + "  left outer join users u ON bsu.user_id = u.id "
     + "  left outer join business_services bs ON bsu.business_service_id = bs.id "
     + "  left outer join rel_user_role rur ON u.id = rur.user_id "
     + "  left outer join role r ON rur.role_id = r.id "
     + "where " 
     + "  bs.name = '" + businessService.getName() + "' "
     + "  and r.name like '" + RoleType.ROLE1 + "' "
     + "order by master asc")
   .list();

功能

  • Hibernate 3.6.10.Final
  • JPA 2.0
  • Spring 4.0.0
  • Oracle JDBC驱动程序版本10.2.0.3.0

1 个答案:

答案 0 :(得分:3)

首先,为什么不尝试减少minimalistic example?您的样本涉及许多实体和关系,为什么不减少它,即使只是为了您自己的故障排除时间?

其次,您的代码不完整,它错过了User和其他实体的id。为了回答目的,我假设id已定义在某处。

我将提供没有业务服务和角色的答案,我想类似的解决方案将适用。

我们如何解决它?

首先,减少到最简单的标准和实体集。例如,对BusinessServiceUser.User.emailAddress:

的限制
Criteria criteria = session.createCriteria(
            BusinessServiceUser.class, "bu");
criteria.setFetchMode("bu.pk.user", FetchMode.JOIN);
criteria.createAlias("bu.pk.user", "userAlias", Criteria.LEFT_JOIN);
criteria.add(Restrictions.eq("userAlias.emailAddress", "test@test.com"));

生成的SQL查询:

select
    this_.BUSINESS_SERVICE_ID as BUSINESS3_33_0_,
    this_.USER_ID as USER2_33_0_,
    this_.master as master33_0_ 
from
    REL_BUSINESS_SERVICE_USER this_ 
where
    useralias1_.email_address=?

显然,缺少预期的连接(因此您不需要复杂的示例来重现问题)。

查看BusinessServiceUserId,它使用@Embedded和@ManyToOne。注意这是Hibernate特定的扩展,通常你不应该在@Embedded中使用@ManyToOne。让我们尝试简单查询而不是标准:

    Query q = session.createQuery("from BusinessServiceUser as u left outer join u.pk.user where u.pk.user.emailAddress='test@test'");
    q.list();

生成的SQL:

select
    businessse0_.BUSINESS_SERVICE_ID as BUSINESS2_33_0_,
    businessse0_.USER_ID as USER3_33_0_,
    user1_.id as id54_1_,
    businessse0_.master as master33_0_,
    user1_.email_address as email2_54_1_,
    user1_.first_name as first3_54_1_,
    user1_.last_name as last4_54_1_ 
from
    REL_BUSINESS_SERVICE_USER businessse0_ 
left outer join
    USERS user1_ 
        on businessse0_.USER_ID=user1_.id 
where
    user1_.email_address='test@test'

Whoala,加入就在那里。所以你在这里至少有一个解决方案 - 使用查询而不是标准。可以使用fetch join等来制作更复杂的查询。

现在到标准。首先,让我们检查传统的标准映射。使用标准映射,您无法引用@Embedded中定义的@ManyToOne。让我们将映射添加到BusinessServiceUser类本身而不是@Transient

 @ManyToOne(fetch=FetchType.LAZY)
 public User getUser() {
   return getPk().getUser();
 }

请注意,此附加映射不会花费您。

Criteria criteria = session.createCriteria(
            BusinessServiceUser.class, "bu");
criteria.setFetchMode("bu.user", FetchMode.JOIN);
criteria.createAlias("bu.user", "userAlias", Criteria.LEFT_JOIN);
criteria.add(Restrictions.eq("userAlias.emailAddress", "test@test.com"));

生成的SQL:

select
    this_.BUSINESS_SERVICE_ID as BUSINESS3_33_1_,
    this_.USER_ID as USER2_33_1_,
    this_.master as master33_1_,
    this_.user_id as user2_33_1_,
    useralias1_.id as id54_0_,
    useralias1_.email_address as email2_54_0_,
    useralias1_.first_name as first3_54_0_,
    useralias1_.last_name as last4_54_0_ 
from
    REL_BUSINESS_SERVICE_USER this_ 
left outer join
    USERS useralias1_ 
        on this_.user_id=useralias1_.id 
where
    useralias1_.email_address=? 

所以在这里你得到了有标准的解决方案2。在实体中添加映射并在标准中使用它们而不是复杂的pk。

虽然我不知道将@EmbeddedId pk与@AssotiationOverride一起使用的设置,条件和连接提取的方式与您尝试的完全相同,但可能它不是最好的方法。