Wednesday, May 7, 2014

Hibernate/persistence annotations

Some useful annotations when using
hibernate.hbm2ddl.auto to update | create | create-drop
If hbm2ddl.auto is set to update it will not change type of field!
     postgres:  ALTER TABLE users ALTER COLUMN role TYPE varchar(16);

javax.persistence.Lob with/without org.hibernate.annotations.Type

Using postgres and omitting Type for text lobs will cause numbers in database tables. 
Like operator will not work!
Solution:
@Lob
@Type(type = "org.hibernate.type.TextType")

If there was version without @Type and you want to update/migrate, please share your expirience.
(If you add @Type, old records will be read as plain strings.)
// This was tested with hibernate 3.6.10. and 5.1.0

org.hibernate.annotations.ForeignKey

Very useful for not having generated names as foreign keys.

In JPA 2.1 you can use javax.persistence.ForeignKey
@JoinColumn(foreignKey = @ForeignKey(name = "FK_ORDER_CUSTOMER"))

javax.persistence.Enumerated(javax.persistence.EnumType.STRING)

When using enum, store it in db as string, not a number

javax.persistence.Id with javax.persistence.Column

This combination will cause a lot of problems with hsqldb (column annotation is same like Id constraint). Postgres will not complain.
@Id
@Column(name = "ID", nullable = false, unique = true)

Solution:
remove nullable and unique


Tested on hsqldb 2.3.2 (as in memory) and postgres 9.2/9.3

Ref:

No comments:

Post a Comment