java.sql.SQLException: ORA-01008: not all variables bound - java

I am trying to insert some values into an Oracle Database 10g Express Edition retrieved through a form. Here is the code,
package com.cid_org.model;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
//import java.util.Collection;
//import java.util.Iterator;
import java.util.Map;
public class CrimeReportPOJO {
private Map<String,String[]> complaintFormData;
private Connection connection;
private int complaintID=0;
public CrimeReportPOJO(Map<String,String[]> complaintFormData,Connection connection){
this.complaintFormData = complaintFormData;
this.connection = connection;
sendCrimeData();
}
private void sendCrimeData(){
try{
String query_VICTIM_DETAILS ="INSERT INTO VICTIM_DETAILS ("+
"VICTIM_FIRST_NAME,"+
"VICTIM_MIDDLE_NAME,"+
"VICTIM_LAST_NAME,"+
"VICTIM_UID_NO,"+
"VICTIM_AGE,"+
"VICTIM_GENDER,"+
"VICTIM_ADDRESS,"+
"NEAREST_POLICE_CHOWKI,"+
"VICTIM_ZIP_CODE,"+
"VICTIM_PHONE_NO,"+
"VICTIM_EMAIL_ADDRESS,"+
"COMPLAINT_ID)"+
"VALUES(?,?,?,?,?,?,?,?,?,?,?,?)";
String query_VICTIMIZER_DETAILS ="INSERT INTO VICTIM_DETAILS ("+
"VICTIMIZER_BUSINESS_NAME,"+
"VICTIMIZER_FIRST_NAME,"+
"VICTIMIZER_MIDDLE_NAME,"+
"VICTIMIZER_LAST_NAME,"+
"VICTIMIZER_GENDER,"+
"VICTIMIZER_ADDRESS,"+
"VICTIMIZER_ZIP_CODE,"+
"VICTIMIZER_PHONE_NO,"+
"VICTIMIZER_EMAIL_ADDRESS,"+
"COMPLAINT_ID)"+
"VALUES(?,?,?,?,?,?,?,?,?,?)";
String query_COMPLAINT_DESCRIPTION ="INSERT INTO COMPLAINT_DESCRIPTION ("+
"COMPLAINT_ID,"+
"COMPLAINT_DESC,"+
"COMPLAINT_TIME_STAMP)"+
"VALUES(?,?,?)";
String query_COMPLAINT_COUNT_DETAILS ="INSERT INTO COMPLAINT_COUNT_DETAILS("+
"VICTIM_UID_NO,"+
"COMPLAINT_COUNT)"+
"VALUES(?,?)";
PreparedStatement ps = connection.prepareStatement(query_VICTIM_DETAILS);
/*Now, lets extract the data to be inserted from the map object
* and call the setString() methods on those values */
/*Collection<String[]> c = complaintFormData.values();
Iterator<String[]> it = c.iterator();
int i=1;
while(it.hasNext()){
String[] s = it.next();
ps.setObject(i, (Object)s[0] );
i++;
}*/
String[] s= complaintFormData.get("personal_first_name");
System.out.println(s[0]);
System.out.println(s);
ps.setString(1,s[0]);
s= complaintFormData.get("personal_middle_name");
ps.setString(2,s[0]);
s= complaintFormData.get("personal_last_name");
ps.setString(3,s[0]);
s= complaintFormData.get("personal_aadhar_card_no");
System.out.println(Integer.parseInt(s[0]));
ps.setInt(4,Integer.parseInt(s[0]) );
s= complaintFormData.get("personal_age");
ps.setInt(5,Integer.parseInt(s[0]));
s= complaintFormData.get("personal_gender");
ps.setString(6,s[0]);
s= complaintFormData.get("personal_address");
ps.setString(7,s[0]);
s= complaintFormData.get("police_chowki");
ps.setString(8,s[0]);
s= complaintFormData.get("personal_zip_code");
ps.setInt(9,Integer.parseInt(s[0]));
s= complaintFormData.get("personal_phone_no");
ps.setInt(10,Integer.parseInt(s[0]));
s= complaintFormData.get("personal_email_id");
ps.setString(11,s[0] );
System.out.println(s[0]);
/*To insert complaint ID into the last column COMPLAINT_ID I am
* calling getComplaintID() method which tells me whether its the
* first time I am inserting into the database or there are already
* complaints registered*/
complaintID = getComplaintID();
System.out.println(complaintID);
if(complaintID==-2){
//First time
ps.setInt(12,1);
}
else{
ps.setInt(12,++complaintID);
}
ps.executeUpdate(query_VICTIM_DETAILS);
}catch(Exception e){
e.printStackTrace(System.out);
System.out.println(e);
}
}
private int getComplaintID(){
String query = "SELECT MAX(COMPLAINT_ID)"+
"FROM COMPLAINT_DESCRIPTION";
try {
PreparedStatement ps = connection.prepareStatement(query);
ResultSet rs = ps.executeQuery();
if(rs.next()){
return rs.getInt(1);
}
else{
/*-2 indicates that the table is empty and the first
**complaint is being registered*/
return -2;
}
} catch (SQLException e) {
e.printStackTrace();
}
/*The syntax compels to return an integer value*/
return -1;
}
}
The problem is that I am getting the following exception:
java.sql.SQLException: ORA-01008: not all variables bound
The stack trace is:
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:331)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:288)
at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:743)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:216)
at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:955)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1169)
at oracle.jdbc.driver.OracleStatement.executeUpdateInternal(OracleStatement.java:1615)
at oracle.jdbc.driver.OracleStatement.executeUpdate(OracleStatement.java:1580)
at com.cid_org.model.CrimeReportPOJO.sendCrimeData(CrimeReportPOJO.java:130)
at com.cid_org.model.CrimeReportPOJO.<init>(CrimeReportPOJO.java:20)
at com.cid_org.controller.CrimeReportControllerServlet.doPost(CrimeReportControllerServlet.java:52)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:722)
Here is the VICTIM_DETAILS table:
http://i.stack.imgur.com/1TEIK.png
and here is the COMPLAINT_DESCRIPTION table,
http://i.stack.imgur.com/qxvPN.png
What I have tried: I inserted the following statement
System.out.println(complaintID);
after calling the getComplaintID() method and the output that I got on the console matches what is actually already in the table(I have cross checked it) and this indicates that the code reaches there successfully which also indicates that getComplaintID() method successfully executed.
Also, I left no value as null in the form and all the values were constraint to the table format.

