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);
}
}
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?
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.
Here, you can try using entity listener by applying @EntityListeners
annotation on entity, which gets notified upon entity lifecycle callback method.
You should not use EntityManager in pre-persist (or in lifecycle methods in general), because it is not aloud according specification:
In general, the lifecycle method of a portable application should not
invoke EntityManager or Query operations, access other entity
instances, or modify relationships within the same persistence
context.[43] A lifecycle callback method may modify thepost persist
non-relationship state of the entity on which it is invoked.
[43] The semantics of such operations may be standardized in a future
release of this specification.
Just obtain normal JDBC connection and use it to execute query.