Introduction to Hibernate Annotations

January 8, 2009

During the process of upgrading hibernate settings to use annotations, the following steps were taken

1) Adding the addtional annotation related jar files:-

* hibernate-annotations.jar
* ejb3-persistence.jar

2) Adding relevant annotations, and removing the old *.hbm.xml files, ie

@MappedSuperclass - a
@Entity - b
@Table(name="FOO_NAME") - c
@Transient - d
@Id - e
@Column( - f
name="clmnName" - f.a
nullable=true, - f.b
unique=false, - f.c
length=255, - f.d
precision=256, - f.e
scale=2 - f.f
)
@Version - g
@ManyToOne - h
@JoinColumn( name="DATE_MODIFIED" )     - i
@Temporal( TemporalType.TIMESTAMP )     - j

———–
Index
———–

a – for abstract entities that are used for extending entities
b – for persistent entities
c – optionally for specifying the table name, else default is to use entity name
d – for non-persistent properties
e – for the id property
f – for ordinary properties that need to be mapped to the relevant table columns… please remember not required if only the default values are required for the following
f.a – column name, not required if it is the same as the field property name
f.b – default value of true
f.c – default value of false
f.d – default value of 255
f.e – used for decimals numbers
f.f – ie the sql equivalent NUMBERIC( percision, scale )
g – for adding optimistic locking capability to an entity
h – for <many-to-one name=”…” column=”…” … /> where an entity is used (within an entity) instead of primary data (ie int). Please note that the default fetching strategy for one-to-one and many-to-one is eager and that the strategy for one-to-many and many-to-many is lazy
i – used in cases where the entity (within the entity) is stored in a seperate table and a join is required to link the two. If no name is specified the default behaviour is that a join column(s) will be created in the owner table and its name will be the concatenation of the name of the property in the owner side, _ (underscore), and the name of the primary key column(s) in the owned side.
j – used for date and time

———————————
ALSO PLEASE NOTE:
———————————

i- annotations only need to be applied to getXXX and relevant isXXX methods… the rest (ie methods such as hasCode, toString) will be ignored even if marked with @Transient

ii- annotations can be marked on top of field properties or methods properties… but not both at the same time

iii- id properties are either assigned by the application or generated by the database… for application generated simply specifiy @Id… but for database generated preferably use @Id @GeneratedValue(strategy=GenerationType.AUTO)

iv – if specifying annotations (at the method level) for an entity that has certain (ie private) fields used only for internal purposes (ie NULL_VALUE = -1) that do not require persistance and as a result no relevent getters, please create a getter and label with @Transient

v – also please note that there is a difference between java annotations (ie @Override), spring annotations and hibernate annotations (used above), all three maybe used independently

3) Modifying the Spring & Hibernate Configurations

i- create a seperate hibernate.cfg.xml file and place all the settings and mappings inside

==========================================================================================
filename: hibernate.cfg.xml
==========================================================================================

<!DOCTYPE hibernate-configuration SYSTEM "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>

<!-- hibernate settings -->
<property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="connection.isolation">2</property><!-- READ_COMMITTED -->
<property name="show_sql">false</property>
<property name="use_sql_comments">false</property>
<property name="format_sql">true</property>

<!-- entity mapping files for old unconverted xml files to still work -->
<mapping resource="com/foo/entityold/model/EntityOld.hbm.xml"/>
...

<!-- annotated entities that don't require the respective hbm.xml files anymore -->
<mapping class="com.foo.entitynew.model.EntityNew"/>

</session-factory>

</hibernate-configuration>

ii- modify the spring context file

==========================================================================================
foo-context.xml – Before Annotations
==========================================================================================

<!-- session factory -->
<bean id="org.hibernate.SessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

<!-- data source -->
<property name="dataSource" ref="dataSource"/>

<!-- mapping resources -->
<property name="mappingResources">
<list>
<value>com/foo/entityold/model/EntityOld.hbm.xml</value>
...
</list>
</property>

<!-- hibernate properties -->
<property name="hibernateProperties">
<props>
<!-- sql dialect -->
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>

<!-- Set the JDBC transaction isolation level... 2 means TRANSACTION_REPEATABLE_READ - a constant indicating that dirty reads and non-repeatable reads are prevented; phantom reads can occur. -->
<prop key="hibernate.connection.isolation">2</prop>

<!--
Write all SQL statements to console. This is an alternative to setting the log category org.hibernate.SQL  to debug.
but please note that this is usually not necessary for production since the stack trace which also includes the particular SQL statement suffices
-->
<prop key="hibernate.show_sql">false</prop>

<!-- If turned on, Hibernate will generate comments inside the SQL, for easier debugging -->
<prop key="hibernate.use_sql_comments">false</prop>

<!-- Pretty print the SQL in the log and console -->
<prop key="hibernate.format_sql">false</prop>
</props>
</property>
</bean>

==========================================================================================
foo-context.xml – After Annotations
==========================================================================================

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

<!-- data source -->
<property name="dataSource" ref="dataSource"/>

<!-- mapping resources and hibernate properties moved to hibernate.cfg.xml -->

<!-- new additions (for annotations to be enabled) -->
<property name="configLocation" value="classpath:hibernate.cfg.xml"/>
<property name="configurationClass" value="org.hibernate.cfg.AnnotationConfiguration"/>

</bean>

Entry Filed under: Hibernate, Java, Spring. Tags: , , .

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


Recent Posts

Recent Comments

Categories

Top Posts

Links

Blog Stats

Meta