Rob
Rob

Reputation: 2666

JPA CDI Injecting DAO into an Entity

I'm new to JPA and CDI and I'm trying to create an enterprise application using these frameworks.

I get how I can inject into beans and keep everything tidy and stateless. I also get that JPA loads relations etc. for me so that I don't have to worry about it anymore. I still use my DAO's for specific find methods and ofcourse to create new entities.

I understand that I don't want to be injecting stuff into my entities since they're managed by JPA and I need to use the new keyword to create a new entity (instead of loading).

I'm used to managing my entities with other classes, for example if we have a User and a Group I use a stateless bean to manage the group (create new ones, find ones etc) and this stateless beans uses my DAO to retrieve and send the data.

I use the Group entity to manage the users (maybe this is wrong?) but I don't want to inject the DAO into the Group since it's an entity. I know there's something wrong in this design but I can't find the best practice for this.

Should all management classes be EJBs? I'm used to creating Domain classes for my logic, should I throw this concept away, put all my logic in EJBs and use the Entities for holding data only?

Upvotes: 2

Views: 1769

Answers (1)

Jan Groth
Jan Groth

Reputation: 14636

I use the Group entity to manage the users (maybe this is wrong?) but I don't want to inject the DAO into the Group since it's an entity. I know there's something wrong in this design but I can't find the best practice for this.

If a Group has Users, map this as a collection (possibly OneToMany).

Use another distinct bean to encapsulate persistence operations, e.g. a GroupService or a GroupDao. In this bean you will inject an EntityManger, which is responsible for persistence ("manage Users and Groups").

This tutorial should give you a start.

Should all management classes be EJBs?

Certainly not necessarily. But it's a bit hard (read: impossible) to tell without knowing your requirements. I suggest that you add isolated questions with more information, then it's way easier to discuss your problem...

As a rule of thumb: Try separating entities (Group, User) from business logic and persistence operations (GroupService, ...Dao).

I find this book gives an excellent overview and discussion about post J2EE pattern.

Upvotes: 1

Related Questions