Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate - Constraint Name

Does anybody knows how to set the constraint name for primary key (PK_[name]) ,check (CK_[Name]),Default [DF_[Name]], Foreign Key (Fk_[Name]) ,Unique .. by using Annotations or xml config for example i want that Table ::::

CREATE TABLE ACCOUNT (
[ID] INT NOT NULL IDENTITY(1,1),
[USERNAME] VARCHAR(50) NOT NULL,
[PASSWORD] VARCHAR(50) NOT NULL,
[EMAIL] VARCHAR(100) NOT NULL,
[GENDER] INT NOT NULL ,
[ADDRESS] INT,
[AGE] INT CONSTRAINT DF_tblAccount_Age DEFAULT 0,
CONSTRAINT PK_tblAccount_ID PRIMARY KEY([ID]),
CONSTRAINT UQ_tblAccount_Address UNIQUE(ADDRESS),
CONSTRAINT FK_tblAccount_Gender FOREIGN KEY([GENDER]) REFERENCES GENDER([ID]),
CONSTRAINT FK_tblAccount_Address FOREIGN KEY([ADDRESS]) REFERENCES ADDRESS([ID]) ON DELETE SET NULL,
CONSTRAINT CK_tblAccount_Age CHECK ([AGE] > 0 AND [AGE] <100)
)

Translate it into annotation class or [name].hbm.xml , does Hibernate support to use constraint name or i must alter the tables every time i create a new class ... I searched and i find 0 results about constraint names !!

Annotation Class Example :::

@Id @GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="ID")
// -->>Add Primary Key constraint Name Here !! ???
private int id;

@Column(name="Name")
private String name;

@Column(name="Surname")
private String surname;

@Column(name="age")
// -->>Add Check constraint Name Here !! ???
private String age;

@OneToOne(cascade={CascadeType.ALL},fetch=FetchType.LAZY)
@OnDelete(action=OnDeleteAction.CASCADE)
@JoinColumn(name="Address" , referencedColumnName="id",nullable=false)
// -->>Add Foreign Key constraint Name Here !! ???
private Address address;
like image 921
kkafkas Avatar asked Aug 22 '15 20:08

kkafkas


1 Answers

In JPA, you can do this at class level, using @Table annotation properties, where you specify constraints names. For primary key id mapped to column id:

@Table(uniqueConstraints = @UniqueConstraint(columnNames = "ID", name = "PERSONS_PK_CONSTRAINT"))
like image 172
OndroMih Avatar answered Oct 23 '22 23:10

OndroMih