I am using hibernate 4.1.9.
My code is
#Transient
private String ldapIdTemp;
package is
import javax.persistence.Transient;
Still in hibernate query, it is not working and putting the attribute in the query.
part of query snippet (assetasset0_.ldapIdTemp as ldapIdTemp16_0_, )
I am not sure what I am doing wrong.
Can you try creating setter and getter for the field and annotate the get method with #Transient, as follows:
private String ldapIdTemp;
#Transient
public String getLdapIdTemp() {
return ldapIdTemp;
}
public void setLdapIdTemp(String ldapIdTemp) {
this.ldapIdTemp = ldapIdTemp;
}
Much depends on how you "integrated" this field in your Entity or class hierarchy. Moreover, field vs. property-access could cause an issue for your setting. See this post for a detailed explanation.
In your case, I could imagine that you either:
mixed field and property-access in your entity inheritance strategy
use XML-based configuration for Hibernate in your application.
In both cases the JPA 2.0/2.1 specification clearly states in Section 2.3.1:
It is an error if a default access type cannot be determined and an access type is not explicitly specified
by means of annotations or the XML descriptor. The behavior of applications that mix the placement of
annotations on fields and properties within an entity hierarchy without explicitly specifying the
Access annotation is undefined.
Please check that your persistent Entity classes have either field OR property-based annotations.
Check the #Transient annotation fully qualified name.
It can be from either,
org.springframework.data.annotation.Transient or javax.persistence.Transient.
Try to use javax.persistence.Transient.
Related
My web application uses struts2-json-plugin-2.2.1
I have an action that exposes an object loaded from DB (through hibernate).
This object contain a java.util.Date field that is so annotated:
#JSON(format = "dd-MM-yyyy")
#Column(name = "DATA_CREAZIONE", nullable = false)
public Date getDataCreazione() {
return this.dataCreazione;
}
Instead of getting:
"dataCreazione":"15-02-2013"
I get this:
"dataCreazione":"2013-02-15T16:51:06"
In debug I notice that the org.apache.struts2.json.JSONWriter class doesn't find any annotation over the getDataCreazione method and that the proxy class is of the "$$_javassist" type rather than "$$EnhancerByCGLIB$$" as other cases...
In the same application I have a lot of this situations and the annotation works fine.
I don't understand what is the problem (or the difference) with other classes.
Do you have any suggestions?
You didn't specify name of the annotation attribute. By default annotations with empty names are not deserialized. For further references take a look at the Apache docs.
btw I confirm the origin of my problem. As I said before it resides in the proxy class that are used. In my case - if I load the object (through hibernate) then the proxy used is $$_javassist - if I get the object (through hibernate) then the object isn't proxied and then JSonWriter can resume the annotation -> so it's able to format as I have annotated –
I'm trying to convert a legacy application to hibernate.
I have an entity that has a field, which should be instantiated to object instance based on a fully qualified name string in a database.
Consider the example below - if I have somePackageName.FirstClass in a database the someObject field should be an instance of FirstClass.
I guess I could use property access and persist / retrieve a string but that doesn't look very elegant to me.
I cannot use #PostLoad etc. - I'm using pure hibernate with spring (not JPA) - these annotations get ignored.
I know for example in MyBatis one can register a custom handler for field. Would anything similar be available in Hibernate?
I'm new to hibernate so I'm not really sure what the options are.
#Entity
class SomePersistentClass{
private SomeInterface someObject;
}
class FirstClass implements SomeInterface{
}
class SecondClass implements SomeInterface{
}
You can use JPA features such as #PostLoad, etc callbacks simply by enabling the proper Hibernate event listeners. Check the Hibernate EntityManager guide for details.
But this one is even easier. This is the role of a Type in Hibernate. First, you'll have to write an implementation of org.hibernate.type.Type or org.hibernate.usertype.UserType and specify that in #Type( type=... ) that handles the conversions (lots of web resources about writing custom Hibernate types). Then annotate your 'someObject' attribute with #Type( type="your.custom.TypeImpl" )
I have a class to map a table for using hibernate. There are some variable I want to ignore for mapping to use as constant. And I want to load constant value from properties so I code it like this:
#Transient
#Value("${something.value}")
private int MY_VALUE;
But, the value of MY_VALUE is always set to 0. Can't I use #Transient annotation with #Value annotation? Or I missed something else?
Those two annotations belong in different domains.
#Transient belongs to an entity, while #Value belongs to Spring Beans. Entities are managed by JPA / Hibernate, Spring Beans are managed by Spring. It is not a good idea to mix the two.
You could achieve this by using the #Configurable annotation and AspectJ compilation or Load Time Weaving, but I would strongly advise against such a hack. Use a Spring Bean to hold a #Value, not an entity!
You use #Value to specify a property value to load when Spring creates the bean.
However, if you are using Hibernate to load data from a database, Spring is not instantiating these classes for you. So your #Value annotation has no effect.
I would suggest injecting the #Value into the DAO that loads these entities from Hibernate, something like
public class FooDao {
#Value("...")
private int yourConfiguredValue;
public getFoo() {
Foo foo = sessionFactory.getCurrentSession().get(...);
foo.setYourValue(yourConfiguredValue);
return foo;
}
}
In my scenario I have a class Employee which has relation with class Organization.
I don't want to serialize a whole dependent object(Organization), rather serialize a single parameter of organization(e.g. orgID).
I tried following:
#Transient
#value("#{target.orgId.id}")
private UUID org_Id;
but it didnt work. So i used a simple getter mehtod instead of a field variable as follows:
#JsonIgnore
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "orgID")
private Organization orgId;
#JsonProperty("orgId")
public UUID getOrg_ID() {
return orgId.getId();
}
it worked and i got simple orgId field in response serialized by Jackson.
It seems Jackson work with getters without considering a field variable is declared or not corresponding to that getter method.
According to my JPA 2.0 book (and online documentation), I should be able to mix field and property access within a single entity or entity hierarchy. The annotation of #Access on the class specifies the default access. When placed on a field or property getter #Access can specify that the default should be overridden for this field.
#Entity
#Access(AccessType.FIELD)
Class Foo {
#Id
int id;
#Column(name = "myfield")
String myField;
#Column(name = "myProp")
#Access(AccessType.PROPERTY)
public int getMyProp () {
return 3;
}
public void setMyProp (int p) {
// do nothing
}
}
This class should result in a table with three columns. However it doesn't with Hibernate...the "myProp" column is missing from the table because apparently Hibernate takes its field vs property cue from the entity ID and runs with it...totally ignoring the JPA spec with regards to #Access.
Can anyone confirm this or did I make a stupid mistake somewhere?
I've seen similar (not the same but similar) issues like HHH-5004 so I wouldn't exclude that this might be a new one (the TCK doesn't seem exhaustive). But what version of Hibernate are you using? Did you try with the latest?
Based on the docs your code seems to be right. The #Access(AccessType.FIELD) annotation on top is unnecessary, because you annotated the field int id;
This tells hibernate to use field access. I tried a very similar example with annotations and xml config mixed. This leads to the same behaviour, so it's probably a bug in hibernate.
I tried with hibernate 3.5.3
I'm observing a very strange behaviour with an entity class and loading an object of this class whith JPA (hibernate entitymanager 3.3.1.ga). The Class has a (embedded) field, that is initialized in the declaration. The setter of the field implements a null check (i.e. would throw an exception when a null value is set).
...
#Entity
public class Participant extends BaseEntity implements Comparable<Participant> {
...
#Embedded
private AmsData amsData = new AmsData();
public void setAmsData(AmsData amsData) {
Checks.verifyArgNotNull(amsData, "amsdata");
this.amsData = amsData;
}
...
}
When I get this object with JPA, the field is null, if there is no data in the db for the fields specified in the embedded object.
...
public class ParticipantJpaDao implements ParticipantDao {
#PersistenceContext
private EntityManager em;
#Override
public Participant getParticipant(Long id) {
return em.find(Participant.class, id);
}
...
}
I debugged the process with a watchpoint on the field (should halt when the field is accessed or modified), and I see one modification when the field is initialized, but when I get the result from the find call, the field is null.
Can anybody explain, why this is so? How can I ensure, that the field is not null, also when there is no data for the embedded object's fields in the db (besides from setting it manually after the find call).
The JPA specification doesn't explicitly say how to handle a set of columns representing an embeddable object which are all empty. It could signal a null reference, or an object instance with all null fields. Hibernate chooses a null reference in this case, though other JPA implementations may pick the later.
The reason why your setter is never called is because Hibernate is accessing your field via reflection, bypassing the setter you implemented. It's doing this because you utilize field-based access rather than property-based access.
Chad's answer would provide the functionality you're looking for, but there is a caveat (see below).
"...The persistent state of an entity
is accessed by the persistence
provider runtime[1] either via
JavaBeans style property accessors or
via instance variables. A single
access type (field or property access)
applies to an entity hierarchy. When
annotations are used, the placement of
the mapping annotations on either the
persistent fields or persistent
properties of the entity class
specifies the access type as being
either field- or property-based access
respectively..." [ejb3 persistence
spec]
so by moving the annotations down to the setter, you are telling JPA that you want to used property-based access instead of field-based access. You should know, however, that field-based access - as you currently implement it - is preferred over property-based access. There are a couple reasons why property-based access is discouraged, but one is that they you're forced to add getters and setters for all of your persistent entity fields, but you may not want those same fields susceptible to mutation by external clients. In other words, using JPA's property-based access forces you to weaken your entity's encapsulation.
The answer is (thanks to rcampell), if all data of an embedded object is null (in the db), the embedded object will also be null, although when it is initialized in the declaration. The only solution seems to be, setting the object manually.
#Override
public Participant getParticipant(Long id) {
Participant participant = em.find(Participant.class, id);
if(participant != null && participant.getAmsData() == null)
{
participant.setAmsData(new AmsData());
}
return participant;
}
Still feels strange to me ...
Well, it's possible that your object could be getting constructed twice behind the scenes. JPA implementations will usually set those fields directly.
I think you need to put the annotations on the Getters and setters themselves if you want them to be used. See this answer:
Empty constructors and setters on JPA Entites
It's 2018 now and I had the same problem in a similiar situation.
Using your code as example, I solved the problem like this:
#Entity
public class Participant extends BaseEntity implements Comparable<Participant> {
...
#Embedded
private AmsData amsData = new AmsData();
public void getAmsData(AmsData amsData) {
Checks.verifyArgNotNull(amsData, "amsdata");
this.amsData = amsData;
}
public AmsData getAmsData(){
if(amsData == null){
amsData = new AmsData();
}
return amsData;
}
...
}
I was having the same problem , I just added getters and setters using #Getter and #setter lombok annotations and it started working