Reputation: 23072
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?
Upvotes: 3
Views: 5716
Reputation: 9
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.
Upvotes: 0
Reputation: 140021
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;
}
}
Upvotes: 4
Reputation: 299148
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!
Upvotes: 6