0

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.

JavaMan
  • 1,142
  • 12
  • 22

1 Answers1

0

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.

Mário Fernandes
  • 1,822
  • 1
  • 21
  • 21
  • thanks for your answer, actually fullName only 'exists' as this getter, so there's no field (that 'name' what should mean fullName was just added by me because it didn't work without) I always get an "could not resolve property: fullName" error :/ Has it anything to do with the fact that name and lastname are in the superclass? – JavaMan Aug 02 '17 at 08:21
  • I understood how fullName exists and that's exactly the point. What you can also try is put the @Transient (validate that it's the correct one) either way and leave as you had in the first code, and simply create a new order, check https://stackoverflow.com/questions/31281162/how-to-order-result-of-hibernate-based-on-a-specific-order, the correct answer shows how to create your own order. – Mário Fernandes Aug 02 '17 at 08:25
  • it worked (after some minor refactoring in my project), thanks a lot! – JavaMan Aug 03 '17 at 05:04
  • Happy to hear :) – Mário Fernandes Aug 03 '17 at 11:58