0

我在数据库中有一个 Customers(one) <-> OrderRecords(many) 关系,并且 OrderRecords 具有引用客户 ID 的外键。

CREATE TABLE customers (cid VARCHAR(8) PRIMARY KEY, name VARCHAR(255));

CREATE TABLE orderrecords (order_id INT, customer_id VARCHAR(8), amount REAL, FOREIGN KEY(customer_id) REFERENCES customers(cid));

并且休眠代码是

客户.java

@Entity
@Table(name="Customers")
public class Customer implements Serializable {

    @Id
    @Column(name="cid")
    private String cid;

    @OneToMany(fetch=FetchType.EAGER, mappedBy="orderRecordPK.customer")
    @Cascade(CascadeType.ALL)
    private Set<OrderRecord> orderRecords = new HashSet<OrderRecord>();

    ...
    other fields, getters and setters
}

订单记录.java

@Entity
@Table(name="OrderRecords")
public class OrderRecord implements Serializable {

    @EmbeddedId
    private OrderRecordPK orderRecordPK;

    ...
    other fields, getters and setters
}

OrderRecordPK.java

@Embeddable
public class OrderRecordPK implements Serializable{
    @Column(name="order_id")
    private int orderId;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="customer_id", nullable=false)
    private Customer customer;

    ...
    other fields, getters and setters
}

数据库是 PostgreSQL。问题是当 OrderRecords 表中的外键是 varchar 类型时,一切正常。生成的 HQL 是
Hibernate: select customer0_.cid as cid0_1_, customer0_.name as name0_1_, orderrecor1_.customer_id as customer3_0_3_, orderrecor1_.customer_id as customer3_3_, orderrecor1_.order_id as order1_3_, orderrecor1_.customer_id as customer3_2_0_, orderrecor1_.order_id as order1_2_0_, orderrecor1_.amount as amount2_0_ from Customers customer0_ left outer join OrderRecords orderrecor1_ on customer0_.cid=orderrecor1_.customer_id where customer0_.cid=?

但是如果 OrderRecords 表中的外键是 char 类型,则 OrderRecords 不会返回任何数据。HQL 将是
Hibernate: select customer0_.cid as cid0_1_, customer0_.name as name0_1_, orderrecor1_.customer_id as customer3_0_3_, orderrecor1_.customer_id as customer3_3_, orderrecor1_.order_id as order1_3_, orderrecor1_.customer_id as customer3_2_0_, orderrecor1_.order_id as order1_2_0_, orderrecor1_.amount as amount2_0_ from Customers customer0_ left outer join OrderRecords orderrecor1_ on customer0_.cid=orderrecor1_.customer_id where customer0_.cid=?

Hibernate: select orderrecor0_.customer_id as customer3_0_1_, orderrecor0_.customer_id as customer3_1_, orderrecor0_.order_id as order1_1_, orderrecor0_.customer_id as customer3_2_0_, orderrecor0_.order_id as order1_2_0_, orderrecor0_.amount as amount2_0_ from OrderRecords orderrecor0_ where orderrecor0_.customer_id=?

解决问题的正确方法是什么?

4

0 回答 0