Perhaps just try calling executeUpdate() with no parameters. You've already set the query string when you created the PreparedStatement.
ps.executeUpdate()

Related

UPDATE Class not found Exception (MySQL drivers) using a Servlet and Prepared Statement

So thanks to the advices bellow I changed my first approach of using statements to using Prepared Statements , I also separated the verifyUser method from the ConnectDB to put it in a new user class (which is asked in my assignment).
Now I don't any NPE anymore but another one which is the Class Not Found Exception for the MySQL JDBC Driver.
The code is as follow for the Users class :
public class Users {
private String login;
private String password;
public Users(String login, String password) {
this.login = login;
this.password = password;
}
public String getUsername() {
return login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public void setUsername(String login) {
this.login = login;
}
public boolean verifyUser(String login, String password) throws SQLException {
ConnectDB cdb = new ConnectDB();
Connection cn = DriverManager.getConnection(cdb.url, cdb.login, cdb.password);
PreparedStatement ps = cn.prepareStatement("SELECT password FROM users WHERE login LIKE ? ");
ps.setString(1,username);
ResultSet rs=ps.executeQuery();
rs.next();
if (rs.getString(2).equals(password)) {
System.out.println("TEST");
return true;
}
else
return false;
}
}
This is my ConnectDB class :
public class ConnectDB {
String url = "jdbc:mysql://localhost:3306/entreprise";
String login = "root";
String password = "kamoulox369";
Connection connection = null;
Statement st = null;
ResultSet rs = null;
PreparedStatement ps = null;
public void getConnection() {
try {
Class.forName("com.example.mysql.jdbc.Driver");
connection = DriverManager.getConnection(url, login, password);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
}
And to put it all together , where it is used in the Servlet :
private void versIndex(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
String login = request.getParameter("user");
String password = request.getParameter("password");
Users user = new Users(login,password);
ConnectDB cdb = new ConnectDB();
cdb.getConnection();
if (user.verifyUser(login, password)) {
RequestDispatcher rd = sc.getRequestDispatcher("/index.jsp");
rd.forward(request, response);
}
}
And of course the Error I'm getting :
java.lang.ClassNotFoundException: com.example.mysql.jdbc.Driver
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1309)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1138)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:291)
at com.example.ConnectDB.getConnection(ConnectDB.java:16)
at com.example.Servlet.versIndex(Servlet.java:111)
at com.example.Servlet.doPost(Servlet.java:41)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:491)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:668)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:764)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1388)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1135)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:844)
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/entreprise
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:702)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
at com.example.Users.verifyUser(Users.java:36)
at com.example.Servlet.versIndex(Servlet.java:113)
at com.example.Servlet.doPost(Servlet.java:41)
There’s nothing simple about servlets or jdbc. They’re both error-prone.
You have a concurrency issue, resource issues where you’re not closing anything (including stranding connections), and also a sql injection vulnerability.
Using static members here is disastrous. Each request executes on a different thread and they will all overwrite objects being used by other threads. Each request should be handled using local variables.
Database connections never get closed, your database will run out of connections and stop working at some point. Close all jdbc objects when you’re done with them.
Concatenating user-entered input into the sql you run allows the user to get in without a valid password or run arbitrary sql. Use PreparedStatement.

