I use spring and hibernate. The following situation occured and I don't know if it's really possible to implement. Will appreciate any help.
For example, there is a hibernate entity
@Entity
public class TestEntity {
private String field1;
private String field2;
private String specField;
@Column(name = "field1")
public String getField1() {
return field1;
}
@Column(name = "field2")
public String getField2() {
return field2;
}
public String getSpecField() {
return (field1 != null ? field1 : field2);
}
}
And I need the value for specField to be generated by SQL query and not by java code. Something like this
@Entity
public class TestEntity {
private String field1;
private String field2;
private String specField;
@Column(name = "field1")
public String getField1() {
return field1;
}
@Column(name = "field2")
public String getField2() {
return field2;
}
@Query(value= "COALESCE(field1, field2)")
public String getSpecField() {
return specField;
}
}
I was told that there should be ability to do so. But didn't find anything that approves this.
it's not actually important what exactly query does. I need that specField will be taken by some query and not by java code. Is it possible?
Thanks for help.
UPDATE Thanks to @premkumar, for advicing to use @Formula So now I have
@Entity
public class TestEntity {
private String field1;
private String field2;
private String specField;
@Column(name = "field1")
public String getField1() {
return field1;
}
@Column(name = "field2")
public String getField2() {
return field2;
}
@Formula("COALESCE(field2, field2)")
public String getSpecField() {
return (field1 != null ? field1 : field2);
}
}
But app fails to start on bean initialization with NullPointerException at org.springframework.orm.hibernate3.LocalSessionFactoryBean.newSessionFactory
I tried also the following:
Put formula above "private String specField" - app started, but hibernate failed on could not find spec_field in database
Put @Formula and @Transient on getter - app started, no errors, but specField is always null. It looks like hibernate totally ignored it