即使存在,createNamedQuery也不会返回数据库中的对象

时间:2015-01-31 21:49:33

标签: java java-ee jpa

我使用createNamedQuery从数据库中收集对象时遇到问题,尽管它们在那里。

商务舱:

Article article;
        try{
            TypedQuery<Article> query = em.createNamedQuery("Article.findByTitle", Article.class);
            query.setParameter("articleTitle",title);
            article = query.getResultList().size()==1 ? query.getResultList().get(0) : null;
        } catch (NoResultException e) {
            throw new NoResultException();
        }

实体类:

@Entity
@Table(name = "article")
@XmlRootElement
@NamedQuery(name = "Article.findByTitle", query = "SELECT a FROM Article a WHERE a.articleTitle = :articleTitle")
public class Article implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Basic(optional = false)
    @Column(unique = true, name = "article_id")
    private Integer articleId;

    @Basic(optional = false)
    @Column(name = "article_title")
    private String articleTitle;

    .
    .
    .
}
控制台中的

是记录此查询:

INFO  [stdout] (default task-15) Hibernate: select article0_.article_id as article_1_0_, article0_.article_date as article_2_0_, article0_.article_short_content as article_3_0_, article0_.article_title as article_4_0_, article0_.article_url as article_5_0_ from article article0_ where article0_.article_title=?

Entitymanager正常工作,因为执行持久性或合并

1 个答案:

答案 0 :(得分:0)

尝试进行调试。你有这一行:

article = query.getResultList().size()==1 ? query.getResultList().get(0) : null;

也许您在查询中获得了多个结果,如果发生这种情况,则该行代码会使文章为空。 您也可以尝试:

List<Article> articles;
        try{
            TypedQuery<Article> query = em.createNamedQuery("Article.findByTitle", Article.class);
            query.setParameter("articleTitle",title);
            articles = query.getResultList();
        } catch (NoResultException e) {
            throw new NoResultException();
        }

getResultList()返回一个对象列表,因为你有TypedQuery,你可以初始化有文章列表