As our current project allows for some experimentation and adoption of recent technologies, we spent today with EJB3 Hibernate Annotations to get away from the XML configuration one used to create with Hibernate before.
The annotations need to be placed in the same compilation unit as the entity class lives in. The result is that these POJOs now are no longer POJOs in a very tight sense. That has been criticized as polluting the codebase with ORM specific annotations. That's certainly right, but one does not replace one ORM tool for another very often and going with the EJB3 Java Persistence annotation one can replace ORM tools, as Hibernate is just one implementation of that API. So I wouldn't fear too much. After all those classes that become entity classes are meant to be stored into a database and somewhere I have to put the mapping. Doing so in Java code instead of an external XML file appears to be clearer and more appealing to a developer.
Here is something we learned today.
Let's define a persistent entity class called Issue
.
@Entity @Table(name="issue") @NamedQueries( { @NamedQuery(name = "findIssueById", query = "from Issue i where i.id = ?") }) public class Issue implements IdentifiableObject { @Id @GeneratedValue private long id ; [...] }
This entity will be persisted into the table issue
and you see that it has an id field. Other fields are omitted for clarity. Further we define a named query findIssueById
.
In a generic DAO class using Spring's Hibernate template we create a method findById
as follows.
public Object findById(String query, long id) { List list = getHibernateTemplate().findByNamedQuery(query, id); if (list.isEmpty()) return null ; else return list.get(0) ; }
Elsewhere in the application we can the find any entity by calling findById passing in the name of the named query and of course the query criteria id.
Issue issueRead = (Issue) repository.findById("findIssueById", someId) ;
In your Spring application context configure your session factory using the AnnotationSessionFactoryBean
.
org.hibernate.dialect.HSQLDialect [...] net.caimito.savila.Issue
Previous | 09 Mar 2007 | Next |
This article has been posted to social media sites. There might be comments. Just follow the links:
About me
Hello! My name is Stephan Schwab.
As International Software Development Coach and Consultant I help CEOs and Department Leaders to improve value creation and cohesion within their organization. The outcome will be higher quality, customer delight and more revenue.
Learn about my professional experience since 1986.
Professional Services
I'm fluent in these human languages:
Scrum Pair-Coaching to develop technical competence:
Resources for new clients:
Search
Special Content
Highlights of the Year
Living on planet Earth
Open Source Projects
Stay in touch
My Books
Everything
See a listing of all posts on this site.