JPA最佳做法? [英] JPA best practices?

查看:111
本文介绍了JPA最佳做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JPA/EclipseLink作为持久层来开发一个小的多层应用程序.在我目前的设计中,我有两组对象,即POJO和Entity对象,我将POJO用于​​一般的编程任务,而Entity类则用于DB的读/写和表映射​​.

I’m working on a little multi-tier application utilizing JPA/EclipseLink as a persistence layer. In my current design I have two sets of objects, POJOs and Entity objects, I use POJOs for general programming tasks and Entity classes are used for DB read/write and table mapping.

现在是否有必要(有问题地)进行POJO => Entity映射,然后再进行一次Entity ==> DB表映射(JPA注释)?我发现将实体类用作我的主要java对象并在需要时将其持久化会更容易,因为所有实体类本质上都是带有两个JPA批注的POJO.

Now is it necessary to have POJO=>Entity mapping (problematically) and then a second Entity==>DB tables mapping (JPA annotations)? I find it easier to just use Entity classes as my main java objects and persist them whenever necessary, after all Entity classes are essentially POJO with with couple of JPA annotations.

在确实有必要将事物分开的情况下,什么是进行POJO =>实体映射的最佳位置,目前我以CRUD方法(例如

Also in a situation where it's indeed necessary to keep things separated, what is the best place to do the POJO=>Entity mapping, currently I do this in a CRUD method, e.g.

public void addCustomerPOJO(Customer customerPOJO){
   //Cteat EntityManager and start a Transaction

   //Create Entity class and populate it with values 
   //from the passed-in regular (non entity) Customer class

  //Persiste and close
}

是否有更好或更通用的方法?

Is there a better or more common way to do this?

推荐答案

将实体用作域对象没有任何问题.您必须知道使用的是已分离的实体,但可以管理.

There is nothing wrong with using your entities as your domain objects. You have to be aware of using entities that have been detached and whatnot, but that can be managed.

我不会通过强迫每个实体映射到另一个bean(或POJO)来人为地为自己创建工作.有时有必要将许多实体(或实体中的值)包装到bean中,但只有在有充分理由的情况下才这样做.

I would not artificially create work for yourself by forcing each entity to be mapped to another bean (or POJO). Sometimes it is necessary to wrap many entities (or values from entities) into a bean, but only do it if there is a good reason.

这篇关于JPA最佳做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