如何从数据库中获取数据?

时间:2014-06-28 01:23:04

标签: maven jsf jpa glassfish-4

我遇到从数据库(JavaDB)获取数据的问题。 确切地说,我认为错误发生在GetAllUsersFromTable方法的UserBean类中。 也许是因为我从数据库中错误地获取了实体。我试过写方法 GetAllUsersFromTable以几种不同的方式,但它不能很好地工作。

我的项目运行良好,直到我不尝试从数据库中获取数据。索引页面显示正确,usersForm也正确显示,当我点击提交按钮时显示错误。在页面上显示错误我应该看到所有用户的表。

我使用Glassfish 4.0并且内置了JavaDB。我不使用任何IDE,如Eclipse或Netbeans。我的项目由Maven管理。我还使用JSF CDI ManagedBeans和JPA。

请问我任何问题。我真的很想解决这个问题。

我收到此错误:


javax.faces.el.EvaluationException: java.lang.NullPointerException
    at   
javax.faces.component.MethodBindingMethodExpressionAdapter.invoke
  (MethodBindingMethodExpressionAdapter.java:101)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    at javax.faces.component.UICommand.broadcast(UICommand.java:315)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at   
    org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
    at  

 org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
    at 
org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
    at   
org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.
    run(WorkerThreadIOStrategy.java:135)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.
    doWork(AbstractThreadPool.java:564)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
    at java.lang.Thread.run(Thread.java:744)
Caused by: java.lang.NullPointerException
    at com.test.UserBean.getAllUsersFromTable(UserBean.java:119)
    at com.test.UserBean$Proxy$_$$_WeldClientProxy.getAllUsersFromTable(Unknown Source)
    at com.test.AllUsersBean.add(AllUsersBean.java:43)
    at com.test.AllUsersBean$Proxy$_$$_WeldClientProxy.add(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at javax.el.ELUtil.invokeMethod(ELUtil.java:326)
    at javax.el.BeanELResolver.invoke(BeanELResolver.java:536)
    at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:256)
    at com.sun.el.parser.AstValue.invoke(AstValue.java:269)
    at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
    at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
    at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at 
 javax.faces.component.MethodBindingMethodExpressionAdapter.invoke
(MethodBindingMethodExpressionAdapter.java:87)
    ... 35 more

UserBean.java文件中的第119行是

user.setId(v.getId());


package com.test;

/*Importing required java libraries */
import java.io.Serializable;
import javax.inject.Named;
import javax.inject.Inject;  
import javax.enterprise.context.ApplicationScoped;
import java.util.ArrayList;
import java.util.List;

@Named("appBean")
@ApplicationScoped
public class AllUserssBean implements Serializable {

   private List<UserBean> users;
   private int id;

   @Inject
   private UserBean subBean;

   public AllUsersBean(){
      users = new ArrayList<UserBean>();
      id = 0;
   }

   public String add() throws Exception {
        subBean.addUserToTable();
        ++id;
        users.add(subBean.getAllUsersFromTable(id));
    subBean.reset();
    return "submit";
   }

   /*Get total number of users */
   public int getTotal(){ return users.size(); }

   public List<UserBean> getUsers() { return users; }
   public void setUsers(List<UserBean> users) { this.users = users; }   
}


package com.test;

/*Importing required java libraries */
import java.io.Serializable;
import javax.inject.Named; 
import javax.enterprise.context.SessionScoped;
import java.sql.*;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceUnit;
import javax.transaction.UserTransaction;
import javax.transaction.RollbackException; 
import javax.persistence.*;
import java.util.List;
import java.util.*;

@Named("subBean")
@SessionScoped
public class UserBean implements Serializable{

   @PersistenceUnit(unitName="testMe")
   private EntityManagerFactory emf;

   @Resource
   private UserTransaction transaction;

   private int id; 
   private String fname;
   private String lname; 

   public UserBean() {
     this.fname = "";
     this.lname = "";
   }

