'Unable to create unique key constraint not found

I have the following entity:

@Entity
@Table(name = "campaign_content", uniqueConstraints = @UniqueConstraint(columnNames = { "campaignContentId", "campaignId", "fieldTag" }))    
public class CampaignContent implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @Column(name = "campaign_content_id")
    private Integer campaignContentId;

    @Column(name = "field_content")
    private String fieldContent;

    @Column(name = "campaign_id")
    private Integer campaignId;

    @Column(name = "field_tag")
    private String fieldTag;

With getter and setter.

However I get:

caused by: org.hibernate.AnnotationException: Unable to create unique key constraint (campaignContentId, campaignId, fieldTag) on table campaign_content: campaignContentId, campaignId, fieldTag not found

What is wrong?



Solution 1:[1]

The name of the column is campaign_content_id, not campaignContentId. Same thing for the other columns, of course. The columnNames attribute expects an array of ... column names. Not an array of Java field or property names.

Solution 2:[2]

In my case this code works, one physical table field name and one entity object member field name.

@Table(uniqueConstraints={@UniqueConstraint(columnNames = {"account_id" , "measureDate"})})

but this code doesn't work at all with same exception.

@Table(uniqueConstraints={@UniqueConstraint(columnNames = {"account_id" , "measure_date"})})

Someone reported this bug to hibernate. Check this. https://forum.hibernate.org/viewtopic.php?f=9&t=986581&view=next

I use

  • spring boot
  • spring data
  • mysql

Solution 3:[3]

If any of constrained column anotated with @Column(name="..."): You need add @Column(name = "...") to another constraining columns too.

Solution 4:[4]

my problem solved by this Your table definition must look like this @Table(name = "campaign_content", uniqueConstraints = @UniqueConstraint(columnNames = { "campaign_content_id", "campaign_id", "field_tag" }))

Solution 5:[5]

For anyone getting this error while using Kotlin, my issue was caused by using @Column instead of @get:Column on a var. Doh!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 JB Nizet
Solution 2 Dennis Kim
Solution 3 Dumitru Preguza
Solution 4 Vahap Gencdal
Solution 5 GlenPeterson