I'm wondering if it is possible to initialize a transient attribute of an entity during a criteria query.
Example
#Entity
public SampleEntity{
#Id
private long id;
[more attributes]
#Transient
private String someTransientString;
[getters and setters]
}
Now I want to compose a CriteriaQuery that loads all SampleEntitys and automatically sets someTransientString to imamightlyfinestring. I have something like the following SQL in mind:
SELECT ID AS ID, [..], 'imamightilyfinestring' AS SOME_TRANSIENT_STRING FROM SAMPLE_ENTITY
I of course know that I can simply iterate the resulting collection and manually set the attribute, but I'm wondering if there is a way to do it within JPA2.
Thanks :)
No, you cannot do it in query.
If you can figure out value for someTransientString outside of query, you can use PostLoad callback (excerpt from JPA 2.0 specification):
The PostLoad method for an entity is invoked after the entity has been
loaded into the current persistence context from the database or after
the refresh operation has been applied to it. The PostLoad method is
invoked before a query result is returned or accessed or before an
association is traversed.
Just add following to your entity:
#PostLoad
protected void initSomeTransientString() {
//Likely some more complex logic to figure out value,
//if it is this simple, just set it directly in field declaration.
someTransientString = "imamightilyfinestring";
}
You can also initialize your transients in the default (i.e., no argument) constructor.
You can see that this is the strategy used, for example, in EclipseLink (read last comment in the following link):
https://bugs.eclipse.org/bugs/show_bug.cgi?id=292385
Related
I am facing a very strange issue at the moment.
I have an entity that contains a property that is an element collection.
#ElementCollection(targetClass=Integer.class, fetch = FetchType.EAGER)
#CollectionTable(name="campaign_publisher", joinColumns=#JoinColumn(name="campaign_id"))
#Column(name = "publisher_id")
...
#NotEmpty(message = "campaign.publishers.missing")
public Set<Integer> getPublishers() {
return this.publishers;
}
public Campaign setPublishers(Set<Integer> publisherId) {
this.publishers = publisherId;
return this;
}
This all works fine. The values are validated and saved correct.
I also want this entity to have optimistic concurrency so I applied a #Version annotation as well.
#Version
private Long etag = 0L;
...
public Long getEtag() {
return etag;
}
public void setEtag(Long etag) {
this.etag = etag;
}
By adding the #Version annotation the #NotEmpty validation on my set of publishers always returns invalid.
To try and diagnose this I have tried the following:
Creating a custom validator at the entity level so I can inspect the values in the entity. I found that the Set of values have been replaced with an empty PersistentSet which is causing the validation to always fail.
I created some unit tests for the entity that uses a validator that is retrieved from the validationfactory and this validator seems to work as expected.
I have also tried to change the ElementCollection to a many-to-many relationship and a bi-directional one-to-many but the issue persists.
Right now I am out of ideas. The only thing I have found that works correctly is disabling the hibernate validation and manually calling the validator just before I save my data.
So my questions are:
Has anyone encountered this issue before?
Any advice on what I could try next?
Thank you all for reading!
Short answer: Set the initial value for etag = null.
// this should do the trick
#Version
private Long etag = null;
Longer one : When you are adding a optimistic locking via adding #Version annotation on a field with a default value you are making hibernate/spring-data think that the entity is not a new one (even the id is null). So on initial save instead of persisting entity undelying libraries try to do a merge. And merging transient entity forces hibernate to just one by one copy all the properties from source entity (the ones which you are persisting) to the target one (which is autocreate by hibernate with all the properties set to default values aka nulls) and here comes the problem, as hibernate will just copy the values of associations of FROM_PARENT type or in other words only associations which are hold on entity side but in your case the association is TO_PARENT (a foreign key from child to parent) hibernate will try to postpone association persistance after main entity save, but save will not work as entity will not pass #NotEmpty validation.
First I would suggest to remove the default value initialization for your #Version property. This property is maintained by hibernate, and should be initialized by it.
Second: are you sure that you are validating the fully constructed entity? i.e. you are constructing something, then do something, and for exact persist/flush cycle your entity is in wrong condition.
To clarify this, while you are on a Spring side, I would suggest to introduce service-level validation on your DAO layer. I.e. force the bean validation during initial call to DAO, rather then bean validation of entity during flush (yeap hibernate batches lots of things, and exact validation happens only during flush cycle).
To achieve this: mark your DAO #Validated and make your function arguments beign validated: FancyEntity store(#Valid #NotNull FancyEntity fancyEntity) { fancyEntity = em.persist(fancyEntity); em.flush(); return fancyEntity;}
By making this, you will be sure that you are storing valid entity: the validation would happen before store method is called. This will reveal the place where your entity became invalid: in your service layer, or in bad behaving hibernate layer.
I noticed that you use mixed access: methods and fields. In this case you can try to set #Version on the method:
#Version
public Long getEtag() {
return etag;
}
not on the field.
Assume we have a simple entity bean, like above
#Entity
public class Schemes implements serializable{
...
#Id private long id;
...
}
I find a record using find method and it works perfect, the problem is I cannot manipulate it(remove) by another EntityManager later, for example I find it with a method, and later I want to remove it, what is the problem?! if I find it with same manager again I would remove it, but if object has found by another manager I cannot.
#ManagedBean #SessionScopped class JSFBean {
private Schemes s;
public JSFBean(){
....
EntityManager em;//.....
s=em.find(Schemes.class,0x10L);//okay!
....
}
public void remove(){//later
....
EntityManager em;//.....
em.getTransaction().begin();
em.remove(s);//Error! some weird error, it throws IllegalArgumentException!
em.getTransaction().commit();
....
}
}
many thanks.
You are probably getting a java.lang.IllegalArgumentException: Removing a detached instance.
The two EMs do not share a persistence context and for the second EM, your object is considered detached. Trying to remove a detached object will result in an IllegalArgumentException.
You can refetch the entity before the removal:
Schemes originalS = em.find(Schemes.class, s.getId());
em.remove(originalS);
EDIT You can also delete the entity without fetching it first by using parametrized bulk queries:
DELETE FROM Schemes s WHERE s.id = :id
Be aware that bulk queries can cause problems on their own. First, they bypass the persistence context, meaning that whatever you do with a bulk query will not be reflected by the objects in the persistence context. This is less an issue for delete queries than for update queries. Secondly, if you have defined any cascading rules on your entites - they will be ignored by a bulk query.
I have an entity class in my Enterprise Java application that has an entity listener attached to it:
#Entity
#EntityListeners(ChangeListener.class)
public class MyEntity {
#Id
private long id;
private String name;
private Integer result;
private Boolean dirty;
...
}
However, I would like it so that the entity listener got triggered for all fields except the boolean one. Is there any way exclude a field from triggering the entity listener without making it transient?
I'm using Java EE 5 with Hibernate.
However, it is possible if you implement your own solution. I've had the same need for audit log business requirement, so designed my own AuditField annotation, and applied to the fields to be audit-logged.
Here's the example in one entity bean - Site.
#AuditField(exclude={EntityActionType.DELETE})
#Column(name = "site_code", nullable = false)
private String siteCode;
So, the example indicates the 'siteCode' is a field to audit log, except DELETE action. (EntityActionType is an enum and it contains CRUD operations.)
Also, the EntityListenerhas this part of code.
#PostPersist
public void created(Site pEntity) {
log(pEntity, EntityActionType.CREATE);
}
#PreUpdate
public void updated(Site pEntity) {
log(pEntity, EntityActionType.UPDATE);
}
#PreRemove
public void deleted(Site pEntity) {
log(pEntity, EntityActionType.DELETE);
}
Now what it has to do in log() is, to figure what fields are to audit log and what custom actions are involved optionally.
However, there's another to consider.
If you put the annotation at another entity variable, what fields of the entity have to be logged? (i.e. chained logging)
It's your choice whether what are annotated with #AuditField only in the entity or some other ways. For my case, we decided to log only the entity ID, which is a PK of a DB table. However, I wanted to make it flexible assuming the business can change. So, all the entites must implement auditValue() method, which is coming from a base entity class, and the default implementation (that's overridable) is to return its ID.
There is some kind of mixing of concepts here. EntityListeners are not notified about changes in attribute values - not for single attribute, neither for all attributes.
For reason they are called lifecycle callbacks. They are triggered by following lifecycle events of entity:
persist (pre/post)
load (post)
update(pre/post)
remove (pre/post)
For each one of them there is matching annotation. So answer is that it is not possible to limit this functionality by type of persistent attributes.
Let's say I have a Hibernate entity that declares a OneToMany relationship to a different entity:
#Entity
public class SomeEntity {
#OneToMany(fetch = FetchType.LAZY)
private List<OtherEntity> otherEntities = new LinkedList<OtherEntity>();
[...]
}
When mapping SomeEntity to the corresponding DTO, all I need are the IDs that identify OtherEntity as primary key (i.e., I am not actually interested in OtherEntity instances).
Does Hibernate support this pattern, i.e., only retrieving the IDs of entities referenced via a OneToMany relationship?
I cannot influence how SomeEntity is retrieved (i.e., I have an existing SomeEntity instance retrieved within te scope of the current Hibernate session), but let's assume that lazy loading has not yet taken place, so just retrieving the child objects' IDs (rather than the complete objects) would actually yield a performance benefit.
Well, if you only need the entities' ids and you want to be economical about it, when you get those entities from the database you should state in your query that you only want to get the ids of each entry, using projections, something like :
SELECT Entity.id as entity FROM Entity WHERE ...
This will return an array of objects of the same type as Entity's id field type.
You can try obtaining the primary key without accessing the entity itself (without otherEntities.get(0).getId()). To do this you can use the PersistenceUnitUtil class:
PersistenceUnitUtil#getIdentifier(yourEntity)
The PersistenceUnitUtil can be obtained from the EntityManagerFactory. So it could be something like:
EntityManager em = ...
PersistenceUnitUtil = em.getEntityManagerFactory().getPersistenceUnitUtil();
Unfortunately, I'm not aware if this will prevent the entity loading from occuring. However, just accessing the otherEntities collection or even obtaining references to each entity will not make the instance to be loaded; you need to invoke a method on the fetched entity in order to be sure it will be loaded.
You also might consider creating a #NamedQuery and return only the OtherEntity ID's.
HTH!
From hibernate reference, section 2.2.2.1.
http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html/entity.html#entity-mapping-property
Declare your columns as lazy initialized:
#Basic(fetch = FetchType.LAZY)
private String getYourProperty() {
}
You also need to disable proxies for your entity class and byte instrument it. There is an example here:
Making a OneToOne-relation lazy
You can use the below HQL as told in the documentation to establish this.
session.createQuery(select new OtherEntity(oe.id) OtherEntity oe
where oe.parentSomeEntity.someId = :someId).list();//also set someId.
Add a constructor in OtherEntity to set the id also there should be a mapping to SomeEntity in OtherEntity.
This HQL will give you a List<OtherEntity> with only id set in the bean.
In my code I am using JSF - Front end , EJB-Middile Tier and JPA connect to DB.Calling the EJB using the Webservices.Using MySQL as DAtabase.
I have created the Voter table in which I need to insert the record.
I ma passing the values from the JSF to EJB, it is working.I have created JPA controller class (which automatcally generates the persistence code based on the data base classes)
Ex: getting the entity manager etc.,
em = getEntityManager();
em.getTransaction().begin();
em.persist(voter);
em.getTransaction().commit();
I have created the named query also:
#NamedQuery(name = "Voter.insertRecord", query = "INSERT INTO Voter v
values v.voterID = :voterID,v.password = :password,v.partSSN = :partSSN,
v.address = :address, v.zipCode = :zipCode,v.ssn = :ssn,
v.vFirstName = :vFirstName,v.vLastName = :vLastName,v.dob = :dob"),
But still not able to insert the record?
Can anyone help me in inserting the record into the Data base through JPA.(Persistence object)?
Update:
If we are using the container managed entity manager, should we need to write begin and commit transactions again...
like this:
em.getTransaction().begin();
em.getTransaction().commit();
I have written:
Voter v= new Voter(voterID,password,partSSN,address,zipCode,ssn,vFirstName,vLastName,d1,voterFlag);
em.persist(v);
But it is resulting to Null pointer exception.
SEVERE: java.lang.NullPointerException
at ejb.Registration.reg(Registration.java:39)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1052)
at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1124)
at com.sun.ejb.containers.BaseContainer.invokeTargetBeanMethod(BaseContainer.java:4038)
at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:5223)
I think that you missed the point of JPA. With JPA, you're not supposed to write queries to insert, update or delete persistent objects, JPA will generate them for you.
So, what you need to do is to create domain objects and to annotate them to make them "persistable" (such annotated objects are called entities) and tell the JPA engine how to "map" them to your database. Let me try to show you the right path...
First, create a Voter domain object and add JPA annotations (an entity class must be annotated with the Entity annotation, must have a no-arg constructor, must implement Serializable, must have a primary key identified by the Id annotation):
#Entity
public class Voter implements Serializable {
private Long id;
private String firstName;
private String lastName;
private String password;
// other attributes
// No-arg constructor
public Voter() {}
#Id #GeneratedValue // property access is used
public Long getId() { return this.id; }
protected void setId(Long id) { this.id = id; }
// other getters, setters, equals, hashCode
}
I'm using JPA's defaults here (default table name, column name, etc). But this can be customized using the Table or Column annotations if you need to map your entity to an existing model.
Then, create a new instance and set the various attributes:
Voter voter = new Voter();
voter.setFirstName(firstName);
voter.setLastName(lastName);
...
And persist it:
em.getTransaction().begin();
em.persist(voter);
em.getTransaction().commit();
This is just a short introduction, JPA can't be covered in one answer. To go further, I suggest to check the Introduction to the Java Persistence API from the Java EE 5 Tutorial.
Update: In a managed component, for example an EJB, the EntityManager is typically injected and transactions are managed by the container (i.e. you don't explicitly call begin/commit). In your case, my bet is that the EntityManager isn't successfully injected and calling any method on it results in a NPE. But that's just a guess, you need to provide more details. What is the line 39 of your EJB? How is the EntityManager annotated? What does your persistence.xml looks like? Please update your question with the relevant details.
Also, you dont need to write begin and commit transactions again.Like this :
em.getTransaction().begin();
em.getTransaction().commit();
if only you are using container managed Entity Managers because it is automatically done by the container.
I guess it is not retrieving the values of from the parameters inserted in the constructor which leads to a NullPointerExpception. It is better if you use voter.setPassword(password); for example to pass in values into the Voter entity. Also check if the values are empty.
Pascal is right you can do it that way. If you want to use the named queries you can do it like this:
Write a method that takes the value(s) to be set and use this.
Query q = em.createNamedQuery("NamedQueryXYZ").setParameter("parameter name", valueToSet)
Parameter name would be using your example "password" or "attribute" basically whatever follows the colon.
I am fairly new to JPA, JSF and all that jazz but I hope this helps.
if you re using the entity manager means you re handling transaction with JTA, so the entity manager will be handled by the container, you re not be able to use
em.getTransaction().begin();
em.getTransaction().commit();
em.getTransaction() it s an entity transaction which will be handled by JTA .
You ll need to directly use the persist(), as you have the entitymanager, and you re data will be addedd.
If you want to use the query it s always possible in a a en.createQuery ...
But I don t know if it can be use as a named query.