如何使用CreateNativeQuery从SQL数据库值中查询单个值?

时间:2021-06-11 15:41:43

using a CRUD and want o access a certain value in the databse. what I tried is:

使用CRUD并希望访问数据库中的某个值。我试过的是:

Query query = em.createNativeQuery("select o from Table o where o.IDfield= '938'"); 
Table o = (Table)query.getSingleResult();

but this fails.

但这失败了。

Any suggestions?

1 个解决方案

#1


0  

Your select looks like a jpql query so it won't work when passed directly to the database as a native query. You can use the createQuery method instead. Even better would be to use a named parameterized query declared on your entity like this:

您的选择看起来像一个jpql查询,因此当作为本机查询直接传递给数据库时它将无法工作。您可以使用createQuery方法。更好的方法是使用在您的实体上声明的命名参数化查询,如下所示:

@Entity
@NamedQueries({@NamedQuery(name="MyEntity.findById", query="select o from MyEntity o where o.IDfield = :id"})
public class MyEntity {
    @Id
    private String IDfield;
}

...

MyEntity entity = (MyEntity)em.createNamedQuery("MyEntity.findById").setParameter("id", "938").getSingleResult();

#1


0  

Your select looks like a jpql query so it won't work when passed directly to the database as a native query. You can use the createQuery method instead. Even better would be to use a named parameterized query declared on your entity like this:

您的选择看起来像一个jpql查询,因此当作为本机查询直接传递给数据库时它将无法工作。您可以使用createQuery方法。更好的方法是使用在您的实体上声明的命名参数化查询,如下所示:

@Entity
@NamedQueries({@NamedQuery(name="MyEntity.findById", query="select o from MyEntity o where o.IDfield = :id"})
public class MyEntity {
    @Id
    private String IDfield;
}

...

MyEntity entity = (MyEntity)em.createNamedQuery("MyEntity.findById").setParameter("id", "938").getSingleResult();