从servlet启动嵌入式Neo4j

时间:2013-05-11 20:02:48

标签: java servlets neo4j

我使用此代码从mysql数据库创建了公司节点

public class EnterCompaniesToNeo4j {


    public static void main(String[] args) throws SQLException, ClassNotFoundException
    {

        ConnectionStrings c=new ConnectionStrings();
        String CONN_STRING=c.getConnString();
        String  USERNAME=c.getUsername();
        String  PASSWORD=c.getPassword();
        Connection conn=null;
        PreparedStatement stmt=null;
        int counter=0;
        ResultSet rs=null;  
       Class.forName("com.mysql.jdbc.Driver");
       conn=DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD); 


GraphDatabaseService graphDB = new GraphDatabaseFactory().newEmbeddedDatabase("build\\web\\NEO4J databases\\db1"); 
Transaction tx = graphDB.beginTx();
Node n = null;
try
{



  stmt=conn.prepareStatement("select * from companies where node_id IS NULL", ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
         // stmt.setString(1, "100641318");

          rs=stmt.executeQuery();  
          while(rs.next())
          {
               // deo gde se kreira nod
   counter=counter+1;
n = graphDB.createNode();

n.setProperty( "taxnumber", rs.getString("tax_number"));
n.setProperty( "name", rs.getString("name"));
n.setProperty( "email", rs.getString("email"));
long br;
br=n.getId();
rs.updateLong("node_id",br);
rs.updateRow();
//System.out.println(n.getProperty("taxnumber"));
//System.out.println(n.getId()+"");
System.out.println(rs.getString("name"));


          }


tx.success();
}
catch ( Exception e )
{
tx.failure();
}
finally
{
tx.finish();
stmt.close();
rs.close();
conn.close();
}
//ExecutionEngine engine = new ExecutionEngine( graphDB );
//ExecutionResult result = engine.execute( "start n=node(2) return n, n.taxnumber,n.name" );//vracanje noda 1
//ExecutionResult result = engine.execute( "START n = node(*) DELETE n" ); //brisanje svih nodova
//System.out.println(result.toString());
System.out.println(""+counter);
graphDB.shutdown();

    }

}

现在我想让用户在登录后插入关系,我是这样从servlet做的

public class InputDebtDataToNeo4j extends HttpServlet {

 GraphDatabaseService graphDB = new GraphDatabaseFactory().newEmbeddedDatabase("build\\web\\NEO4J databases\\db1"); 

 Transaction tx = graphDB.beginTx();

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

   ArrayList<InputData> l111 = new ArrayList<InputData>();
   ArrayList<InputData> l222 = new ArrayList<InputData>();

  HttpSession session=request.getSession(true); 

  l111= (ArrayList<InputData>) session.getAttribute("hasdata");
  l222=(ArrayList<InputData>) session.getAttribute("hasnotdata");
  //put ka Neo4j bazi



  long mynodenumber;
  mynodenumber = Long.parseLong(session.getAttribute("node_id").toString());

        try {



           for (InputData element : l111)
           {
ExecutionEngine engine = new ExecutionEngine( graphDB );
ExecutionResult result = engine.execute( "START a=node("+mynodenumber+"), b=node("+element.getNodeidnumber()+") CREATE a-[r:OWE{amount:"+element.getDebtamount()+"}]->b RETURN r" );//vracanje noda 1

out.println("Relacija "+result.toString()+"</br>");            
out.println("Taks broj "+element.getTaxnumberdata()+"</br>");
out.println("Node Broj "+element.getNodeidnumber()+"</br>");
out.println("Iznos duga "+String.valueOf(element.getDebtamount())+"</br>");
out.println("Moj node broj "+mynodenumber+"</br>");
           }




            //response.sendRedirect("DebtSolutions.jsp");
tx.success();           
        } 
        catch(Exception e )
        {
   tx.failure();
   out.println(e.toString());
        }
        finally { 
          tx.finish();
         graphDB.shutdown();
            out.close();
        }
    }

结果我收到此错误消息

type Exception report

message Error instantiating servlet class servlets.InputDebtDataToNeo4j

description The server encountered an internal error that prevented it from fulfilling this request.

exception

javax.servlet.ServletException: Error instantiating servlet class servlets.InputDebtDataToNeo4j
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:947)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1009)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1852)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    java.lang.Thread.run(Thread.java:722)

root cause

java.lang.IllegalStateException: Database locked.
    org.neo4j.kernel.InternalAbstractGraphDatabase.create(InternalAbstractGraphDatabase.java:289)
    org.neo4j.kernel.InternalAbstractGraphDatabase.run(InternalAbstractGraphDatabase.java:227)
    org.neo4j.kernel.EmbeddedGraphDatabase.<init>(EmbeddedGraphDatabase.java:79)
    org.neo4j.graphdb.factory.GraphDatabaseFactory$1.newDatabase(GraphDatabaseFactory.java:70)
    org.neo4j.graphdb.factory.GraphDatabaseBuilder.newGraphDatabase(GraphDatabaseBuilder.java:205)
    org.neo4j.graphdb.factory.GraphDatabaseFactory.newEmbeddedDatabase(GraphDatabaseFactory.java:56)
    servlets.InputDebtDataToNeo4j.<init>(InputDebtDataToNeo4j.java:30)
    sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    java.lang.reflect.Constructor.newInstance(Constructor.java:525)
    java.lang.Class.newInstance0(Class.java:372)
    java.lang.Class.newInstance(Class.java:325)
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:947)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1009)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1852)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    java.lang.Thread.run(Thread.java:722)

我应该在servlet中做些什么来使它工作......

1 个答案:

答案 0 :(得分:1)

您可能希望将图表数据库作为单例。

因此,要么在servlet中声明GraphDatabaseService静态(请记住每个请求创建一个新的servlet实例(或者至少有线程/池的数量)。

或者您已将其注入,或者将其存储在Application-Context中。或者使用在启动时创建图数据库的ServletContextListener,并在关闭时正确关闭它。