change the OptimisticLockPolicy to use local-time - jpa

I'm using Eclipselink JPA, I have an Entity with a Timestamp field annotated with #Version por optimistic locking.
By default, this sets the entitymanager to use database time, so, if I have to do a batch update it doesn't work properly as it query the database for time each time it wants to do an insert.
How can I change the TimestampLockingPolicy to use LOCAL_TIME?
The class org.eclipse.persistence.descriptors.TimestampLockingPolicy.class has a public method useLocalTime() but I dont know how to use or, from where should I call it.

Found the answer:
first lets create a DescriptorCustomizer
public class LocalDateTimeCustomizer implements DescriptorCustomizer {
#Override
public void customize(ClassDescriptor descriptor) throws Exception {
OptimisticLockingPolicy policy = descriptor.getOptimisticLockingPolicy();
if (policy instanceof TimestampLockingPolicy) {
TimestampLockingPolicy p = (TimestampLockingPolicy) policy;
p.useLocalTime();
}
}
}
then annotate the entity that has the #Version with
#Customizer(LocalDateTimeCustomizer.class)

Related

Java JPA write only ID for nested entity

How can I avoid unnecessary queries to the DB?
I have LoadEntity with two nested entity - CarrierEntity and DriverEntity. Java class:
#Entity
public class LoadEntity {
...
#ManyToOne
#JoinColumn(name="carrier_id", nullable=false)
private CarrierEntity carrierEntity;
#ManyToOne
#JoinColumn(name="driver_id", nullable=false)
private DriverEntity driverEntity;
}
But API send me carrierId and driverId. I make it:
DriverEntity driverEntity = driverService.getDriverEntityById(request.getDriverId());
loadEntity.setDriverEntity(driverEntity);
loadRepository.save(loadEntity);
How can I write only driverId with JPA?
With Spring Data JPA you can always fall back on plain SQL.
Of course, this will side step all the great/annoying logic JPA gives you.
This means you won't get any events and the entities in memory might be out of sync with the database.
For this reason you might also increase the version column, if you are using optimistic locking.
That said you could update a sing field like this:
interface LoadRepository extends CrudRepository<LoadEntity, Long> {
#Query(query="update load_entity set driver_id = :driverId where carrier_id=:carrier_id", nativeQuery=true)
#Modifying
void updateDriverId(Long carrierId, Long driverId);
}
If you just want to avoid the loading of the DriverEntity you may also use JpaRepository.getById

Audit accesses to a JPA entity

I have a JPA entity, with its attibutes and several NamedQueries.
I'm trying to log some information "any time the entity is used for something", i.e.:
any time any of its NamedQueries is invoked
any time the entity is used in a Query q = em.createQuery("SELECT....FROM thisEntity a, otherEntity b WHERE.....");
any time any of its attributes is accessed
The information i want to log must include the invoker class name and invoker method, among other.
I guess this must be achieved through interceptors, but i'm not sure for example if interceptors allow me to intercept the accesses to the class throw its NamedQueries.
You could achieve that using callback methods like #PrePersist, #PostPersist, #PostLoad, #PreUpdate, #PostUpdate, #PreRemove, #PostRemove inside the entity classes.
For example
public class EntityA {
...
#PrePersist
public void beforePersist(){
//Log information
}
}
Additionally you could use that callback methods in listener classes.
public class EntityListenerA{
#PrePersist
public void beforePersist(EntityA ob) {
//Log information
}
}
#EntityListeners(EntityListenerA.class)
public class EntityA {
...
}
In your case I supose you must use the callback #PostLoad depending on the query.
Hope this help

How to intercept a SELECT query

I am exploring Entity Framework 7 and I would like to know if there is a way to intercept a "SELECT" query. Every time an entity is created, updated or deleted I stamp the entity with the current date and time.
SELECT *
FROM MyTable
WHERE DeletedOn IS NOT NULL
I would like all my SELECT queries to exclude deleted data (see WHERE clause above). Is there a way to do that using Entity Framework 7?
I am not sure what your underlying infrastructure looks like and if you have any abstraction between your application and Entity Framework. Let's assume you are working with DbSet<T> you could write an extension method to exclude data that has been deleted.
public class BaseEntity
{
public DateTime? DeletedOn { get; set; }
}
public static class EfExtensions
{
public static IQueryable<T> ExcludeDeleted<T>(this IDbSet<T> dbSet)
where T : BaseEntity
{
return dbSet.Where(e => e.DeletedOn == null);
}
}
//Usage
context.Set<BaseEntity>().ExcludeDeleted().Where(...additional where clause).
I have somewhat same issue. I'm trying to intercept read queries like; select, where etc in order to look into the returned result set. In EF Core you don't have an equivalent to override SaveChanges for read queries, unfortunately.
You can however, still i Entity Framework Core, hook into commandExecuting and commandExecuted, by using
var listener = _context.GetService<DiagnosticSource>();
(listener as DiagnosticListener).SubscribeWithAdapter(new CommandListener());
and creating a class with following two methods
public class CommandListener
{
[DiagnosticName("Microsoft.EntityFrameworkCore.Database.Command.CommandExecuting")]
public void OnCommandExecuting(DbCommand command, DbCommandMethod executeMethod, Guid commandId, Guid connectionId, bool async, DateTimeOffset startTime)
{
//do stuff.
}
[DiagnosticName("Microsoft.EntityFrameworkCore.Database.Command.CommandExecuted")]
public void OnCommandExecuted(object result, bool async)
{
//do stuff.
}
}
However these are high lewel interceptors and hence you won't be able to view the returned result set (making it useless in your case).
I recommend two things, first go to and cast a vote on the implementation of "Hooks to intercept and modify queries on the fly at high and low level" at: https://data.uservoice.com/forums/72025-entity-framework-core-feature-suggestions/suggestions/1051569-hooks-to-intercept-and-modify-queries-on-the-fly-a
Second you can use PostSharp (a commercial product) by using interceptors like; LocationInterceptionAspect on properties or OnMethodBoundaryAspect for methods.

