Mahdi Kolivand
Mahdi Kolivand

Reputation: 11

Define unique key in hibernate

I have three models in my project.

 public class Bank{
   private int id;
   private String title;
   ....
}
public class Branch{
   private Bank bank;
   private int id;
   private String title;
   ....
}
public class Account{
   private Branch branch;
   private int id;
   private String accountNumber;
   private String title;
   ....
}

how to define the accountNumber and id Of bank combined as a unique key?

Upvotes: 0

Views: 1036

Answers (1)

veljkost
veljkost

Reputation: 1932

For composite unique key, you can use uniqueConstraints property of @Table annotation:

@Table(
    name = "account",
    uniqueConstraints = {@UniqueConstraint(columnNames = {"accountNumber", "bank"})}
)
public class Account{
    private Branch branch;
    private int id;
    private String accountNumber;
    private String title;
    @ManyToOne
    private Bank bank;
}

Upvotes: 1

Related Questions