I’ve finally gotten around to learning Hibernate Annotations. Wow. It really is an improvement over dealing with old-style .hbm files. Although .hbm files are powerful in their own it is in my opinion an improvement to bring everything back into the Java source file. There’s less confusion and a little less room for things to get sloppy and out-of-synch.
When I first set out to learn annotations, I took a wrong turn and wound up in the land of JPA and EJB3. Things got confusing fast and I felt as if I was vastly adding complexity to my domain model by pulling in all of these various frameworks. It turns out that you can pull in Hibernate Annotations and still develop with simplicity of Hibernate and Spring integration.
Here’s a very small example.
@Entity
@Table(name = "visitor")
public class Visitor extends AbstractEntity implements java.io.Serializable
{
@Id
@Column(name = "visitor_id")
@GeneratedValue(strategy=GenerationType.AUTO, generator = "VISITOR_SEQUENCE")
@SequenceGenerator(name="VISITOR_SEQUENCE", sequenceName = "visitor_sequence")
private Long visitorId;
private String accountName;
private String password;
private String firstName;
private String lastName;
}
That’s it for a very simple entity with no relations. One of the powerful aspects is that it is portable. The AUTO specification for the id generator is portable between MySQL and Oracle. If you combine this with Hibernate’s auto-DDL generation it is a quick way to scale your development environment between a local instance of MySQL and a development/staging server running Oracle. Currently I like to have one JUnit test that runs the DDL generation so that I can start over with a fresh database. There may be more elegant solutions but this works with little fuss.