通过非PK列抛出Hibernate ManyToOne JOIN" int类型的错误值"

时间:2015-03-25 17:29:29

标签: java spring hibernate postgresql jpa

首先让我让我的场景清楚我正在使用hibernate 4.3,带有spring MVC的Postgresql 9.3,并且我使用JBOSS工具进行逆向工程。

每次我使用HQL或session.get()选择数据时(SQL查询工作正常) 引起:org.postgresql.util.PSQLException:int类型的错误值:demoemailaddr@gmail.com

实体类,
Applicant.java

@Entity
@Table(name = "applicant", schema = "public", uniqueConstraints = { @UniqueConstraint(columnNames = "user_id"), @UniqueConstraint(columnNames = "email"), @UniqueConstraint(columnNames = "registration_id") })
public class Applicant implements java.io.Serializable
{
    @Id
    @Column(name = "application_id", unique = true, nullable = false, length = 7)
    private String applicationId;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "email", unique = true, nullable = false)
    private Users usersByEmail;

     // setters and getters
}

和与上述类具有@ManytOne关系的Users类。

@Entity
@Table(name = "users", schema = "public", uniqueConstraints = { @UniqueConstraint(columnNames = "email"), @UniqueConstraint(columnNames = "application_id") })
public class Users implements java.io.Serializable
{
    @Id
    @Column(name = "user_id", unique = true, nullable = false)
    private int userId;

    @Column(name = "email", unique = true, nullable = false, length = 100)
    private String email;

}

现在检查架构结构

CREATE TABLE users
(
  email character varying(100) NOT NULL,
  user_id integer NOT NULL,
  CONSTRAINT users_pk PRIMARY KEY (user_id),
  CONSTRAINT unique_email UNIQUE (email)
)

 CREATE TABLE applicant
(
  application_id character(7) NOT NULL,
  email character varying(100) NOT NULL,
  CONSTRAINT users_email_fk FOREIGN KEY (email)
  REFERENCES users (email) MATCH SIMPLE
  ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT unique_applicant_email UNIQUE (email)
 )

[已编辑]我在具有唯一约束的用户表的电子邮件中使用加入列但不是PK(PK是user_id)
PS:我无法改变数据库模式结构,我没有权限

3 个答案:

答案 0 :(得分:2)

您需要将referencedColumnName属性添加到@ManyToOne关联:

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "email", referencedColumnName = "email", unique = true, nullable = false)
private Users usersByEmail;

答案 1 :(得分:1)

您将joinColumn定义为电子邮件,创建联接时将使用您的申请人表中的EMAIL列(即varchar保留电子邮件值)。但是连接是由@ID注释字段完成的,对于用户来说是userId并且它是数字的,所以你得到了例外。

Join始终是@ID,field,joincolumn只告诉它应该存储在join或local表中的哪个位置。

答案 2 :(得分:0)

您需要在数据库中定义主键(而不是多个唯一字段)或使用reveng.xml告诉hibernate工具什么是真正的主键。

您需要以下内容:

<table name="applicant"> 
 <primary-key>
  <key-column name="application_id"/>
 </primary-key>
</table>

您可以在以下文档中查看详细信息: http://docs.jboss.org/tools/latest/en/hibernatetools/html/reverseengineering.html