hibernate postgres多对一映射问题

时间:2013-12-12 12:18:35

标签: hibernate postgresql

生成“create table”sql时,我遇到了hibernate映射的问题。 属性sid是String类型,但在数据库中生成表acl_entry后它变为整数类型。我不知道为什么。这导致了如下错误:

org.postgresql.util.PSQLException: ERROR: insert or update on table "acl_entry"
violates foreign key constraint "id"
  Detail: Key (sid)=(0) is not present in table "acl_sid".
        at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryEx
ecutorImpl.java:2157).

感谢任何帮助。

这是我的代码:

AclEntry.java:

@Id
@SequenceGenerator(name="aclentry_identifier_seq", sequenceName="aclentry_identifier_seq", allocationSize=1)
@GeneratedValue(strategy = GenerationType.AUTO, generator="aclentry_identifier_seq")
@Column(name = "id", insertable=false, updatable=false)
private Integer id;



@ManyToOne(fetch=FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "sid", nullable = false)
@ForeignKey(name = "id")
private AclSid aclSid;


public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

AclSid.java:

@Id
    @SequenceGenerator(name="aclsid_identifier_seq", sequenceName="aclsid_identifier_seq", allocationSize=1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator="aclsid_identifier_seq")
    @Column(name = "id", insertable=false, updatable=false)
    private Integer id;



    @Column(name = "sid")
    private String sid;


    public Integer getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

我的问题是:在生成acl_entry之后,其字段“sid”是整数类型而不是预期的String。这导致生成后的密钥(sid)=(0)。

表acl_entry生成为:

mask integer,
  acl_object_identity integer,
  sid integer NOT NULL

感谢阅读。

1 个答案:

答案 0 :(得分:1)

而不是

@ManyToOne(fetch=FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "sid", nullable = false)
@ForeignKey(name = "id")
private AclSid aclSid;

尝试设置

@ManyToOne(fetch=FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "sid", nullable = false, referencedColumnName = "id")
private AclSid aclSid;

ManyToOneJoinColumn是JPA注释。 ForeignKey是一个特定于Hibernate的注释,我个人从未使用它,所以你可能不需要这样做:)