   public int getId() { return id; }
   public void setId(int id) { this.id = id; }
   public String getFname() { return fname; }
   public void setFname(String fname) { this.fname = fname; }
   public String getLname() { return lname; }
   public void setLname(String lname) { this.lname = lname; }
   public UserTransaction getTransaction() { return transaction; }
   public void setTransaction(UserTransaction transaction) { this.transaction = transaction; }

   public void addUserToTable() throws Exception
        {

        EntityManager manager = emf.createEntityManager();
         boolean commit;
    try{
       transaction.begin();
           manager.joinTransaction();   
       commit = false;
        try {
        User v = null;
        v.setFname(fname);  
        v.setLname(lname);
        manager.persist(v);
        transaction.commit();
        commit = true;
         }finally {
                if(commit==false){
              transaction.rollback();
                }
         }

    } catch(Exception e) { 
             e.printStackTrace();
        }finally {     
         manager.close();
    }
   }


   public UserBean getAllUsersFromTable(int id) {
        EntityManager manager = emf.createEntityManager();
        User v = null;
        UserBean user = new UserBean();
    try {
        v = manager.find(User.class, id);
            user.setId(v.getId());
        user.setFname(v.getFname());
            user.setLname(v.getLname());
        }finally {
            manager.close();
        }   
    return user; 
   } 

  /*
   public List getAllUsersFromTable() throws javax.transaction.SystemException, 
   javax.transaction.NotSupportedException {
        EntityManager manager = emf.createEntityManager();
        User v = null;
        List<User> results;
    try {
            TypedQuery<User> query = 
                 manager.createQuery("SELECT * FROM User", User.class);
        results = query.getResultList();
        }finally {
            manager.close();
        }   
    return results; 
   } */

   /*reset method is used to set all the parameters to null and
     to 0. This method is called after user was added to the
     list of users */
   public void reset(){
    setFname("");
        setLname("");
   }
}


package com.test;

/*Importing required java libraries */
import java.io.Serializable;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.EntityManager;
import javax.persistence.Entity;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;


@Entity
public class User implements Serializable{

   @Id 
   @GeneratedValue 
   private int id; 
   private String fname;
   private String lname;

   public User() {}

   public int getId() { return id; }
   public void setId(int id) { this.id = id; }
   public String getFname() { return fname; }
   public void setFname(String fname) { this.fname = fname; }
   public String getLname() { return lname; }
   public void setLname(String lname) { this.lname = lname;} 
}

的index.xhtml

<!DOCTYPE html  
     PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xml:lang="en" lang="en"
  xmlns="http://www.w3.org/1999/xhtml" 
  xmlns:f="http://java.sun.com/jsf/core"
  xmlns:h="http://java.sun.com/jsf/html"
  xmlns:ui="http://java.sun.com/jsf/facelets">

<h:head><title></title></h:head>
<h:body>
   <div style="text-align:center">
       <h1>Hello</h1>
       <p><h:link value="User Form" outcome="userForm"/></p>
       <p><h:link value="All users List" outcome="allUsersList"/></p>
   </div>
</h:body>
</html>

userForm.xhtml

<!DOCTYPE html  
     PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xml:lang="en" lang="en"
  xmlns="http://www.w3.org/1999/xhtml" 
  xmlns:f="http://java.sun.com/jsf/core"
  xmlns:h="http://java.sun.com/jsf/html"
  xmlns:ui="http://java.sun.com/jsf/facelets">

<h:head>
    <h:outputStylesheet library="css" name="template.css"/>
    <title>User Form page</title>
</h:head>
<h:body>
    <h:form id="submissionForm">
    <table border="0">

        <tr>
        <td><h:outputLabel for="fname" value="First name:"></h:outputLabel></td>
    <td><h:inputText id="firstName" value="#{subBean.fname}" maxlength="30" 
           requiredMessage="Please enter first name!" validatorMessage="First 
               name can include only letters. You can't live it empty!" > 
            <f:validateRegex pattern="[a-zA-Z]{1,30}"></f:validateRegex>
            </h:inputText></td>
        <td><h:message for="firstName" style="color:red;"></h:message></td>
        </tr>

        <tr>
        <td><h:outputLabel for="lname" value="Last name:"></h:outputLabel></td>
    <td><h:inputText id="lastName" value="#{subBean.lname}" maxlength="30" 
           requiredMessage="Please enter last name!" validatorMessage="Last 
               name can include only letters. You can't live it empty!" > 
            <f:validateRegex pattern="[a-zA-Z]{1,60}"></f:validateRegex>
            </h:inputText></td>
        <td><h:message for="lastName" style="color:red;"></h:message></td>
        </tr>

    <tr>
    <td colspan="3">
