Hibernate:@UniqueConstraint和@ManyToOne字段?

时间:2010-06-18 04:29:13

标签: hibernate groovy

使用以下代码:

@Entity 
@Table(uniqueConstraints=[@UniqueConstraint(columnNames=["account","name"])])
class Friend {
  @Id @GeneratedValue(strategy=GenerationType.AUTO)
  public Long id
  @ManyToOne
  public Account account
  public String href
  public String name
}

我收到以下错误:

org.hibernate.AnnotationException: Unable to create unique key constraint (account, name) on table Friend: account not found

这似乎与@ManyToOne约束有关,我想这实际上创建了一个单独的UniqueConstraint ???

无论如何,如果我把它拿出来,就没有关于UniqueConstraint的抱怨,但还有另一个错误让我相信它必须留在。

org.hibernate.MappingException: Could not determine type for: com.mksoft.fbautomate.domain.Account, at table: Friend, for columns: [org.hibernate.mapping.Column(account)]

任何提示我如何创建这样一个所需的约束(即,帐户和名称的每个组合只出现一次???)

谢谢!

米莎

2 个答案:

答案 0 :(得分:12)

解决方案:

@Entity 
@Table(uniqueConstraints=[@UniqueConstraint(columnNames=["myaccountcolum","name"])])
class Friend {
  @Id @GeneratedValue(strategy=GenerationType.AUTO)
  public Long id
  @ManyToOne
  @JoinColumn(name="myaccountcolum")
  public Account account
  public String href
  public String name
}

说明: 生成的表中@ManyToOne的列名可能类似于account_id而不是account。 @UniqueConstraint需要确切的列名,而不是您在类中使用的名称。要确保它正常工作,请使用@JoinColumn为此列指定一个特定名称,并确保在UniqueConstraint中使用相同的名称。

答案 1 :(得分:0)

我使用@JoinColumn,没关系,但是我正在运行liquibase脚本“ diffAll”,并且这同时创建了mysql和oracle的.yaml文件。

列名称在mysql中为“ profile”,在oracle数据库中为“ profile_id”。

当我写“ @JoinColumn(name =” profile“)时,尝试删除” profile_id“列并为oracle db添加” profile“列。

我如何为多个数据库创建@UniqConstraint。

谢谢。 最好的问候。