Access field with @Transient in JPA query

2019-07-04 04:06发布

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!

标签: jpql
4条回答
Animai°情兽
2楼-- · 2019-07-04 04:12

Either you add column locationIdentifier in your db table and unmark it as Transient, or you cannot use this column in queries.

查看更多
We Are One
3楼-- · 2019-07-04 04:16

@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);
查看更多
forever°为你锁心
4楼-- · 2019-07-04 04:19

You cannot use a transient Member in a query. Thats makes no sense! JPQL is used to get something from the database, and if there is no "locationIdentifier" you can't add this to your where-clause. What would you expect in SQL if there is no such database-field?

查看更多
聊天终结者
5楼-- · 2019-07-04 04:24

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.

查看更多
登录 后发表回答