Access field with @Transient in JPA query

♀尐吖头ヾ 提交于 2019-12-12 15:54:36

问题


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!


回答1:


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.




回答2:


@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);



回答3:


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




回答4:


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?



来源:https://stackoverflow.com/questions/13154535/access-field-with-transient-in-jpa-query

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!