Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unique constraint not created in JPA

I have created the following entity bean, and specified two columns as being unique. Now my problem is that the table is created without the unique constraint, and no errors in the log. Does anyone have an idea?

@Entity
@Table(name = "cm_blockList", uniqueConstraints = @UniqueConstraint(columnNames = {"terminal", "blockType"}))
public class BlockList {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    @ManyToOne(cascade = CascadeType.PERSIST)
    @JoinColumn(name="terminal")
    private Terminal terminal;
    @Enumerated(EnumType.STRING)
    private BlockType blockType;
    private String regEx;
}
like image 947
homaxto Avatar asked May 31 '10 14:05

homaxto


People also ask

How do you make a unique field in JPA?

A unique constraint can be either a column constraint or a table constraint. At the table level, we can define unique constraints across multiple columns. JPA allows us to define unique constraints in our code using @Column(unique=true) and @UniqueConstraint.

How do you handle unique constraint exception in Java?

To handle unique constraint violations: Catch uniqueness exceptions thrown by the database at the lowest level possible — in the UnitOfWork class. Convert them into Result.

What is the use of @column annotation?

@Column annotation is used for Adding the column the name in the table of a particular MySQL database.

What is unique constraint with example?

The UNIQUE Constraint prevents two records from having identical values in a column. In the CUSTOMERS table, for example, you might want to prevent two or more people from having an identical age.


2 Answers

Well, I found another way to make the design. More because the design evolved than a work around.
I heard however from a colleague, that had had the same problem, that unique constraint only are created by hibernate (we are running JBoss 4.3) when the entire database is created. It will not work when you create a new table in an existing database.
So in persistence.xml it is necessary to set hibernate.hbm2ddl.auto to create-drop to make it work. I can not confirm this though.

like image 110
homaxto Avatar answered Nov 15 '22 09:11

homaxto


You dont have to drop everything, just drop this particular table you want to create unique index for

like image 23
Dima Avatar answered Nov 15 '22 09:11

Dima