Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate: @UniqueConstraint with @ManyToOne field?

Using the following code:

@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
}

I get the following error:

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

It seems this has to do with the @ManyToOne constraint, which I imagine actually creates a separate UniqueConstraint???

In any case, if I take this out, there is no complaint about the UniqueConstraint, but there is another error which makes me believe it must be left in.

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

Any hints how I can create such a desired constraint (i.e., that each combination of account and name occurs only once???)

Thank you!

Misha

like image 962
Миша Кошелев Avatar asked Jun 18 '10 04:06

Миша Кошелев


1 Answers

The solution:

@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
}

Explanation: The column name for the @ManyToOne in the generated table will probably be something like account_id instead of account. The @UniqueConstraint expects the exact column name, not the name you use in your class. To make sure it just works, give this column a specific name with @JoinColumn and make sure the same name is used in your UniqueConstraint.

like image 90
Peter Avatar answered Nov 11 '22 21:11

Peter