Thursday, November 26, 2009

Hibernate annotation for a Map Enum type



Hibernate Annotations are so great, especially together with the Hibernate Tools that allows to generate the whole database (sql table definitions) from your annotated beans.
Right now I mapped the first time a java.util.Map with some enum type as key and a primitive type as value (java.lang.String).
The mapping looks like the following:

 
public class Test { 
    @CollectionOfElements 
    @JoinTable(name = "my_table") 
    @Cascade(value = org.hibernate.annotations.CascadeType.DELETE_ORPHAN) 
    @Enumerated(value = EnumType.STRING) 
    @org.hibernate.annotations.MapKey(columns = {@Column(name = "my_enum")}) 
    @Column(name = "my_value", length = 4000) 
    public Map getMappedValues() { 
        return _mappedValues; 
    } 
 
} 


What I was not able to do was to define the type of the value (String) as hibernate type text. This gave the correct table/column definition at build time (hibernate tools), but a ClassCastException at runtime, saying that MyEnumType is not compatible to hibernate’s type text. So I used the length of the @Column annotation as a temporary workaround - I’ll dig into this now or later

Wednesday, November 25, 2009

Hibernate (annotations) - how to get started??

My experiences and background were similar, and I also had a hard time finding a tutorial that addressed my development preferences (which seem similar to yours):
  • Prefer JPA annotations over XML, only adding Hibernate annotations when the JPA counterparts do not suffice
  • Use Hibernate's SessionFactory / Session to access persistent data rather than JPA EntityManager
  • Use immutable classes wherever possible
I read most of Java Persistence with Hibernate, and it took a long time to separate this use case from all the other options that it presents (XML configuration in Hibernate/JPA format, xdoclet "annotations", etc...).
It would have made so much more sense to me if the available documentation would take a stand and actively push me in this direction instead of giving me a bunch of options and wondering where to go. Lacking that, I learned the following lessons by converting the standard Hibernate Tutorial over to annotations.

