Suppose I am having 'subject' table
CREATE TABLE subject (id int PRIMARY KEY, name VARCHAR(255) **UNIQUE**)
and associated Mapped Object,
@Entity @Table(name="subject") public class SubjectDO { @Id @Column(name="id") int id; @Column(name="name", unique=true) String name; ... // Getter-Setter methods }
When I try to save object having duplicate 'name' with and without 'unique=true' defined, I am getting similar behavior (same exception.) And it is obvious that JPA implementation can't really do anything unless reaching out to DB for checking.
What is the real use case for it?
(I am assuming here, unique constraint is defined at Database level too.)
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. These annotations are interpreted by the schema generation process, creating constraints automatically.
@Column. Let's start with the @Column annotation. It is an optional annotation that enables you to customize the mapping between the entity attribute and the database column.
In this article, we will discuss how to change the column name in the Spring project using JPA. @Column annotation is used for Adding the column the name in the table of a particular MySQL database. Syntax: @Column(name=”DESC”, nullable=false, length=512)
columnDefinition definition: The SQL fragment that is used when generating the DDL for the column. columnDefinition default: Generated SQL to create a column of the inferred type.
unique
in @Column
is used only if you let your JPA provider create the database for you - it will create the unique constraint on the specified column. But if you already have the database, or you alter it once created, then unique
doesn't have any effect.
unique=true
in @Column
annotation will be used only in DDL generation
, it doesn't have any impact during runtime. The actual uniqueness checks happens in the database
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With