Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
830 views
in Technique[技术] by (71.8m points)

mysql - @Column(unique=true) does not seem to work

Even though I set the attribute to be @Column(unique=true), I still insert a duplicate entry.

@Entity
public class Customer {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(unique=true )
    private String name;

    ...
}

I set the name using regular EL in JSF. I did not create table using JPA

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The unique=true element of the Column annotation and / or the UniqueConstraint annotation that can be used at the table level are used to specify that a unique constraint is to be included in the generated DDL.

In other words, they don't do anything during the runtime, the verification is left to the database (which makes sense as unicity can't be tested at the Java level reliably1) and if for whatever reason you don't have the corresponding constraint(s) defined at the database level, nothing will happen.

Add the constraint manually:

ALTER TABLE Customer ADD CONSTRAINT customer_name_unq UNIQUE (name);

See also

1 Unless you acquire a table lock (ouch!), you can't check for unicity with a SQL query in a concurrent environment.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...