Configuration

  • Keep hibernate.cfg.xml to the bare minimum (see below).
  • Define database column / table names explicitly with the JPA annotations so you get exactly the schema you want. You can double-check it by using SchemaExport.create(true, false). Note that you may not get the exact schema you expect if Hibernate tries to update the schema on an existing database (for example, you can't add a NOT NULL constraint to a column that already contains null values).
  • Create the SessionFactory's Configuration using AnnotationConfiguration.addAnnotatedClass().addAnnotatedClass()...
Here's my copy of hibernate.cfg.xml. It only sets properties, and explicitly avoids any mapping configuration.


    
            
        org.hsqldb.jdbcDriver
        jdbc:hsqldb:hsql://localhost
            sa
            
            1
            org.hibernate.dialect.HSQLDialect

            
            update
            thread
            org.hibernate.cache.NoCacheProvider
            false
    




Scope

  • Begin/commit/rollback transactions outside each Manager / DAO class. I have no idea why the tutorial's EventManager starts/commits its own transactions, as the book identifies this as being an anti-pattern. For the servlet in the tutorial, this can be done by making a Filter that starts the transaction, invokes the rest of the FilterChain, and then commits/rolls back the transaction.
  • Similarly, make the SessionFactory outside and pass it in to each Manager / DAO class, which then calls SessionFactory.getCurrentSession() any time it needs to access data. When it comes time to unit test your DAO classes, make your own SessionFactory that connects to an in-memory database (such as "jdbc:hsqldb:mem:test") and pass it into the DAO being tested.
For example, some snippets from my version of EventManager:

public final class EventManager {

private final SessionFactory sessionFactory;

/** Default constructor for use with JSPs */
public EventManager() {

        this.sessionFactory = HibernateUtil.getSessionFactory();
}

/** @param Nonnull access to sessions with the data store */
public EventManager(SessionFactory sessionFactory) {

        this.sessionFactory = sessionFactory;
}

    /** @return Nonnull events; empty if none exist */
public List getEvents() {

        final Session db = this.sessionFactory.getCurrentSession();
        return db.createCriteria(Event.class).list();
}

/**
 * Creates and stores an Event for which no people are yet registered.
 * @param title Nonnull; see {@link Event}
 * @param date Nonnull; see {@link Event}
 * @return Nonnull event that was created
 */
public Event createEvent(String title, Date date) {

        final Event event = new Event(title, date, new HashSet ());
        this.sessionFactory.getCurrentSession().save(event);
        return event;
}

/**
 * Registers the specified person for the specified event.
 * @param personId ID of an existing person
 * @param eventId ID of an existing event
 */
public void register(long personId, long eventId) {

        final Session db = this.sessionFactory.getCurrentSession();
        final Person person = (Person) db.load(Person.class, personId);
        final Event event = (Event) db.load(Event.class, eventId);
        person.addEvent(event);
        event.register(person);
}

...other query / update methods...
}


Data classes

  • Fields are private
  • Getter methods return defensive copies since Hibernate can access the fields directly
  • Don't add setter methods unless you really have to.
  • When it is necessary to update some field in the class, do it in a way that preserves encapsulation. It's much safer to call something like event.addPerson(person) instead of event.getPeople().add(person)
For example, I find this implementation of Event much simpler to understand as long as you remember that Hibernate accesses fields directly when it needs to.


@Entity(name="EVENT")
public final class Event {

private @Id @GeneratedValue @Column(name="EVENT_ID") Long id; //Nullable

/* Business key properties (assumed to always be present) */
private @Column(name="TITLE", nullable=false) String title;

@Column(name="DATE", nullable=false)
@Temporal(TemporalType.TIMESTAMP)
private Date date;

/* Relationships to other objects */
@ManyToMany
@JoinTable(
name = "EVENT_PERSON",
joinColumns = {@JoinColumn(name="EVENT_ID_FK", nullable=false)},
inverseJoinColumns = {@JoinColumn(name="PERSON_ID_FK", nullable=false)})
private Set<Person> registrants; //Nonnull

public Event() { /* Required for framework use */ }

/**
* @param title Non-empty name of the event
* @param date Nonnull date at which the event takes place
* @param participants Nonnull people participating in this event
*/
public Event(String title, Date date, Set<Person> participants) {

this.title = title;
this.date = new Date(date.getTime());
this.registrants = new HashSet<Person> (participants);
}

/* Query methods */

/** @return Nullable ID used for persistence */
public Long getId() {

return this.id;
}

public String getTitle() {

return this.title;
}

public Date getDate() {

return new Date(this.date.getTime());
}

/** @return Nonnull people registered for this event, if any. */
public Set<Person> getRegistrants() {

return new HashSet<Person> (this.registrants);
}

/* Update methods */

public void register(Person person) {

this.registrants.add(person);
}
}
Hope that helps!

How to use Hibernate @Any annotations?

For example let's assume three different applications which manage a media library - the first application manages books borrowing, the second one DVDs, and the third VHSs. The applications have nothing in common. Now we want to develop a new application that manages all three media types and reuses the exiting Book, DVD, and VHS entities. Since Book, DVD, and VHS classes came from different applications they don't have any ancestor entity - the common ancestor is java.lang.Object. Still we would like to have one Borrow entity which can refer to any of the possible media type.
To solve this type of references we can use the any mapping. this mapping always includes more than one column: one column includes the type of the entity the current mapped property refers to and the other includes the identity of the entity, for example if we refer to a book it the first column will include a marker for the Book entity type and the second one will include the id of the specific book.
@Entity
@Table(name = "BORROW")
public class Borrow{

@Id
@GeneratedValue
private Long id;

@Any(metaColumn = @Column(name = "ITEM_TYPE"))
@AnyMetaDef(idType = "long", metaType = "string",
metaValues = {
@MetaValue(targetEntity = Book.class, value = "B"),
@MetaValue(targetEntity = VHS.class, value = "V"),
@MetaValue(targetEntity = DVD.class, value = "D")
})
@JoinColumn(name="ITEM_ID")
private Object item;

.......
public Object getItem() {
return item;
}

public void setItem(Object item) {
this.item = item;
}

}