【问题标题】:JPA entitymanager run native sql query to get everything out from a tableJPA entitymanager 运行本机 sql 查询以从表中获取所有内容
【发布时间】:2015-02-21 18:42:10
【问题描述】:

我需要做的是运行一段原生 sql 查询来选择所有内容并获取 从特定表中取出数据。

我的应用是一个基于 Spring Hibernate 的网络应用。这是我的代码:

DAOserviceImpl:

@Service
public class ItemServiceImpl implements ItemService {

    @PersistenceContext
    EntityManager em;

    @Transactional
    public void addItem(Item item) {
        em.persist(item);
    }

    @Transactional
    public List<Item> iosADVsearchResults(String itemCode) {
        //run native query with jpa
        List<Item> itemList = (List<Item>)em.createQuery("SELECT * FROM item itemcode='" + itemCode + "'")
            .getResultList(); 
        return itemList;
    }
}

但我最终得到的是这个错误:

HTTP 状态 500 - 请求处理失败;嵌套异常是 java.lang.IllegalArgumentException:org.hibernate.hql.ast.QuerySyntaxException:意外令牌:= 第 1 行附近,第 35 列 [SELECT itemcode FROM item itemcode='ll3369']

我正在关注本教程:http://www.oracle.com/technetwork/articles/vasiliev-jpql-087123.html

请帮忙,任何代码示例都会有所帮助。

【问题讨论】:

    标签: sql database jpa entitymanager hibernate-criteria


    【解决方案1】:

    em.createQuery() 需要一个用 JPQL 而不是 SQL 编写的查询(有关一些信息,请参阅 this)。对于 SQL 查询,使用em.createNativeQuery()

    List<Item> itemList = (List<Item>)em.createNativeQuery("SELECT * FROM item WHERE itemcode='" + itemCode + "'", Item.class).getResultList();
    

    【讨论】:

      【解决方案2】:

      如果您使用 JPA,则获取所有记录的查询应如下所示:

      List<Item> itemList = (List<Item>) em.createQuery("SELECT i FROM item where  itemcode=?1)
                                          .setParameter(1, itemcode)
                                          .getResultList();
      

      这将返回与参数 itemcode 匹配的所有记录 ..

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-09-19
        • 2022-11-26
        • 1970-01-01
        • 2011-09-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-11
        相关资源
        最近更新 更多