Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Active record pattern with Hibernate

I am developing a fairly simple web app using Spring MVC + JSP + Hibernate. To get started I followed this tutorial: http://www.cavalr.com/blog/Spring_3_and_Annotation_Based_Hibernate_4_Example

This is working ok, but I am concerned about the verbosity of code. To support the User entity, we also have UserDao, UserDaoImpl, UserService and UserServiceImpl. I understand that for a large enterprise application you might actually want this. But for my simple web app this is unneeded (and unwanted) complexity. I could achieve all this in Python much more simply.

So, is there any way to have Hibernate use the Active Record design pattern? The sort of thing I'd be looking to do is have User inherit methods like get() from a base class. So you could do User.get(userName)

I am open minded to using a different ORM to Hibernate; I'd just started with that as it seems the common choice. And also it's supposedly similar to Python SQLAlchemy, which I am familiar with.

I am also open minded to more out of the box solutions, perhaps an IDE plugin that can autogenerate the DAO classes.

Any suggestions appreciated!

Paul

like image 410
paj28 Avatar asked Jun 08 '26 16:06

paj28


2 Answers

Have a look at spring roo, it uses the active record pattern.

Or (after a look at roo) you can build it by your own. All you need is:

  • @Configurable at your entities to enable injection (this requires also real AspectJ)

You can use it to inject the EntityManager or hibernateSession

like image 50
Ralph Avatar answered Jun 10 '26 05:06

Ralph


 UserDao, UserDaoImpl, UserService and UserServiceImpl

The interfaces make testing with mock objects easier, I guess you could rid of them if you don't plan using mocks.

I have one generic DomainRepository for simple get/sets - you don;t need the service class(es) unless multple entites are involved.

To further reduce the code you write, take a look a spring data, although I guess it might be overkill here.

like image 26
NimChimpsky Avatar answered Jun 10 '26 04:06

NimChimpsky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!