Hibernate: Difference between revisions

From Wiki RB4
 
(36 intermediate revisions by 2 users not shown)
Line 5: Line 5:
In order to provide a clean POJO programming model, Hibernate hides itself inside of your POJO by using either its own implementation of the JDK collections or by using a CGLIB proxy to surround an object reference, depending on the type of association it is managing. Since object graphs can be quite large, and in some cases infinite, it is mandatory to draw the line somewhere when loading an object and claim these associations as lazy. This deferral means that at some later point, it may be necessary to fetch the associated objects from the database when this line is crossed.
In order to provide a clean POJO programming model, Hibernate hides itself inside of your POJO by using either its own implementation of the JDK collections or by using a CGLIB proxy to surround an object reference, depending on the type of association it is managing. Since object graphs can be quite large, and in some cases infinite, it is mandatory to draw the line somewhere when loading an object and claim these associations as lazy. This deferral means that at some later point, it may be necessary to fetch the associated objects from the database when this line is crossed.


===Startup===
===Configuration and Startup===
If there is a file named import.sql e.g. in the root directory of an [[JEE#beans_jar_file|EJB jar file]] and hibernate.hbm2ddl.auto in the [[JavaJEEJPA#persistence.xml|persistence.xml]] the file is imported at startup of a JBoss application server.
If there is a file named import.sql e.g. in the root directory of an [[JEE#beans_jar_file|EJB jar file]] and hibernate.hbm2ddl.auto in the [[JavaJEEJPA#persistence.xml|persistence.xml]] the file is imported at startup of a JBoss application server.
====SessionFactory====
A '''session factory''' represents a particular logical data-store configuration (s.[[Hibernate#hibernate.cfg.xml|hibernate.cfg.xml]]). The [[JavaJEEJPA|JPA]] aquivalent of the session factory is the entity manager factory, the aquivalent of the session factory configuration is the [[JavaJEEJPA#Persistance_Unit|persistence unit]]. In most hibernate applications a SessionFactory should be instantiated once during application initialization. There are advanced options to store the factory like JNDI. A simple and pragmatic approach is to use a static global variable and static initialization (s. example uweheuer application server.HibernateUtil).
====Session====
A '''session''' is a particular unit of work, that means a set of data access operations. The aquivalent in JPA is the [[JavaJEEJPA#Entity_Manager|entity manager]].
====Startup====
A typical example of a Hibernate startup procedure:
SessionFactory sf = new Configuration().configure().buildSessionFactory();
or
uweheuerSessionFactory = new AnnotationConfiguration().configure("uweheuer.hibernate.cfg.xml").buildSessionFactory();
When <code>new configuration()</code> is called Hibernate searches for a file named <code>hibernate.properties</code> in the root of the classpath. If found they are loaded into the configuration object. When <code>configure()</code> is called, Hibernate searches for a file named <code>hibernate.cfg.xml</code>. Bei Web Application ist die Ablage unter \WEB-INF\classes. Its possible to have more than one for multiple databases, one for each database (e.g. project 'uweheuer', files uweheuer.hibernate.cfg.xml and uweswiki.hibernate.cfg.xml).
====hibernate.cfg.xml====
<hibernate-configuration>
  <session-factory>
  <property name="hbm2ddl.auto">[update|create]</property>
Update scheint die beste Einstellung, Änderungen an der Klasse bewirken beim Initialisieren der Anwendung (Reload for a web application) eine Änderung in der zugehörigen Tabelle. Daten gehen nicht verloren. Allerdings werden z.B. neue java long members in der DB mit NULL initialisiert. Dies führt in der Regel zu einer Exception beim Laden.
==Libraries==
* ejb3-persistance.jar (javax.persistance.*)
* hibernate3.jar (org.hibernate.*)


==Associations==
==Associations==
Line 33: Line 62:
==Patterns==
==Patterns==


====Ordererd unidirectional OneToMany Association====
===Ordererd unidirectional OneToMany Association===
Class A has many Bs, B has one A, but doesn't know about it:
Class A has many Bs, B has one A, but doesn't know about it:


Line 44: Line 73:
Merkwürdigerweise liegt dies eine zusätzliche Mapping-Tabelle namens A_B an, die man eigentlich vermeiden könnte, aber es funktioniert. Es muss immer das Objekt der Klasse A gespeichert werden. Auf der Seite von B steht nich
Merkwürdigerweise liegt dies eine zusätzliche Mapping-Tabelle namens A_B an, die man eigentlich vermeiden könnte, aber es funktioniert. Es muss immer das Objekt der Klasse A gespeichert werden. Auf der Seite von B steht nich


====Non Ordered bedirectional OneToMany Association====
===Non Ordered bedirectional OneToMany Association===
Class A has many Bs, B has one A:
Class A has many Bs, B has one A:
   
   
Line 60: Line 89:
'''mappedBy''' signals that the associations is managed by the member of B (foreign key of table of B).
'''mappedBy''' signals that the associations is managed by the member of B (foreign key of table of B).


====Ordered biderectional OneToMany Association====
===Ordered biderectional OneToMany Association===


in the one class:
in the one class:
Line 75: Line 104:
s. also compare http://forum.hibernate.org/viewtopic.php?t=974127
s. also compare http://forum.hibernate.org/viewtopic.php?t=974127


====Ordered biderectional ZeroToMany Association====
===Ordered biderectional ZeroToMany Association===
in the zero or one class:
in the zero or one class:
  @OneToMany(cascade = {CascadeType.ALL})
  @OneToMany(cascade = {CascadeType.ALL})
Line 94: Line 123:
#create the Hibernate configuration file [[Hibernate#hibernate.cfg.xml|hibernate.cfg.xml]]
#create the Hibernate configuration file [[Hibernate#hibernate.cfg.xml|hibernate.cfg.xml]]
#use the persistance classes
#use the persistance classes
===Building an Application===
* add libs
* reengineer db to java classes or create java classes
* create Util class for session e.g. HibernateUtil.java in project 'ballaballa_hiber'


===Designing the domain model===
===Designing the domain model===
Line 110: Line 144:
For a many-end association end the propertie must be of an interface type like java.util.set or java.util.List.
For a many-end association end the propertie must be of an interface type like java.util.set or java.util.List.


===Hibernate Infrastructure===
====SessionFactory====
In most hibernate applications SessionFactory should be instantiated once during application initialization (s. example uweheuer application server.HibernateUtil).




===Reverse Engineer a Database===
see [[Eclipse#Reveres_Engineer_a_database_with_Hibernate|Eclipse]]


===Reverse Engineer a Database===
 
For reverse engineering perform the following steps:
====Adding persistent class members====
#create a Hibernate Console Configuration via ''File->New->Other->Hibernate->Hibernate Console Configuration'' (edit it by changing to the perspective Hibernate) and double click in the Hibernate Configurations view
* add it to the class
#specify Database Connection, Property file, Configuration file [[Hibernate#ConfigurationFiles|Hibernate configuration file]]. The rest seems to be unneccessary.
* rebuild and reload application
#''Run->Hibernate Code Generation...->Open Hibernate Code Generation Dialog...''
* the [[Hibernate#hibernate.cfg.xml|hibernate config file]] manages the db, if set correspondingly
#Create a new Code Generation Configuration or edit an existing
##specify the existing output directory
##specify via the reveng.xml setup dialog the tables for reverse engineering
##select the exporters
##press ''Run'' or later ''Run->Hibernate Code Generation->&lt;Code Generation Configuration>''


===Storing new or detached objects===
===Storing new or detached objects===
Line 138: Line 166:


====Log4j====
====Log4j====
In JBoss Logging configuration is done [[JBoss#Logging|here]].
special entries in log4j.properties:
special entries in log4j.properties:
  ### log the sql inclusive values
  ### log the sql inclusive values
Line 149: Line 179:
  <property name="use_sql_comments">true</property>
  <property name="use_sql_comments">true</property>
then all SQL statements are written to stdout.
then all SQL statements are written to stdout.
==Hibernate Configuration==
===Location and Startup===
Bei Web Application ist die Ablage unter \WEB-INF\classes. It is read during startup of the web application.
===Configuration Files===
The name of the configuration file is normally '''hibernate.cfg.xml'''. Its possible to have more than one for multiple databases, one for each database (e.g. project 'uweheuer', files uweheuer.hibernate.cfg.xml and uweswiki.hibernate.cfg.xml). Normally the configuration files are read during startup by e.g. project 'uweheuer' in HibernateUtil.java:
uweheuerSessionFactory = new AnnotationConfiguration().configure("uweheuer.hibernate.cfg.xml").buildSessionFactory();
<hibernate-configuration>
  <session-factory>
  <property name="hbm2ddl.auto">[update|create]</property>
update scheint die beste Einstellung, Änderungen an der Klasse bewirken beim Initialisieren der Anwendung (Reload for a web application) eine Änderung in der zugehörigen Tabelle. Daten gehen nicht verloren.


==Literatur==
==Literatur==
#Java Persistance with Hibernate
#Java Persistance with Hibernate
#[http://www.galileocomputing.de/artikel/gp/artikelID-328?GalileoSession=81704626A3.e1-.ow1s#abschnitt0 Online-Buch zu Annotations]
#[http://www.galileocomputing.de/artikel/gp/artikelID-328?GalileoSession=81704626A3.e1-.ow1s#abschnitt0 Online-Buch zu Annotations]

Latest revision as of 19:54, 27 November 2011

Introduction[edit]

Hibernate is an open source object/relational mapping tool for Java. Hibernate lets you develop persistent classes following common Java idiom - including association, inheritance, polymorphism, composition and the Java collections framework.

Hibernate makes use of persistent objects commonly called as POJO (POJO = "Plain Old Java Object".) along with XML mapping documents for persisting objects to the database layer. The term POJO refers to a normal Java objects that does not serve any other special role or implement any special interfaces of any of the Java frameworks (EJB, JDBC, DAO, JDO, etc...). Hibernate uses runtime reflection to determine the persistent properties of a class. The objects to be persisted are defined in a mapping document, which serves to describe the persistent fields and associations, as well as any subclasses or proxies of the persistent object. The mapping documents are compiled at application startup time and provide the framework with necessary information for a class. Additionally, they are used in support operations, such as generating the database schema or creating stub Java source files. In order to provide a clean POJO programming model, Hibernate hides itself inside of your POJO by using either its own implementation of the JDK collections or by using a CGLIB proxy to surround an object reference, depending on the type of association it is managing. Since object graphs can be quite large, and in some cases infinite, it is mandatory to draw the line somewhere when loading an object and claim these associations as lazy. This deferral means that at some later point, it may be necessary to fetch the associated objects from the database when this line is crossed.

Configuration and Startup[edit]

If there is a file named import.sql e.g. in the root directory of an EJB jar file and hibernate.hbm2ddl.auto in the persistence.xml the file is imported at startup of a JBoss application server.

SessionFactory[edit]

A session factory represents a particular logical data-store configuration (s.hibernate.cfg.xml). The JPA aquivalent of the session factory is the entity manager factory, the aquivalent of the session factory configuration is the persistence unit. In most hibernate applications a SessionFactory should be instantiated once during application initialization. There are advanced options to store the factory like JNDI. A simple and pragmatic approach is to use a static global variable and static initialization (s. example uweheuer application server.HibernateUtil).

Session[edit]

A session is a particular unit of work, that means a set of data access operations. The aquivalent in JPA is the entity manager.

Startup[edit]

A typical example of a Hibernate startup procedure:

SessionFactory sf = new Configuration().configure().buildSessionFactory();

or

uweheuerSessionFactory = new AnnotationConfiguration().configure("uweheuer.hibernate.cfg.xml").buildSessionFactory();

When new configuration() is called Hibernate searches for a file named hibernate.properties in the root of the classpath. If found they are loaded into the configuration object. When configure() is called, Hibernate searches for a file named hibernate.cfg.xml. Bei Web Application ist die Ablage unter \WEB-INF\classes. Its possible to have more than one for multiple databases, one for each database (e.g. project 'uweheuer', files uweheuer.hibernate.cfg.xml and uweswiki.hibernate.cfg.xml).

hibernate.cfg.xml[edit]

<hibernate-configuration>
 <session-factory>
  <property name="hbm2ddl.auto">[update|create]</property>

Update scheint die beste Einstellung, Änderungen an der Klasse bewirken beim Initialisieren der Anwendung (Reload for a web application) eine Änderung in der zugehörigen Tabelle. Daten gehen nicht verloren. Allerdings werden z.B. neue java long members in der DB mit NULL initialisiert. Dies führt in der Regel zu einer Exception beim Laden.

Libraries[edit]

  • ejb3-persistance.jar (javax.persistance.*)
  • hibernate3.jar (org.hibernate.*)

Associations[edit]

EJB CMP 2.0 also manages associations/relationships (CMR). Associations in CMP are inherently bidirectional, a change to one side is instantly reflected at the other side. Hibernate don't implement managed associations.

Annotations[edit]

In addition to the standard JPA annotation set, Hibernate has its own 'vendor' annotations to support additional mapping features and association types that aren’t part of the JPA specificationTo use annotations the java file has to (s. JPA Annotations)

import javax.persistance.*;

and the configuration file has to list all annotated classes like

 <mapping class="<Package>.<Classname>" />

Length[edit]

@org.hibernate.validator.Length(min=<Number>, max=<Number>)
<attribute declaration>

for length validation.

NotNull[edit]

@org.hibernate.validator.NotNull
<attribute declaration>

for validation.

Patterns[edit]

Ordererd unidirectional OneToMany Association[edit]

Class A has many Bs, B has one A, but doesn't know about it:

class A
{
  @OneToMany([<fetching>|<cascading>])
  @IndexColumn(name = <name>) // list order
  private List<B> bs = new ArrayList<B>;

Merkwürdigerweise liegt dies eine zusätzliche Mapping-Tabelle namens A_B an, die man eigentlich vermeiden könnte, aber es funktioniert. Es muss immer das Objekt der Klasse A gespeichert werden. Auf der Seite von B steht nich

Non Ordered bedirectional OneToMany Association[edit]

Class A has many Bs, B has one A:

class A
{
  @OneToMany(mappedBy = "<MemberOfB>")
  private <Collection><B> bs = new <ConcreteCollection>();
  
  public void addB(B b)
  {
    b.setA(this); // neccessary, that the relationship can be handled only by the other end
    bs.add(b);
  }

mappedBy signals that the associations is managed by the member of B (foreign key of table of B).

Ordered biderectional OneToMany Association[edit]

in the one class:

@OneToMany(cascade = {CascadeType.ALL})	
@JoinColumn(name = "menu_id", nullable = false)
@IndexColumn(name = "menu_list_position")	// list order      
private List<Urlx> urls = new ArrayList<Urlx>()

in the many class:

@ManyToOne
@JoinColumn(name = "menu_id", nullable = false, updatable = false, insertable = false)
private Menux  menu;

s. also compare http://forum.hibernate.org/viewtopic.php?t=974127

Ordered biderectional ZeroToMany Association[edit]

in the zero or one class:

@OneToMany(cascade = {CascadeType.ALL})	
@JoinColumn(name = "parent_id", nullable = true) // nullable is true
@IndexColumn(name = "parent_list_position")	 // list order            
private List<Menux> menus = new ArrayList<Menux>();

in the many class:

@ManyToOne
@JoinColumn(name = "parent_id", nullable = true, updatable = false, insertable = false)
private Menux  parent;

Development Process[edit]

  1. copy the following libs to the application lib directory (hibernate core, hibernate annotations, hibernate validation):
    ant-antlr-1.6.5.jar
    asm-attrs.jar
    asm.jar
    cglib-2.1.3.jar
    commons-collections-2.1.1.jar
    commons-logging-1.0.4.jar
    dom4j-1.6.1.jar
    ejb3-persistence.jar
    hibernate-annotations.jar
    hibernate-commons-annotations.jar
    hibernate-validator.jar
    hibernate3.jar
    jta.jar
    log4j-1.2.11.jar
    <JDBCDriver>.jar
  2. create the annotated class e.g. Action.java
  3. create the Hibernate configuration file hibernate.cfg.xml
  4. use the persistance classes

Building an Application[edit]

  • add libs
  • reengineer db to java classes or create java classes
  • create Util class for session e.g. HibernateUtil.java in project 'ballaballa_hiber'

Designing the domain model[edit]

Entitity Types vs. Value Types[edit]

Hibernate supports a fine-grained domain model (more classes than tables). An object of entity type has its own identity (primary key value). An object reference to an entity ist persisted as a reference in the database (a foreign key value). An entity has its own life cylce, it may exist independently of other entities. Criteria for an entity is:

  • shared references
  • lifecycle dependencies
  • identity

An object of value type has no database identity, it belongs to an entity instance and its persistent state ist embedded in the table row of its owning entity.

Associations[edit]

To specifiy the multiplicity it is neccessary to ask:

  • can there be more than one object of class A for a particular object of class B
  • can there be more than one object of class B for a particular object of class A

For a many-end association end the propertie must be of an interface type like java.util.set or java.util.List.


Reverse Engineer a Database[edit]

see Eclipse


Adding persistent class members[edit]

  • add it to the class
  • rebuild and reload application
  • the hibernate config file manages the db, if set correspondingly

Storing new or detached objects[edit]

org.hibernate.Session session = server.HibernateUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
session.save(vocable); // update() for detached objects
tx.commit();
session.close();

Debugging Concepts[edit]

The best way is to enabling logging via log4j:

Log4j[edit]

In JBoss Logging configuration is done here.

special entries in log4j.properties:

### log the sql inclusive values
log4j.logger.org.hibernate.SQL=debug
log4j.logger.org.hibernate.type=debug

ConfigurationFiles[edit]

Add the following entries:

<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="use_sql_comments">true</property>

then all SQL statements are written to stdout.

Literatur[edit]

  1. Java Persistance with Hibernate
  2. Online-Buch zu Annotations