Hibernate

Hibernate is a de-facto standard object/relational persistence tool for Java. This partly explains the lack of other tools supported by PicoContainer Persistence.

The Persistence Hibernate module provides support for DI and lifecycle.

Let's walk through a typical use case: how to configure a Hibernate persister using a given configuration file. We want the hibernate configuration path to be configurable via a PicoContainer script - let's say XML for the sake of this example, although of course anything said for XML will hold for other scripts too. The hibernate.cfg.xml will look something like



  
    

    
    
  


and we want to use this config file to create a Hibernate SessionFactory that will be injected in the persister:
public class MyHibernatePersister {

    private SessionFactory factory;

    /**
     * Creates an MyHibernatePersister with a Hibernate SessionFactory
     * 
     * @param factory the SessionFactory
     */
    public MyHibernatePersister(SessionFactory factory){
        this.factory = factory;
    }

    // ... your hibernate code
}
to manage persisted entities such as MyEntity
@Entity
@Table(name = "ENTITY")
public class MyEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private String id;

    @Column(name = "NAME", nullable = true)
    private String name;

}
Note that we are using annotations here to define the mapping - although their use is optional even though highly recommended. To provide the required dependency via PicoContainer all we need to do is register the following two adapters of Hibernate objects org.picocontainer.persistence.hibernate.annotations.ConstructableAnnotationConfiguration and org.picocontainer.persistence.hibernate.ConfigurableSessionFactory :

 
    hibernate.cfg.xml
  
  
  

If you wanted to not use annotations, all you had to do was to use org.picocontainer.persistence.hibernate.ConstructableConfiguration in place of the ConstructableAnnotationConfiguration (and of course define the mapping manually via a hibernate.hbm.xml file).