<h:commandButton id="submit" value="Submit" action="#{appBean.add()}" 
       style="float:right;margin-right:10px;"/>
    </td>
        </tr>

    </table>
        </h:form>  
</h:body>
</html>

allUsersForm.xhtml

<!DOCTYPE html  
     PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xml:lang="en" lang="en"
  xmlns="http://www.w3.org/1999/xhtml" 
  xmlns:f="http://java.sun.com/jsf/core"
  xmlns:h="http://java.sun.com/jsf/html"
  xmlns:ui="http://java.sun.com/jsf/facelets">

<h:head>
<title>List of All Users page</title>
</h:head>
<h:body>
 <h:form id="AllUsersListForm">  

  <h2><h:outputText value="The next election date: #{msgs.date}"/></h2><p></p>

  <h:dataTable value="#{appBean.users}" var="v">
   <h:column>
     <f:facet name="header"><h:outputText value="Id"></h:outputText></f:facet>
     <h:outputText value="#{v.id}"></h:outputText>      
   </h:column>

   <h:column>
     <f:facet name="header"><h:outputText value="First Name"></h:outputText></f:facet>
     <h:outputText value="#{v.fname}"></h:outputText>      
   </h:column>

   <h:column>
     <f:facet name="header"><h:outputText value="Last Name"></h:outputText></f:facet>
     <h:outputText value="#{v.lname}"></h:outputText>      
   </h:column>

   <f:facet name="footer"><h:outputText 
    value="The total number of users: #{appBean.getTotal()}"></h:outputText>      
   </f:facet>
  </h:dataTable>

  <p></p>
  <p><h:link value="Home page" outcome="index"/></p>

 </h:form>   
</h:body>
</html>

persistence.xml(它位于main / resources / META-iNF / perssitence.xml下)

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" 
       xmlns="http://java.sun.com/xml/ns/persistence"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
         http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
  <persistence-unit name="test1" transaction-type="JTA">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <jta-data-source>jdbc/username</jta-data-source>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties>
      <property name="javax.persistence.schema-generation.database.action"
    value="drop-and-create"/>
      <property name="javax.persistence.schema-generation.create-source"
    value="metadata"/>
      <property name="javax.persistence.schema-generation.drop-source"
    value="metadata"/> 
     <property name="javax.persistence.jdbc.user" value="Us"/>
     <property name="javax.persistence.jdbc.password" value="Us"/>
    </properties>
  </persistence-unit>
</persistence>

当我去(localhost:4848 / common / index.jsf) 我创建JDBC连接池,一切都是正确的。当我Ping我获得成功回应 我还创建了JDBC连接资源,所有内容都设置正确

这就是我们可以用一个例子来添加数据做数据库


public class AddingDatabase 
{ 
  @PersistenceUnit(unitName="test_db”) private EntityManagerFactory emf; 
  @Resource private UserTransaction utx; 

  void doDML(MyEntity e) throws SystemException, NotSupportedException, 
  javax.transaction.RollbackException,HeuristicMixedException,HeuristicRollbackException 
  { 
    EntityManager em = emf.createEntityManager(); 
    utx.begin(); 
    em.joinTransaction(); 

    try { 
        boolean committed = false; 
        try { 
            em.persist(e); 
            utx.commit(); 
            committed = true; 
        } finally { 
            if (!committed) utx.rollback(); 
        } 
    } 
    finally { 
       em.close(); 
    } 
  } 
} 

1 个答案:

答案 0 :(得分:1)

这可能不是答案,但我需要完全格式化。

您在以下代码中做了什么?

    User v = null;
    v.setFname(fname);  
    v.setLname(lname);
    manager.persist(v);

怎么可能不生产NPE?