JPA 2.0 Eclipselink - Adding/Deleting to child list gets optimistic lock

I am having an issue where eclipselink (2.5) is throwing an OptimisticLockException even though the only thing I'm modifiying is trying to either add or remove an item from a child list.
Entities :
#Entity
#Table(name="PLAN_ORG_RELATIONSHIP")
#Customizer(GridCacheCustomizer.class)
#AdditionalCriteria("CURRENT_TIMESTAMP BETWEEN this.startDate AND this.endDate")
#NamedQuery(name="PlanOrganizationRelationship.findAll", query="SELECT p FROM PlanOrganizationRelationship p")
#Portable
public class PlanOrganizationRelationship extends PrismObject implements Serializable {
#OneToMany(mappedBy="planOrganizationRelationship", cascade=CascadeType.PERSIST, orphanRemoval=true)
#PortableProperty(10)
private List<PlanOrganizationAction> planOrganizationActions;
public PlanOrganizationAction addPlanOrganizationAction(PlanOrganizationAction planOrganizationAction) {
getPlanOrganizationActions().add(planOrganizationAction);
planOrganizationAction.setPlanOrgRelationship(this);
return planOrganizationAction;
}
public PlanOrganizationAction removePlanOrganizationAction(PlanOrganizationAction planOrganizationAction) {
getPlanOrganizationActions().remove(planOrganizationAction);
planOrganizationAction.setPlanOrgRelationship(null);
return planOrganizationAction;
}
#Column(name="LST_UPDT_DT")
#Version
#PortableProperty(5)
private Timestamp lastUpdatedDate;
}
Other side of One To Many:
#Entity
#Table(name="PLAN_ORGANIZATION_ACTION")
#Customizer(GridCacheCustomizer.class)
#AdditionalCriteria("CURRENT_TIMESTAMP BETWEEN this.startDate AND this.endDate")
#NamedQuery(name="PlanOrganizationAction.findAll", query="SELECT p FROM PlanOrganizationAction p")
#Portable
public class PlanOrganizationAction extends PrismObject implements Serializable {
#ManyToOne
#JoinColumn(name="PLN_ORG_RLTNP_SEQ_ID")
#PortableProperty(7)
private PlanOrganizationRelationship planOrganizationRelationship;
}
I have 3 paths - Adding new Relationship with Actions (both entities new) or Add an Action or Remove Action
When I am adding both, I perist the parent and the children are persisted as well and that is the expected behavior.
When I try to add or remove I try something like
PrismOrganizationRelationship por = findById (..) //we are spring-data-jpa
por.addPlanOrganizationAction(action);
repo.save(por); // Throws optimistic lock - even though #Version is the same
Not sure what is causing this issue ?
Check cascade=CascadeType.PERSIST. It work only for persist(save newly entity) operation. your operation remove child entity mean updating main entity. Thats why, you need to useCascadeType.MARGE` for update operation.

How to implement "delete all" for a Spring Roo Entity?

I'm trying to delete all database entries for a Spring Roo entity. When I look at *_Roo_Entity.aj it seems as if there is no "delete all" method. I tried to implement it myself (Licences is the name of the Roo entity. Don't mind the naming. It was reverese engineered from a database and may be changed later):
public static int Licences.deleteAll() {
return entityManager().createQuery("delete from Licences o").executeUpdate();
}
It compiles just fine but when I call Licences.deleteAll() I get the following exception:
org.springframework.dao.InvalidDataAccessApiUsageException: Executing an update/delete query;
nested exception is javax.persistence.TransactionRequiredException: Executing an update/delete query (NativeException)
Adding #Transactional doesn't make a difference.
What am I missing here?
Is this approach completely wrong and I need to implement it like this:
public static void Licences.deleteAll() {
for (Licences licence : findAllLicenceses()) {
licence.remove();
}
}
This works, but is JPA smart enough to translate this into a delete from licences query or will it create n queries?
#Transactional doesn't work on static function
change
public static int Licences.deleteAll() {
return entityManager().createQuery("delete from Licences o").executeUpdate();
}
to
public int Licences.deleteAll() {
return entityManager().createQuery("delete from Licences o").executeUpdate();
}
https://jira.springsource.org/browse/SPR-5999
Bye
JPA does not have a delete all functionality. (even not with JQL!)
At least there are only three ways:
The loop, like you did
A JPQL Query see: JPQL Reference: 10.2.9. JPQL Bulk Update and Delete
A native SQL Query, but this will cause many problems with Entity Manager caches!
BTW: It seams that you are using AspectJ to attach you delete method. - You can do this (even if I do not know, why not adding the static method direct to the Entity class), but you must not touch the Roo generated aj files!
public static int Licences.deleteAll() {
return new Licences().deleteAllTransactional();
}
#Transactional
private int Licences.deleteAllTransactional() {
if (this.entityManager == null) this.entityManager = entityManager();
return this.entityManager.createQuery("delete from Licences o").executeUpdate();
}