Exception java.sql.SQLException: Could not set parameter at position (...). whit mariadb

The following code throws an exception to me, by using the mariadb manager, this with mysql not passed, allows me to do executeUpdate, but not executeQuery. The truth I have sought the solution and none is my case, because I am not committing any of those mistakes. Already reinstalled java and mariadb, still does not work.Thanks!
This is my code:
package Conexion;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class mainPruebas {
public static void main(String[] args)
{
String url = "jdbc:mariadb://127.0.0.1:3306/buscadorpersonas?autoReconnect=true&useSSL=false";
String user = "root";
String pass = "2222";
Connection conexion=null;
PreparedStatement ps=null;
try {
conexion = DriverManager.getConnection(url,user,pass);
ps = conexion.prepareStatement("SELECT CODIGOCLIENTE, EMPRESA, POBLACION FROM tclientes WHERE POBLACION='?';");
ps.setString(1, "MADRID");
ResultSet rs = ps.executeQuery();
while(rs.next()) {
System.out.println(rs.getString("CODIGOCLIENTE")+" "+rs.getString("EMPRESA")+" "+rs.getString("POBLACION"));
}
conexion.close();
}catch(Exception e) {
e.printStackTrace();
}
}
}
Exception:
java.sql.SQLException: Could not set parameter at position 1 (values
was
'MADRID') Query - conn:8(M) - "SELECT CODIGOCLIENTE, EMPRESA, POBLACION FROM
tclientes WHERE POBLACION='?';"
at
org.mariadb.jdbc.internal.util.exceptions.ExceptionMapper.getSqlException(ExceptionMapper.java:192)
at org.mariadb.jdbc.MariaDbPreparedStatementClient.setParameter(MariaDbPreparedStatementClient.java:435)
at org.mariadb.jdbc.BasePrepareStatement.setString(BasePrepareStatement.java:1379)
at Conexion.mainPruebas.main(mainPruebas.java:22)
Remove the quotation marks around the question mark in your PreparedStatement
ps = conexion.prepareStatement("SELECT CODIGOCLIENTE, EMPRESA, POBLACION FROM tclientes WHERE POBLACION=?;");
REPLACE
ps = conexion.prepareStatement("SELECT CODIGOCLIENTE, EMPRESA, POBLACION FROM tclientes WHERE POBLACION='?';")
WITH
ps = conexion.prepareStatement("SELECT CODIGOCLIENTE, EMPRESA, POBLACION FROM tclientes WHERE POBLACION=?;")
NOTICE: I have removed the '' around ?

Servlet.service() for servlet in context with path threw exception eclipse

