Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I name my constraints with JPA?

When I use the maven-hibernate3-plugin (aka hbm2ddl) to generate my database schema, it creates many database constraints with terrifically hard-to-remember constraint names like FK7770538AEE7BC70 .

Is there any way to provide a more useful name such as FOO_FK_BAR_ID ?

If so, it would make it a tad easier to track down issues in the log files and other places where the violation doesn't tell you anything other than the constraint name.

like image 394
HDave Avatar asked Jul 02 '10 21:07

HDave


People also ask

How do you define unique constraints on email field of an entity class in JPA?

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.

Can JPA entity implements interface?

No, not possible with JPA or Hibernate. It does seem strange, when coding in the Java language which allows for attributes to be interfaces, that a persistence standard like JPA, intended for Java, does not support persisting attributes that are interfaces.

Can I define multiple unique constraints on a table?

Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for a column or set of columns. A PRIMARY KEY constraint automatically has a UNIQUE constraint. However, you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.

Does JPA create database?

For this reason, the ability to have JPA frameworks -- such as EclipseLink or Hibernate -- create tables and databases as they bootstrap is built right into the specification. These database creation facilities are also a great way to validate a newly set up Hibernate and JPA development environment.


1 Answers

As of JPA 2.1 it is possible to give a name to foreign key. E.g.

@ManyToOne @JoinColumn(foreignKey=@ForeignKey(name="MY_FANCY_FK_NAME")) Account account; 

Just make sure it is used within @JoinColumn. JavaDoc: https://docs.oracle.com/javaee/7/api/javax/persistence/ForeignKey.html#name%28%29

like image 144
Piohen Avatar answered Oct 08 '22 20:10

Piohen