5

I am planning to integrate ORM in my project, so i used eclipse's JPA project to generate entity classes out of old databases. In total 168 entity classes where generated and it's fine. But in some constraints like nullable, unique are not automatically generating.

For example I need something like this :-

@Column(name="USER_NAME",unique = true)
private String userName;

but after auto generating entities there is no unique constraint in code. How can I achieve this simply?

any suggestions will be useful.

Aleksandr M
  • 24,264
  • 12
  • 69
  • 143
  • If you can't get this working using Eclipse's JPA project you might like to consider trying the reverse engineer from Hibernate / JBoss Tools. There's a couple of articles online that take you through how to do this step by step e.g. https://www.mkyong.com/hibernate/how-to-generate-code-with-hibernate-tools/ – Steve Chambers Sep 25 '17 at 08:34
  • The `unique` property of the `@Column` annotation is only used in DDL generation i.e. in cases when you are generating the database schema from your mapped JPA entities. It has absolutely no effect on the code. As you are going the opposite way then there is little point in having it: https://stackoverflow.com/questions/30460596/jpa-column-unique-true-what-is-really-point-of-having-unique-attribute – Alan Hay Sep 28 '17 at 16:15

4 Answers4

2

Check your JPA version in your eclipse, if you found lowest versions update it to latest one. Latest JPA creates all the constraints which we defined in database table.
hope this helps you.

Find Latest JPA on New "JPA project screen"

Community
  • 1
  • 1
AdamIJK
  • 615
  • 2
  • 12
  • 22
1

@Unique represents a unique index that prevents duplicate values in the indexed field. A PersistenceException is thrown on commit (or flush) if different entities have the same value in a unique field (similar to how primary keys behave). In your exemple :

@Unique
@Column(name="USER_NAME")
private String userName;
F0XS
  • 1,271
  • 3
  • 15
  • 19
1

The unique constraint will only be created if you create the table. If the table already exists only new columns will be added during DDL updates. So you have to either drop the table manually or set the value for javax.persistence.schema-generation.database.action to drop-and-create.

fhossfel
  • 2,041
  • 16
  • 24
1

YOu have to use the Hibernate Tools from Jboss, which enable you to do a better reverse engineering.

http://hibernate.org/tools/

There are a bunch of tutorials outside which are explaining how to use the hibernate tools.

cilap
  • 2,215
  • 1
  • 25
  • 51