I am creating a web application with JDBC. I have added my connector .jar file to the Tomcat/lib folder. I configured context.xml in META-INF and web.xml. But when I run my application I get this error. I can not figure out the reason of it. Maybe, some connection problems. So I would be very grateful if you helped me with that.
Servlet:
#WebServlet("/QueryServlet")
public class QueryServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
DataSource ds;
/**
* #see HttpServlet#HttpServlet()
*/
public QueryServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Set the MIME type for the response message
response.setContentType("text/html");
// Get a output writer to write the response message into the network socket
PrintWriter out = response.getWriter();
Connection conn = null;
Statement stmt = null;
String url = "jdbc:mysql://localhost:3306/mysql/ebookshop";
String user = "***";
String pwd = "***";
try {
// Step 1: Create a database "Connection" object
// For MySQL
InitialContext ctx = new InitialContext();
ds = (DataSource) ctx.lookup("java:comp/env/jdbc/ebookshop");
//
//DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Class.forName("com.mysql.jdbc.Driver");
conn = ds.getConnection(); // <<== Check
// For MS Access
// conn = DriverManager.getConnection("jdbc:odbc:ebookshopODBC");
// Step 2: Create a "Statement" object inside the "Connection"
stmt = conn.createStatement();
// Step 3: Execute a SQL SELECT query
String sqlStr = "SELECT * FROM books WHERE author = "
+ "'" + request.getParameter("author") + "'"
+ " AND qty > 0 ORDER BY author ASC, title ASC";
// Print an HTML page as output of query
out.println("<html><head><title>Query Results</title></head><body>");
out.println("<h2>Thank you for your query.</h2>");
out.println("<p>You query is: " + sqlStr + "</p>"); // Echo for debugging
ResultSet rset = stmt.executeQuery(sqlStr); // Send the query to the server
// Step 4: Process the query result
int count = 0;
while(rset.next()) {
// Print a paragraph <p>...</p> for each row
out.println("<p>" + rset.getString("author")
+ ", " + rset.getString("title")
+ ", $" + rset.getDouble("price") + "</p>");
++count;
}
out.println("<p>==== " + count + " records found ====</p>");
out.println("</body></html>");
} catch (SQLException | NamingException | ClassNotFoundException ex) {
ex.printStackTrace();
} finally {
out.close();
try {
// Step 5: Close the Statement and Connection
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
context.xml:
<Context antiJARLocking="true" path="/DBConnectionPoolTest">
<Resource name="jdbc/ebookshop"
auth="Container"
type="javax.sql.DataSource"
username="***" password="v"
driverclassname="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/ebookshop"
maxactive="10"
maxidle="4" />
</Context>
pom.xml:
<display-name>ebookshop</display-name>
<resource-ref>
<description>DB Connection Pool</description>
<res-ref-name>jdbc/ebookshop</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
Eclipse output:
SEVERE: Servlet.service() for servlet [servlets.QueryServlet] in context with path [/ebookshop] threw exception [Servlet execution threw an exception] with root cause
java.lang.AbstractMethodError: com.mysql.jdbc.Connection.isValid(I)Z
at org.apache.tomcat.dbcp.dbcp2.DelegatingConnection.isValid(DelegatingConnection.java:924)
at org.apache.tomcat.dbcp.dbcp2.PoolableConnection.validate(PoolableConnection.java:282)
at org.apache.tomcat.dbcp.dbcp2.PoolableConnectionFactory.validateConnection(PoolableConnectionFactory.java:359)
at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.validateConnectionFactory(BasicDataSource.java:2316)
at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:2299)
at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:2043)
at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:1543)
at servlets.QueryServlet.doGet(QueryServlet.java:61)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)

Start embeded Neo4j from servlet

