March 25, 2009 @ 10:51 am
Changing Hibernate Mapping from XML to Annotations
It was because of my job interview last Friday that I’ve decided to start doing away with mapping my hibernate metadata on xml and go for Annotations instead. The interviewer suggested it and of course I’m easily convinced once I heard that “it make things easier.”
The great thing about these frameworks is that everything’s utterly comprehensive and modular. You just need to identify one specific thing that you’d want to integrate and just work on it bit by bit. Learning these web frameworks rattled me in the beginning with its steep learning curve but once you get the hang of it, integrating any modules that you can think of gets easier and easier. Also, you can never really run out of online tutorials and resources to guide you through the integration; forums almost always have already discussed the programming issues that you’re encountering, you just need to know how to search for it.
So, right now, I am already working on this long, long running project with some objects already mapped. I picked one object to try to convert from xml mapping to Annotations mapping – Project. Hibernate already have a road map (http://hibernate.org/152.html) defined in case you wanted to learn a specific module.
So firstly, I downloaded Hibernate Annotations and all its dependencies. Then made sure that it’s in my classpath.
Then I changed this
into this
package com.pink.sandbox.pts.domain;
import org.hibernate.annotations.*;
import javax.persistence.*;
import java.util.Date;
import java.util.List;
import com.pink.sandbox.cms.domain.Client;
import com.pink.sandbox.hris.domain.Department;
@javax.persistence.Entity
@javax.persistence.Table(name="project")
public class Project {
@Id @GeneratedValue(generator="generator")
@GenericGenerator(name = "generator", strategy = "increment")
private Long id;
private String name;
@ManyToOne
@JoinColumn(name="department")
private Department department;
@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="client")
private Client client;
private String joNum;
private String description;
private Date startDate;
private Date endDate;
private String poNum;
private Date clientStartDate;
private Date clientEndDate;
@OneToMany(cascade = javax.persistence.CascadeType.ALL)
@IndexColumn(name = "seqIdx")
@JoinColumn(name="parentId")
private List stages;
private boolean completed;
/* getter and setter methods go here ...*/
}
and change a few lines in my hibernate.cfg.xml from this
into this
and then add this into my session factory bean
org.hibernate.cfg.AnnotationConfiguration
Filed under Geekology Permalink
