Spring数据JPA在查询中加入子类

时间:2017-06-21 07:18:17

标签: hibernate spring-data spring-data-jpa hql jpa-2.0

考虑这个课程:

@Entity
@Table(name = "USER_TABLE")
@Inheritance(strategy = InheritanceType.JOINED)
public class User {

    @Id
    @GenericGenerator(name = "system-uuid", strategy = "uuid2")
    @GeneratedValue(generator="system-uuid")
    @Column(name = "id", unique = true)
    @Type(type= "org.hibernate.type.PostgresUUIDType")
    private UUID id;

    @Column(name = "USERNAME")
    private String userName;
}

及其简单的孩子:

@Entity
@Table(name = "CUSTOMER")
public class Customer extends User{
        //some extra fields
}

我有另一个与用户有关的课程:

@Entity
@Table(name = "USER_ACTIVITY")
public class UserActivity {

    @ManyToOne
    @JoinColumn(name = "USERID")
    private User user;

    //id and other fields
}

这是棘手的部分。我想获取与“客户”相关的UserActivity类型的所有对象。我试过这样的事情:

public interface UserActivityRepository extends PagingAndSortingRepository<UserActivity,UUID> {
    @Query("select u from UserActivity u join Customer.id")
    List<UserActivity> findAllByUserIsNotNullOrderByCreatedDesc(Pageable pageable);
}

但是hibernate告诉我,我已经指定了一条无效的路径。

你可以帮我吗?

2 个答案:

答案 0 :(得分:1)

您可以明确加入Customer或按User ID属于Customer ID进行过滤:

  1. select u from UserActivity u, Customer c where u.user.id = c.id
  2. select u from UserActivity u where u.user.id in (select id from Customer)
  3. 选择您喜欢的任何一个,因为现代数据库中的优化器将优化两个查询,以便在两种情况下性能都相同。

答案 1 :(得分:0)

User实体中使用@DiscriminatorColumn(name = "TYPE")

@Entity
@Table(name = "USER_TABLE")
@Inheritance(strategy = InheritanceType.JOINED)
@DiscriminatorColumn(name = "TYPE")
@DiscriminatorValue("USER")
public class User {

    ...

}

Customer实体

中定义@DiscriminatorValue("CUSTOMER")
@Entity
@Table(name = "CUSTOMER")
@DiscriminatorValue("CUSTOMER")
public class Customer extends User {

    ...

}

像这样查询您的存储库

@Query("select u from UserActivity u join u.user user where TYPE(user) = 'CUSTOMER'")
List<UserActivity> findAllByUserIsNotNullOrderByCreatedDesc();

注意: @DiscriminatorValue注释不是必需的。 JPA根据实体类型推断列名称。