如何在EJB3的Entity类内部访问EntityManager [英] How to access EntityManager inside Entity class in EJB3

查看:115
本文介绍了如何在EJB3的Entity类内部访问EntityManager的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要执行db查询,以便在多对多关联表中设置额外的列按列排序。因此我需要从Entity类内部访问db序列,然后选择序列的nextval并将其分配给@prepersist生命周期回调方法中的order_by列。

I need to execute a db query inorder to set the extra column "The order by column" in a many to many association table. so I need to access the db sequence from inside the Entity class and and select the nextval of the sequence and assign it to the order_by column in @prepersist lifecycle callback method.

@Entity
public class ProductWishlist implements Serializable
{

....
@Column(name="ORDER_BIT")
private long orderBit;

// getter setter
// .......

@Prepersist
public void setOrderBit(EntityManager entityManager)
{
   Query q=entityManager.createNativeQuery("select nextval('SHP_PRODUCTS_PICS_ORDER_SEQ')");
Long order=(Long)q.getResultList().get(0);
this.setOrderBit(order);

}
}


如何从setOrderBit()中访问EntityManger?如何将Entitymanager传递给它?
或如何在Entity类内执行本机查询?

HOw can I access entitymanger from within setOrderBit ()? how can i Pass Entitymanager into it? Or How can i execute native query inside an Entity class?

推荐答案

注入 EntityManager <不建议在实体bean中使用/ code>。在我看来,充当POJO的实体bean用于在层或网络之间进行数据传输。

Injecting EntityManager in entity bean isn't recommended. In my view, the entity bean acting as POJO is meant for data transmission between layers or network.

最好预先填充实体,在持久化之前进行数据操作。但是,可以在实体回调方法中完成对属性或数据格式的某些验证。

Its better to pre-populate entity, data manipulation prior persistence. But some validation on attributes or formatting of data can be done within entity callback methods.

在这里,您可以通过在实体上应用 @EntityListeners 注释来尝试使用实体侦听器,该注释会在实体生命周期中得到通知回调方法。

Here, you can try using entity listener by applying @EntityListeners annotation on entity, which gets notified upon entity lifecycle callback method.

这篇关于如何在EJB3的Entity类内部访问EntityManager的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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