简体   繁体   中英

JPA Transient property together Hibernate Criteria API

Is there possible to use @PostLoad with Hibernate Criteria API? For instance:

@Entity
public class EntityExample {

  private Integer startYear;

  private Integer startPeriod;

  @Transient
  private String start;

  @PostLoad
  private void init() {
    this.start = this.startYear.toString() + this.startPeriod.toString();
  }

  public String getStart() {
    return this.start;
  }
} 

public class DAOExample {

  public Collection<EntityExample> get(String start) {
    Session session = getSession();
    Criteria criteria = session.createCriteria(EntityExample.class, "entity");
    criteria.add(Restrictions.ne("entity.start", start));
    return criteria.list();
  }
}

When I use @Formula with Hibernate Criteria (for example: @Formula(value = "start_year::text || start_period::text") ), it works fine. But I'm trying to use @PostLoad 'cause if it's needed refactor any envolved property it will not be necessary remember change manually the value of the formula. However, using @PostLoad causes: org.hibernate.QueryException: could not resolve property: start of: com.entity.EntityExample

@Transient marks properties as not included in the database table. Now you use Criteria API to create a query containing it. This equals following query:

select * from EntityExample where start != 'start value'

This one will fail as well, because start is no column in that table. You will need to do workaound for this. Without knowing the use case it is very much impossible to think of a good workaround. The easiest one would be to just include start in the table, but I guess you had reasons to not include it right away

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM