JPA CDI Injecting DAO into an Entity

我的梦境 提交于 2019-12-11 01:04:36

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/10211371/jpa-cdi-injecting-dao-into-an-entity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!