peter.petrov
peter.petrov

Reputation: 39457

hibernate - select/load only field

I want to add a field in a Hibernate table-mapped/entity class.

I want this field to not be mapped to an actual table column, and I want Hibernate not to try to insert/update it to the DB.

But I want to be able to load this field via a custom select in the DAO e.g. via

query.addEntity(getPersistentClass().getName());

The closest I got to this was by making the field @Transient,
but then even the select does not load its value. So this is not
quite what I need.

Is this possible at all and if so how?

Upvotes: 0

Views: 1246

Answers (3)

Pram
Pram

Reputation: 11

You can use @Column(name = "{name of column}", insertable=false, updatable = false)

Do not mark the field as @Transient.

This way this property will not be inserted or updated but can be used in selects.

Upvotes: 0

perbellinio
perbellinio

Reputation: 682

Your getter must be a bit smarter. For exemple you can the HibernateCallback interface from spring like that:

public String getName(Session session) {
 return new HibernateCallback<String>() {
  @Override
  public String doInHibernate(Session session) throws HibernateException {
   return session.createSQLQuery("SELECT NAME FROM MY_TABLE WHERE SOME_CONDITIONS").uniqueResult();
  }
 }.doInHibernate(session);
}

A better way would be to create a kind of execute method in another class where you have access to the session. With that solution you can still mark your field as @Transient.

Upvotes: 1

Amer Qarabsa
Amer Qarabsa

Reputation: 6574

Well if i understand what you are trying to do well then i think the solution like this

@Column(name = "{name of column}", updatable = false)

In this way the hibernate will not try to update this column once the object created

Upvotes: 1

Related Questions