问题!使用数据访问对象(dao)和JPA不提取实体数据?

时间:2014-06-16 11:39:16

标签: java jsp jpa dao

我有这个Dao根据用户ID获取事件。它返回事件对象。

public enum Dao {
INSTANCE;
public List<EventsDetail> getevents(String userId) {
    EntityManager em = EMFService.get().createEntityManager();
    Query q = em.createQuery("select t from EventsDetail t where t.MemberId = :userId");
    q.setParameter("userId", userId);
    @SuppressWarnings("unchecked")
    List<EventsDetail> events = q.getResultList();
    return events;
  }
}

这里我有这个调用dao的jsp页面,因为我导入了dao类。在这里我使用了try和catch来抛出异常,我得到空指针异常。

<%
Dao dao = Dao.INSTANCE;
UserService userService = UserServiceFactory.getUserService();
User user = userService.getCurrentUser();
List<EventsDetail> events = new ArrayList();
if (user != null) {
  pageContext.setAttribute("user", user);
  events = dao.getevents(user.getUserId());
    %>
}....

 <% 
try{
for (EventsDetail event : events) {
    pageContext.setAttribute("title", event.Title());
    pageContext.setAttribute("place", event.getPlace());
    pageContext.setAttribute("category", event.Category());
    pageContext.setAttribute("cdate", event.Cdate());
 %>
            <div class="row">
                <span class="r1"><%=count%></span>
                <span class="r2">${fn:escapeXml(cdate)}</span>
                <span class="r2">${fn:escapeXml(place)}</span>
                <span class="r3">${fn:escapeXml(title)}</span>
                <span class="r4">${fn:escapeXml(category)}</span>

            </div>
 <% }  
          } catch (Exception e)
          {
            System.out.println("Exception:" + e);
          }
             %>

问题是我只从数据存储区获取空数据,数据已经存在于数据存储区中。

1 个答案:

答案 0 :(得分:1)

我认为问题出在你的getEvents方法上。

您可以尝试执行以下操作:

public enum Dao {
INSTANCE;
public List<EventsDetail> getevents(String userId) {
    EntityManager em = EMFService.get().createEntityManager();
    Query q = em.createQuery("select t from EventsDetail t where t.MemberId = " + userId);
    q.setParameter("userId", userId);
    @SuppressWarnings("unchecked")
    List<EventsDetail> events = q.getResultList();
    return events;
  }
}

并确保传递正确的userId。