Search code examples
javahibernatejpahibernate-mappinghibernate-annotations

Hibernate/JPA add a calculated field


I'm currently converting hibernate .hbm.xml files to annotations and have a problem very similar this Adding a calculated field on jpa + jackson

I've got a DB Table with some fields including first_name and last_name, so this fields should be persistent (this works as expected).

But now I've got a method getFullName()

  // ?????
public String getFullName() {
   return getFirstName() + " " + getLastName();
}

And I don't know which annotation I should add to the method? (tried @Transient, @Formula, @Basic, @Column, .... fullName shouldn't be persistent)

The problem is that I use the fullName to create an Order

Order.asc("fullName");

and then use it in the method

public List<Student> findAll(Session session, Order order) {
  Criteria crit = session.createCriteria(Student.class);
  if (null != order) {
    crit.addOrder(order);
  }
  return crit.list();
}

.........................................................

My current 'solution' is

 @Formula("concat(first_name,' ',last_name)")
 private String name;

 @Override
 public String getFullName() {
   return getFirstName() + " " + getLastName();
 }

But this is redundant and not really what I want.

In the end I want to use the latest Hibernate version.


Solution

  • If the fullName is not persistence then you should use the @Transient, but the javax.persistence one.

    Also, put the @Formula("concat(first_name,' ',last_name)") on the getFullName and remove the getName -> this was actually incorrect as @Transient and @Formula don't work together very well.

    Like said in the comment, you can create your own order to add to the criteria api.