John Henckel
John Henckel

Reputation: 11397

How to put unique constraint on a foreign key in JPA

Using JPA (hibernate, spring tool suite) I'm trying to make a uniqueness constraint on two table columns, one of which is a foreign key. I can't figure out the syntax.

I tried.

@Table(uniqueConstraints={@UniqueConstraint(columnNames = {"company.companyId" , "state"})})
@Entity
public class Branch {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int branchId;
    @ManyToOne(optional = false)
    private Company company;
    @Column
    int state;
}

but I get error:

database column 'company.companyId' not found. Make sure that you use the correct column name which depends on the naming strategy in use (it may not be the same as the property name in the entity, especially for relational types)

so I tried several other ways, such as "company_id" and "company_company_id" and "company_companyId". None of them work.

Upvotes: 3

Views: 3458

Answers (1)

John Henckel
John Henckel

Reputation: 11397

I tried "company_company_id" and now it works.

It is hard to notice that constraint exists. I am using MSSMS and it doesn't show up in the "Constraints" folder. You have to "script table to create" in order to see the constraints properly. HTH

Upvotes: 3

Related Questions