Hibernate和PostgreSQL char类型兼容性问题

时间:2013-09-16 17:42:57

标签: java sql hibernate jpa jdbc

我有一个客户(一个)< - > OrderRecords(很多)关系在数据库中,而OrderRecords有外键来引用Customers的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));

Hibernate代码

Customer.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
}

OrderRecord.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=?

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

0 个答案:

没有答案