I have created companies nodes from mysql database using this code
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();
}
}
Now I want to enable users to insert relationships after they are logged in , I do it from servlet like this
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();
}
}
And for a result I get this error message
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)
What should I do in my servlet to make it work ...
You would want to have the graph database as a singleton.
So either you declare your GraphDatabaseService static in your servlet (remember there is a new servlet instance created per request (or at least as many as there are threads/pooled).
Or you have it injected, or you store it in the Application-Context. Or use a ServletContextListener that creates the graph database on startup and shuts it down correctly at shutdown.

org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

I am using struts and hibernate. I have a parent and child relation using set in hbm.
In the action I am using session.saveOrUpdate() method to save but while saving it is showing the below error. Can anyone help regardng this with explanation where I made the mistake?
Here is my hbm.file
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.model.cargo" table="cargo">
<id name="id" column="id" type="java.lang.Long">
<generator class="increment" />
</id>
<property name="cname" column="cname" />
<property name="cdate" column="cdate" />
<property name="csource" column="csource" />
<property name="cdestination" column="cdestination" />
<property name="create" column="createby" />
<property name="status" column="status" />
<set name="itemList" table="item" inverse="true"
cascade="all-delete-orphan">
<key>
<column name="id" />
</key>
<one-to-many class="com.model.Item" />
</set>
</class>
<class name="com.model.Item" table="item">
<id name="itemid" column="itemid" type="java.lang.Long">
<generator class="increment" />
</id>
<property name="itemName" column="itemname" />
<property name="weight" column="weight" />
<many-to-one class="com.model.cargo" name="cargo"
column="id" />
</class>
</hibernate-mapping>
My action
package com.action;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.plugin.HibernatePlugIn;
import com.form.cargoForm;
import com.model.cargo;
import com.model.Item;
public class CargoAction extends DispatchAction {
public ActionForward add(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
if (log.isDebugEnabled()) {
log.debug("Entering Master add method");
}
try {
cargoForm cargoForm = (cargoForm) form;
//System.out.println("ID" + cargoForm.getId());
cargo cargo = new cargo();
System.out.println("in cargo Action");
// copy customerform to model
cargoForm.reset(mapping, request);
BeanUtils.copyProperties(cargo, cargoForm);
cargoForm.reset(mapping, request);
// cargoForm.setInputParam("new");
// updateFormBean(mapping, request, cargoForm);
}
catch (Exception ex) {
ex.printStackTrace();
return mapping.findForward("failure");
}
return mapping.findForward("success1");
}
public ActionForward save(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
SessionFactory sessionFactory=null;
Session session =null;
System.out.println("in cargo Action");
try{
sessionFactory = (SessionFactory) servlet
.getServletContext().getAttribute(HibernatePlugIn.KEY_NAME);
session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
cargoForm carForm = (cargoForm) form;
cargo cargo = new cargo();
System.out.println("in cargo Action");
BeanUtils.copyProperties(cargo,carForm);
System.out.println("id"+ carForm.getId());
System.out.println("item id"+ carForm.getItemid());
Set itemset = carForm.getItemDtl();
System.out.println("size"+itemset.size());
Iterator iterator =itemset.iterator();
while(iterator.hasNext()) {
Item it = (Item)iterator.next();
System.out.println("name"+it.getItemName()); //log.debug("HERE");
it.setCargo(cargo); }
cargo.setItemList(itemset);
System.out.println("size"+ itemset.size());
session.saveOrUpdate("cargo",cargo);
tx.commit();
}catch(Exception e){
e.printStackTrace();
}
return mapping.findForward("success");
}
public ActionForward search(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
System.out.println("in cargo search Action");
SessionFactory sessionFactory = (SessionFactory) servlet
.getServletContext().getAttribute(HibernatePlugIn.KEY_NAME);
HttpSession session1 = request.getSession();
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
cargoForm cargoform = (cargoForm) form;
// System.out.println("Name"+cargoForm.getName());
cargo cargo = new cargo();
System.out.println("in cargo search Action");
// copy customerform to model
BeanUtils.copyProperties(cargo, cargoform);
String name;
String status;
String createby;
name = cargo.getCname();
status = cargo.getStatus();
createby = cargo.getCreate();
System.out.println("Name..." + name);
System.out.println("status..." + status);
System.out.println("createby..." + createby);
try {
if ((name.equals("")) && (createby.equals(""))
&& (status.equals("")))
return mapping.findForward("failure");
String SQL_QUERY = "from cargo c where c.cname=:name or c.status=:status or c.create=:createby";
Query query = session.createQuery(SQL_QUERY);
query.setParameter("name", name);
query.setParameter("status", status);
query.setParameter("createby", createby);
ArrayList al = new ArrayList();
for (Iterator i = query.iterate(); i.hasNext();) {
cargo cargo1 = (cargo) i.next();
al.add(cargo1);
System.out.println("Cargo ID is:" + cargo1.getId());
}
System.out.println("Cargo list is:" + al.size());
session1.setAttribute("clist", al);
} catch (Exception e) {
e.printStackTrace();
return mapping.findForward("failure");
}
System.out.println("search Cargo list is success");
return mapping.findForward("success");
}
public ActionForward edit(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
SessionFactory sessionFactory=null;
Session session =null;
if (log.isDebugEnabled()) {
log.debug("Entering Master Edit method");
}
try {
sessionFactory = (SessionFactory) servlet
.getServletContext().getAttribute(HibernatePlugIn.KEY_NAME);
session = sessionFactory.openSession();
Transaction transaction=session.beginTransaction();
cargoForm carForm = (cargoForm) form;
// System.out.println(carForm.getStatus());
// System.out.println(carForm.getCreate());
cargo cargo = new cargo();
BeanUtils.copyProperties(cargo, carForm);
System.out.println("In Cargo Edit "+cargo.getId());
String qstring = "from cargo c where c.id=:id";
Query query = session.createQuery(qstring);
query.setParameter("id", cargo.getId());
ArrayList all = new ArrayList();
cargo c = (cargo) query.iterate().next();
System.out.println("Edit Cargo list " + all.size());
Set purchaseArray = new HashSet();
System.out.println("Edit"+c.getItemList().size());
carForm.setItemDtl(purchaseArray);
BeanUtils.copyProperties(carForm,c);
// transaction.commit();
session.flush();
} catch (Exception e) {
e.printStackTrace();
return mapping.findForward("failure");
}
// return a forward to edit forward
System.out.println("Edit Cargo list is success");
return mapping.findForward("succ");
}
public ActionForward delete(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
try {
SessionFactory sessionFactory = (SessionFactory) servlet
.getServletContext().getAttribute(HibernatePlugIn.KEY_NAME);
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
cargoForm carForm = (cargoForm) form;
// System.out.println(carForm.getStatus());
// System.out.println(carForm.getCreate());
cargo cargo = new cargo();
BeanUtils.copyProperties(cargo, carForm);
System.out.println("In Cargo Delete "+cargo.getId());
//String qstring = "delete from cargo c where c.id=:id";
//Query query = session.createQuery(qstring);
session.delete("cargo",cargo);
// session.delete(cargo);
// session.flush();
//query.setParameter("id", cargo.getId());
//int row=query.executeUpdate();
//System.out.println("deleted row"+row);
tx.commit();
} catch (Exception e) {
e.printStackTrace();
return mapping.findForward("failure");
}
// return a forward to edit forward
System.out.println("Deleted success");
return mapping.findForward("succes");
}
}
My parent model
package com.model;
import java.util.HashSet;
import java.util.Set;
public class cargo {
private Long id;
private String cname;
private String cdate;
private String csource;
private String cdestination;
private String create;
private String status;
private Set itemList = new HashSet();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
public String getCdate() {
return cdate;
}
public void setCdate(String cdate) {
this.cdate = cdate;
}
public String getCsource() {
return csource;
}
public void setCsource(String csource) {
this.csource = csource;
}
public String getCdestination() {
return cdestination;
}
public void setCdestination(String cdestination) {
this.cdestination = cdestination;
}
public String getCreate() {
return create;
}
public void setCreate(String create) {
this.create = create;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Set getItemList() {
return itemList;
}
public void setItemList(Set itemList) {
this.itemList = itemList;
}
}
My child model
package com.model;
public class Item{
private Long itemid;
private String itemName;
private String weight;
private cargo cargo;
public Long getItemid() {
return itemid;
}
public void setItemid(Long itemid) {
this.itemid = itemid;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public cargo getCargo() {
return cargo;
}
public void setCargo(cargo cargo) {
this.cargo = cargo;
}
}
And my form
package com.form;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import com.model.Item;
public class cargoForm extends ActionForm {
private Long id;
private String cname;
private String cdate;
private String csource;
private String cdestination;
private String create;
private String status;
private Long[] itemid;
private String[] itemName;
private String[] weight;
private Set itemset = new HashSet();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
public String getCdate() {
return cdate;
}
public void setCdate(String cdate) {
this.cdate = cdate;
}
public String getCsource() {
return csource;
}
public void setCsource(String csource) {
this.csource = csource;
}
public String getCdestination() {
return cdestination;
}
public void setCdestination(String cdestination) {
this.cdestination = cdestination;
}
public String getCreate() {
return create;
}
public void setCreate(String create) {
this.create = create;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Long[] getItemid() {
return itemid;
}
public void setItemid(Long[] itemid) {
this.itemid = itemid;
}
public String[] getItemName() {
return itemName;
}
public void setItemName(String[] itemName) {
this.itemName = itemName;
}
public String[] getWeight() {
return weight;
}
public void setWeight(String[] weight) {
this.weight = weight;
}
/*
* public Set getItemset() { return itemset; }
*
* public void setItemset(Set itemset) { this.itemset = itemset; }
*/
public Set getItemDtl() {
if (itemid != null) {
itemset = new HashSet();
System.out.println("cargadd form" + itemid);
for (int i = 0; i < itemid.length; i++) {
Item it = new Item();
// it.setItemId(itemId[i]);
it.setItemName(itemName[i]);
System.out.println("cargadd form" + itemName[i]);
it.setWeight(weight[i]);
itemset.add(it);
System.out.println("cargadd form" + itemset.size());
}
}
return itemset;
}
public void setItemDtl(Set itemset) {
System.out.println("cargadd form" + itemset.size());
this.itemset = itemset;
System.out.println("cargadd form" + itemset.size());
}
public void reset(ActionMapping mapping, HttpServletRequest request) {
cname = "";
csource = "";
cdestination = "";
cdate = "";
status = "";
create = "";
}
}
The error:
Hibernate: select max(itemid) from item
Hibernate: insert into item (itemname, weight, position, id, itemid) values (?, ?, ?, ?, ?)
Hibernate: update cargo set name=?, date=?, source=?, destination=?, createby=?, status=? where id=?
Oct 4, 2010 10:44:08 AM org.hibernate.jdbc.BatchingBatcher doExecuteBatch
SEVERE: Exception executing batch:
org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
at org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(Expectations.java:61)
at org.hibernate.jdbc.Expectations$BasicExpectation.verifyOutcome(Expectations.java:46)
at org.hibernate.jdbc.BatchingBatcher.checkRowCounts(BatchingBatcher.java:68)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:242)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:235)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:140)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
at com.action.CargoAction.save(CargoAction.java:125)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:269)
at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:170)
at org.apache.struts.chain.commands.servlet.ExecuteAction.execute(ExecuteAction.java:58)
at org.apache.struts.chain.commands.AbstractExecuteAction.execute(AbstractExecuteAction.java:67)
at org.apache.struts.chain.commands.ActionCommandBase.execute(ActionCommandBase.java:51)
at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:191)
at org.apache.commons.chain.generic.LookupCommand.execute(LookupCommand.java:305)
at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:191)
at org.apache.struts.chain.ComposableRequestProcessor.process(ComposableRequestProcessor.java:283)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913)
at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:462)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:172)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:174)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:879)
at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:665)
at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:528)
at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:81)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:689)
at java.lang.Thread.run(Unknown Source)
Oct 4, 2010 10:44:08 AM org.hibernate.event.def.AbstractFlushingEventListener performExecutions
SEVERE: Could not synchronize database state with session
org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
at org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(Expectations.java:61)
at org.hibernate.jdbc.Expectations$BasicExpectation.verifyOutcome(Expectations.java:46)
at org.hibernate.jdbc.BatchingBatcher.checkRowCounts(BatchingBatcher.java:68)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:242)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:235)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:140)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
at com.action.CargoAction.save(CargoAction.java:125)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:269)
at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:170)
at org.apache.struts.chain.commands.servlet.ExecuteAction.execute(ExecuteAction.java:58)
at org.apache.struts.chain.commands.AbstractExecuteAction.execute(AbstractExecuteAction.java:67)
at org.apache.struts.chain.commands.ActionCommandBase.execute(ActionCommandBase.java:51)
at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:191)
at org.apache.commons.chain.generic.LookupCommand.execute(LookupCommand.java:305)
at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:191)
at org.apache.struts.chain.ComposableRequestProcessor.process(ComposableRequestProcessor.java:283)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913)
at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:462)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:172)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:174)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:879)
at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:665)
at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:528)
at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:81)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:689)
at java.lang.Thread.run(Unknown Source)
org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
at org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(Expectations.java:61)
at org.hibernate.jdbc.Expectations$BasicExpectation.verifyOutcome(Expectations.java:46)
at org.hibernate.jdbc.BatchingBatcher.checkRowCounts(BatchingBatcher.java:68)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:242)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:235)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:140)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
at com.action.CargoAction.save(CargoAction.java:125)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:269)
at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:170)
at org.apache.struts.chain.commands.servlet.ExecuteAction.execute(ExecuteAction.java:58)
at org.apache.struts.chain.commands.AbstractExecuteAction.execute(AbstractExecuteAction.java:67)
at org.apache.struts.chain.commands.ActionCommandBase.execute(ActionCommandBase.java:51)
at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:191)
at org.apache.commons.chain.generic.LookupCommand.execute(LookupCommand.java:305)
at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:191)
at org.apache.struts.chain.ComposableRequestProcessor.process(ComposableRequestProcessor.java:283)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913)
at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:462)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:172)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:174)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:879)
at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:665)
at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:528)
at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:81)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:689)
at java.lang.Thread.run(Unknown Source)
In the Hibernate mapping file for the id property, if you use any generator class, for that property you should not set the value explicitly by using a setter method.
If you set the value of the Id property explicitly, it will lead the error above. Check this to avoid this error.
its happen when you try to delete the same object and then again update the same object
use this after delete
session.clear();
what i have experienced is that this exception raise when updating object have an id which not exist in table. if you read exception message it says "Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1" which means it was unable to found record with your given id.
To avoid this i always read record with same id if i found record back then i call update otherwise throw "exception record not found".
It looks like, cargo can have one or more item. Each item would have a reference to its corresponding cargo.
From the log, item object is inserted first and then an attempt is made to update the cargo object (which does not exist).
I guess what you actually want is cargo object to be created first and then the item object to be created with the id of the cargo object as the reference - so, essentally re-look at the save() method in the Action class.
It looks like, when you try to delete the same object and then again update the same object, then it gives you this error. As after every update hibernate for safe checking fires how many rows were updated, but during the code the data must have been deleted. Over here hibernate distinguish between the objects based on the key what u have assigned or the equals method.
so, just go through once through your code for this check, or try with implementing equals & hashcode method correctly which might help.
/*
* Thrown when a version number or timestamp check failed, indicating that the
* Session contained stale data (when using long transactions with versioning).
* Also occurs if we try delete or update a row that does not exist.
*
*/
if ( expectedRowCount > rowCount ) {
throw new StaleStateException(
"Batch update returned unexpected row count from update [" + batchPosition +"]; actual row count: " + rowCount +"; expected: " + expectedRowCount);
}
<property name="show_sql">true</property>
This should show you the SQL that is executed and causes the problem.
*The StaleStateException would be thrown only after we successfully deleted one object, and then tried to delete another. The reason for this is, while persisting the objects across sessions, objects must first be deleted from the Session before deleted. Otherwise, subsequent deletes will cause the StaleStateException to be thrown.
Session.Remove(obj);
objectDAO.Delete(obj);
*The problem was that a table must have only one field that is primary key (I had a composite key and this is not a good idea, except for the many to many relation). I have solved using a new id table field auto incremental.
*It can be fix by using Hibernate session.update() -- you need to have the table/view's primary key equal your corresponding bean property (eg. id).
*
For update() and saveOrUpdate() methods, id generator value should be there in the database. For the save() method, id generator is not required.
As mentioned above, be sure that you don't set any id fields which are supposed to be auto-generated.
To cause this problem during testing, make sure that the db 'sees' aka flush this SQL, otherwise everything may seem fine when really its not.
I encountered this problem when inserting my parent with a child into the db:
Insert parent (with manual ID)
Insert child (with autogenerated ID)
Update foreign key in Child table to parent.
The 3. statement failed. Indeed the entry with the autogenerated ID (by Hibernate) was not in the table as a trigger changed the ID upon each insertion, thus letting the update fail with no matching row found.
Since the table can be updated without any Hibernate I added a check whether the ID is null and only fill it in then to the trigger.
This often happens when SQL statements are implemented in some performance costly way (implicit type conversions etc.).
I advice to debug the resulting SQL statements.
To debug turn on SQL logging
Turn on hibernate SQL logging by adding the following lines to your log4j properties file:
# logs the SQL statements
log4j.logger.org.hibernate.SQL=debug
# Logs the JDBC parameters passed to a query
log4j.logger.org.hibernate.type=trace
Before failing you will see the last SQL statement attempted in your log, copy and paste this SQL into an external SQL client and run it.
I had the same as well.Making the Id (0) doing "(your Model value).setId(0)" solved my problem.
please do not set id of child class which is generator class is foreign only set parent class id if your parent class id is assigned...
just do one thing dont set id of child class via setter method your problem will be fix.....definately.
So For my case I noticed hibernate is trying to update the record rather than inserting it and that thrown the exception mentioned.
I finally came to find that my entity had an updatedAt timestamp column:
<timestamp name="updatedDate" column="updated_date" />
and when I was trying to initialize the object i found that the code was
setting this field explicitly.
after removing that setUpdateDate(new Date()) it worked and did an insert instead.
FYI, another way this exception can occur is if:
Your transaction isolation is READ_COMMITTED
Transaction #1 queries for an entity, then deletes that entity
A simultaneous transaction #2 does the same thing
Then this can happen: TX #1 successfully commits before TX #2, then when TX #2 tries to delete the entity (again) it's not there any more - even though it was found by a query earlier in that same transaction. Note this anomaly is allowed with READ_COMMITTED isolation.
In my case the resulting exception looked like this:
HHH000315: Exception executing batch [org.hibernate.StaleStateException:
Batch update returned unexpected row count from update [0]; actual row
count: 0; expected: 1; statement executed: delete from Foobar where id=?],
SQL: delete from Foobar where id=?
if The given id is not exist in the DB ,then you may get this exception.
Exception in thread "main" org.springframework.orm.hibernate3.HibernateOptimisticLockingFailureException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1; nested exception is org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

Categories