Related
Getting org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions when I am trying to delete a record in hibernate using session.delete(cust)
Please provide some help. Thanks!
I have tried to check the field mapping for id column.
And before calling delete method, id is bound with the cust object.
Configuration configuration = new Configuration().configure();
SessionFactory factory = configuration.buildSessionFactory();
Session session = factory.openSession();
long id = 2;
try {
Transaction t = session.beginTransaction();
Customer cust = (Customer) session.get(Customer.class, id);
session.delete(cust);
t.commit();
} catch (HibernateException e) {
System.out.println(e.getLocalizedMessage());
session.getTransaction().rollback();
}
}
Within my project, I am using a property placeholder to read a property file, containing the configuration for my database connection. During my initial setup and reconfiguration at some point later I want to be able to change the details of the database host.
I tried to use the refresh() method called on the current application context, but somehow the Spring Data Beans are not reloaded and I am getting an IllegalStateException issued by Spring Data:
HTTP Status 500 - Request processing failed; nested exception is java.lang.IllegalStateException: open
Exception report: Message: Request processing failed; nested exception is java.lang.IllegalStateException: open description: The server encountered an internal error that prevented it from fulfilling this request. exception: org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalStateException: open
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
javax.servlet.http.HttpServlet.service(HttpServlet.java:644)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:139)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
root cause: java.lang.IllegalStateException: open
org.bson.util.Assertions.isTrue(Assertions.java:36)
com.mongodb.DBTCPConnector.getPrimaryPort(DBTCPConnector.java:408)
com.mongodb.DBCollectionImpl.update(DBCollectionImpl.java:263)
com.mongodb.DBCollection.update(DBCollection.java:191)
com.mongodb.DBCollection.save(DBCollection.java:975)
com.mongodb.DBCollection.save(DBCollection.java:934)
org.springframework.data.mongodb.core.MongoTemplate$10.doInCollection(MongoTemplate.java:950)
org.springframework.data.mongodb.core.MongoTemplate.execute(MongoTemplate.java:410)
org.springframework.data.mongodb.core.MongoTemplate.saveDBObject(MongoTemplate.java:945)
org.springframework.data.mongodb.core.MongoTemplate.doSave(MongoTemplate.java:885)
org.springframework.data.mongodb.core.MongoTemplate.save(MongoTemplate.java:833)
org.springframework.data.mongodb.repository.support.SimpleMongoRepository.save(SimpleMongoRepository.java:73)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:483)
org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:442)
org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:427)
org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:381)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.data.repository.core.support.RepositoryFactorySupport$DefaultMethodInvokingMethodInterceptor.invoke(RepositoryFactorySupport.java:512)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
com.sun.proxy.$Proxy2987.save(Unknown Source)
de.steilerdev.myVerein.server.controller.InitController.initSuperAdmin(InitController.java:158)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:483)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:781)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:721)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
javax.servlet.http.HttpServlet.service(HttpServlet.java:644)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:139)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
Unfortunately I am not very confident with beans and their lifecycle, so I need help reloading the appropriate bean. I would also be okay with the possibility to restart the Spring application itself, even though it would be an expensive operation. Since it is only needed very rarely I would be okay with the costs of that.
I am not sure which parts of the code you need, but here is a link to the Github repository. (Sorry for the poor documentation, still at the beginning of the project)
Thanks!
Edit: Some classes involved in the process:
de.steilerdev.myVerein.server.controller.InitController (Receiving the related request, storing the settings to my SettingsRepository)
#Controller
#RequestMapping("/init")
public class InitController
{
#Autowired
private SettingsRepository settingsRepository;
#Autowired
private UserRepository userRepository;
#Autowired
private DivisionRepository divisionRepository;
#Autowired
private ReloadableResourceBundleMessageSource messageSource;
private static Logger logger = LoggerFactory.getLogger(InitController.class);
#RequestMapping(value = "settings")
public ResponseEntity<String> initSettings(#RequestParam String clubName,
#RequestParam String databaseHost,
#RequestParam String databasePort,
#RequestParam String databaseUser,
#RequestParam String databasePassword,
#RequestParam String databaseCollection,
#RequestParam String rememberMeTokenKey,
Locale locale)
{
logger.debug("Starting initial configuration");
if(!settingsRepository.isInitSetup())
{
logger.warn("An initial setup API was used, even though the system is already configured.");
return new ResponseEntity<>(messageSource.getMessage("init.message.settings.notAllowed", null, "You are not allowed to perform this action at the moment", locale), HttpStatus.BAD_REQUEST);
} else if(clubName.isEmpty() || rememberMeTokenKey.isEmpty())
{
logger.warn("The club name or remember me key is not present");
return new ResponseEntity<>(messageSource.getMessage("init.message.settings.noKeyOrName", null, "The club name and remember me key is required", locale), HttpStatus.BAD_REQUEST);
} else
{
int databasePortInt = 27017;
if(databaseHost.isEmpty())
{
logger.warn("The database host is empty, using default value.");
databaseHost = "localhost";
}
if(databasePort.isEmpty())
{
logger.warn("The database port is empty, using default value.");
databasePort = "27017";
} else
{
try
{
databasePortInt = Integer.parseInt(databasePort);
} catch (NumberFormatException e)
{
logger.warn("The database port seems not to be a number " + databasePort);
return new ResponseEntity<>(messageSource.getMessage("init.message.settings.dbPortNoNumber", null, "The database port needs to be a number", locale), HttpStatus.BAD_REQUEST);
}
}
if(databaseCollection.isEmpty())
{
logger.warn("The database collection name is empty, using default value");
databaseCollection = "myVerein";
}
if(!mongoIsAvailable(databaseHost, databasePortInt, databaseUser, databasePassword, databaseCollection))
{
logger.warn("The stated MongoDB is not available");
return new ResponseEntity<>(messageSource.getMessage("init.message.settings.mongoNotAvailable", null, "The stated MongoDB is not available", locale), HttpStatus.BAD_REQUEST);
}
try
{
logger.debug("Temporarily storing information");
settingsRepository.setClubName(clubName);
settingsRepository.setDatabaseHost(databaseHost);
settingsRepository.setDatabasePort(databasePort);
settingsRepository.setDatabaseUser(databaseUser);
settingsRepository.setDatabasePassword(databasePassword);
settingsRepository.setDatabaseName(databaseCollection);
settingsRepository.setRememberMeKey(rememberMeTokenKey);
} catch (IOException e)
{
logger.warn("Unable to save settings.");
return new ResponseEntity<>(messageSource.getMessage("init.message.settings.savingSettingsError", null, "Unable to save settings, please try again", locale), HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<>(messageSource.getMessage("init.message.settings.savingSettingsSuccess", null, "Successfully saved settings", locale), HttpStatus.OK);
}
}
#RequestMapping(value = "superAdmin")
public ResponseEntity<String> initSuperAdmin(#RequestParam String firstName,
#RequestParam String lastName,
#RequestParam String email,
#RequestParam String password,
#RequestParam String passwordRe,
Locale locale)
{
if(!settingsRepository.isInitSetup())
{
logger.warn("An initial setup API was used, even though the system is already configured.");
return new ResponseEntity<>(messageSource.getMessage("init.message.admin.notAllowed", null, "You are not allowed to perform this action at the moment", locale), HttpStatus.BAD_REQUEST);
} else if(firstName.isEmpty() || lastName.isEmpty() || email.isEmpty() || password.isEmpty() || passwordRe.isEmpty())
{
logger.warn("A required parameter of the super admin is empty or missing during initial configuration");
return new ResponseEntity<>(messageSource.getMessage("init.message.admin.missingParameter", null, "A required parameter is empty or missing", locale), HttpStatus.BAD_REQUEST);
} else if(!password.equals(passwordRe))
{
logger.warn("The password and the re-typed password do not match!");
return new ResponseEntity<>(messageSource.getMessage("init.message.admin.passwordMatchError", null, "The password and the re-typed password do not match", locale), HttpStatus.BAD_REQUEST);
} else
{
logger.debug("Creating a new initial user.");
User superAdmin = new User();
superAdmin.setFirstName(firstName);
superAdmin.setLastName(lastName);
superAdmin.setEmail(email);
superAdmin.setPassword(password);
logger.debug("Creating a new initial root division.");
Division rootDivision = new Division(settingsRepository.getClubName(), null, superAdmin, null);
//Saving changes and restarting context
try
{
settingsRepository.setInitSetup(false);
//This call is restarting the application.
settingsRepository.saveSettings(superAdmin);
} catch (IOException e)
{
logger.warn("Unable to save settings.");
return new ResponseEntity<>(messageSource.getMessage("init.message.admin.savingSettingsError", null, "Unable to save settings, please try again", locale), HttpStatus.INTERNAL_SERVER_ERROR);
}
try
{
userRepository.save(superAdmin);
divisionRepository.save(rootDivision);
} catch (ConstraintViolationException e)
{
logger.warn("A database constraint was violated while saving the new super admin.");
return new ResponseEntity<>(messageSource.getMessage("init.message.admin.constraintViolation", null, "A database constraint was violated while saving the new super admin", locale), HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(messageSource.getMessage("init.message.admin.savingAdminSuccess", null, "Successfully saved the new super admin. The settings are now being saved and the application is restarted.", locale) , HttpStatus.OK);
}
}
private boolean mongoIsAvailable(String databaseHost, int databasePort, String databaseUser, String databasePassword, String databaseCollection)
{
logger.debug("Creating mongo client to test connection");
List<MongoCredential> credential = null;
MongoClient mongoClient = null;
if(!databaseUser.isEmpty() && !databasePassword.isEmpty())
{
credential = Arrays.asList(MongoCredential.createMongoCRCredential(databaseUser, databaseCollection, databasePassword.toCharArray()));
}
try
{
mongoClient = new MongoClient(new ServerAddress(databaseHost, databasePort),credential);
//Checking if connection REALLY works
List<String> databases = mongoClient.getDatabaseNames();
if(databases == null)
{
logger.warn("The list of databases is null");
return false;
} else if(databases.isEmpty())
{
logger.info("The databases are empty");
return true;
} else
{
logger.debug("The database connection seems okay.");
return true;
}
} catch (UnknownHostException e)
{
logger.warn("Unable to resolve mongoDB host: " + e.getMessage());
return false;
} catch (MongoException e)
{
logger.warn("Unable to receive list of present databases: " + e.getMessage());
return false;
} finally
{
if(mongoClient != null)
{
mongoClient.close();
}
}
}
}
de.steilerdev.myVerein.server.model.SettingsRepository (Retrieving and storing the settings persistent within a properties file, as well as restarting the application if the settings changed)
public class SettingsRepository
{
#Autowired
private MongoTemplate mongoTemplate;
#Autowired
private SimpleMongoDbFactory mongoDbFactory;
#Autowired
private ApplicationContext applicationContext;
private Properties settings;
private Resource settingsResource;
private final static String settingsFileName = "myVerein.properties";
//Property names
private final static String databaseName = "dbName";
private final static String databaseHost = "dbHost";
private final static String databasePort = "dbPort";
private final static String databaseUser = "dbUser";
private final static String databasePassword = "dbPassword";
private final static String rememberMeKey = "rememberMeKey";
private final static String clubName = "clubName";
private final static String initSetup = "initSetup";
private boolean changed;
private boolean databaseChanged;
private static Logger logger = LoggerFactory.getLogger(SettingsRepository.class);
public Properties loadSettings() throws IOException
{
if(settings == null)
{
logger.debug("Loading settings file from classpath");
settingsResource = new ClassPathResource(settingsFileName);
changed = false;
databaseChanged = false;
return (settings = PropertiesLoaderUtils.loadProperties(settingsResource));
} else
{
return settings;
}
}
//Getter and setter removed
public void saveSettings(User currentUser) throws IOException
{
saveSettings(loadSettings(), currentUser);
}
public void saveSettings(Properties settings, User currentUser) throws IOException
{
if(changed)
{
logger.debug("Saving settings to " + settingsResource.getFile().getAbsolutePath());
settings.store(new FileOutputStream(settingsResource.getFile()), "Settings last changed " + (currentUser != null ? ("by " + currentUser.getEmail() + " (" + LocalDateTime.now().toString() + ")") : LocalDateTime.now().toString()));
if(databaseChanged)
{
try
{
mongoDbFactory.destroy();
} catch (Exception e)
{
System.err.println("Problem destroying factory");
}
((ConfigurableApplicationContext) applicationContext).refresh();
}
this.settings = null;
} else
{
logger.debug("No need to save the settings");
}
}
}
The exception is thrown in line 178 of the InitController, which means after reloading and during saving an object to the new controller userRepository.save(superAdmin);
It's hard to say, why reload does not work, based on plain Exception, but here are some hints:
Regarding restarting application context, there is a good article
http://jroller.com/Solomon/entry/reloading_a_spring_web_application
You can get some clues for why it malfunctions from there.
With context reload you need to be careful to close all open resources, properly, on application shutdown.
Check that you closed Mongo connection properly in your application context.
What is the correct way to close the mongo connection using spring-mongo?
After you added your code. It's hard to understand, what are you trying to accomplish with this. This will take you allot of effort to make it work properly, and most of this efforts will be waist.
You can't reload specific bean in Spring Context, but you can reload whole context, by calling ApplicationContext refresh(), after which all beans will be recreated, including your Controller beans. So this should at least be a separate Controller, with no additional functionality. Also It seems you are assuming you can change mongo configuration, and at the same call write something to mongo, using old references ... this is not how things work in spring. So just don't.
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()
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.
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