Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access field with @Transient in JPA query

Tags:

jpql

I have an entity with a transient attribute:

@Entity
@Table(name = "asset")
public class Asset {
    @Transient
    private String locationIdentifier = "N/A";

    @SuppressWarnings("unused")
    @PostLoad
    private void onPostLoad() {
        if (location != null) {
            locationIdentifier = location.getIdentifier();
        }
    }

   [other stuffs]

   }

I tried to access locationIdentifier this way in JPA:

String sqlString = "SELECT asset FROM Asset WHERE asset.locationIdentifier = :inputstr";
Query query = entityManager.createQuery(sqlString);

But I got an error: Cannot resolve the property locationIdentifier

I want to ask how I access locationIdentifier using JPQL?

Sorry for my English. Thanks in advance!

like image 743
Cuong Le Avatar asked Oct 24 '25 15:10

Cuong Le


2 Answers

JPQL queries are transformed to SQL queries and SQL queried operate to the data in database. Marking property transient means that property is not persisted to the database and consequently it cannot be queried from the database.

like image 149
Mikko Maunu Avatar answered Oct 26 '25 21:10

Mikko Maunu


@Transient means that the attribute is totally ignored by JPA. It cannot be referred to in a query.

Simply remove @Transient and it should work.

Also, you need to provide the parameter value to the query:

String sqlString = "SELECT asset FROM Asset WHERE asset.locationIdentifier = :inputstr";
Query query = entityManager.createQuery(sqlString);
query.setParameter("inputstr", someValue);
like image 38
Glen Best Avatar answered Oct 26 '25 23:10

Glen Best



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!