单表继承的JPA 2条件查询(Hibernate)

时间:2016-06-01 03:47:49

标签: java hibernate jpa

我的项目正在使用JPA 2和Hibernate,并且有一个表继承设置来处理两种类型的客户。当我尝试使用Spring Data JPA规范查询客户数据时,我总是得到不正确的结果。我认为这是因为我创建了错误的查询,但仍然不知道如何使其正确。

这是我的测试代码(我正在尝试按公司名称搜索客户):

@Test
public void test() {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Customer> customerQuery = criteriaBuilder.createQuery(Customer.class);
    Root<Customer> customerRoot = customerQuery.from(Customer.class);
    Root<CompanyCustomer> companyCustomerRoot = customerQuery.from(CompanyCustomer.class);

    CriteriaQuery<Customer> select = customerQuery.select(customerRoot);
    select.where(criteriaBuilder.equal(companyCustomerRoot.get(CompanyCustomer_.companyName), "My Company Name"));

    TypedQuery<Customer> query = entityManager.createQuery(select);
    List<Customer> results = query.getResultList();

    assertEquals(1, results.size()); // always got size 2
}

日志中的SQL脚本:

Hibernate: 
    select
        customer0_.id as id2_16_,
        customer0_.type as type1_16_,
        customer0_.first_name as first_na8_16_,
        customer0_.last_name as last_nam9_16_,
        customer0_.company_name as company13_16_ 
    from
        customers customer0_ cross 
    join
        customers companycus1_ 
    where
        companycus1_.type='COMPANY' 
        and companycus1_.company_name=?

我的数据库中有两条记录:

insert into customers (id, type, company_name) values (1, 'COMPANY', 'My Company Name');

insert into customers (id, type, first_name, last_name) values (2, 'PERSONAL', 'My First Name', 'My Last Name');

我的单表继承设置:

@Entity
@Table(name = "customers")
@DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.STRING)
public abstract class Customer {    

    @Enumerated(EnumType.STRING)
    @Column(name = "type", insertable = false, updatable = false)
    private CustomerType type;
    private String contactNumber;
}

@Entity
@DiscriminatorValue("PERSONAL")
public class PersonalCustomer extends Customer {          

    private String firstName;
    private String lastName;    
}

@Entity
@DiscriminatorValue("COMPANY")
public class CompanyCustomer extends Customer {

    private String companyName;
}

public enum CustomerType {

    COMPANY, PERSONAL;
}

1 个答案:

答案 0 :(得分:0)

我找到了答案 JPA Criteria Query over an entity hierarchy using single table inheritance

  

解决方案:   使用CriteriaBuilder.treat()来向下转换Customer实体,而不是使用CriteriaQuery.from()