HIbernate Annotation Auto Generate table in MySQL - java

I am new in hibernate and i want to do hibernate annotation and auto generate table in mysql as i submit data.but i have some error like sql grammar.please help me to solve this error.my all code is below..
My Jsp File
<html>
<head>
</head>
<body>
<form action="controller" method="post">
Id : <input type="text" name="id"><br>
First-Name : <input type="text" name="fName"><br>
Last-Name : <input type="text" name="lName"><br>
<input type="submit" value="submit">
</form>
</body>
</html>
This is My Pojo Class
package com.connection;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "csl_emp")
public class Employee {
#Id
private int id;
private String firstName, lastName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
This is my servler
package com.connection;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class controller
*/
public class controller extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public controller() {
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("in the controller");
String id = request.getParameter("id");
String fname = request.getParameter("fName");
String lname = request.getParameter("lName");
System.out.println(id + fname + lname);
Employee employee = new Employee();
employee.setFirstName(fname);
employee.setLastName(lname);
employee.setId(Integer.parseInt(id));
EmpDao dao = new EmpDao();
dao.addData(employee);
RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher("/success.jsp");
requestDispatcher.forward(request, response);
}
}
This is mY dao class
package com.connection;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
public class EmpDao {
public void addData(Employee employee) {
Session session = new AnnotationConfiguration().configure().buildSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
session.saveOrUpdate(employee);
transaction.commit();
session.close();
}
}
And This is my Configuration File
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/javadb</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hbm2ddl.auto">true</property>
<mapping class="com.connection.Employee"/>
</session-factory>
</hibernate-configuration>
And I have getting error like this
Sep 12, 2013 11:49:25 AM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\java\jdk1.6.0_43\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files/java/jdk1.6.0_43/bin/../jre/bin/server;C:/Program Files/java/jdk1.6.0_43/bin/../jre/bin;C:/Program Files/java/jdk1.6.0_43/bin/../jre/lib/amd64;C:\Windows\System32;C:\Program Files\java\jdk1.6.0_43\bin;C:\Program Files\apache-ant-1.8.4\bin;C:\Program Files (x86)\MySQL\MySQL Server 5.0\bin;D:\eclipse;;.
Sep 12, 2013 11:49:26 AM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:jspcrud' did not find a matching property.
Sep 12, 2013 11:49:26 AM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:Hibernate-J2EE-Annotation' did not find a matching property.
Sep 12, 2013 11:49:27 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
Sep 12, 2013 11:49:27 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
Sep 12, 2013 11:49:27 AM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 2769 ms
Sep 12, 2013 11:49:27 AM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Sep 12, 2013 11:49:27 AM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.40
Sep 12, 2013 11:49:28 AM org.apache.catalina.util.SessionIdGenerator createSecureRandom
INFO: Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [203] milliseconds.
Sep 12, 2013 11:49:30 AM org.apache.catalina.loader.WebappClassLoader validateJarFile
INFO: validateJarFile(E:\projects\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Hibernate-J2EE-Annotation\WEB-INF\lib\servlet-api-2.4.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class
Sep 12, 2013 11:49:31 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
Sep 12, 2013 11:49:31 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Sep 12, 2013 11:49:31 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 3324 ms
in the controller
1chiragsoni
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
Sep 12, 2013 11:49:48 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [controller] in context with path [/Hibernate-J2EE-Annotation] threw exception
org.hibernate.exception.SQLGrammarException: could not retrieve snapshot: [com.connection.Employee#1]
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:67)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.persister.entity.AbstractEntityPersister.getDatabaseSnapshot(AbstractEntityPersister.java:1039)
at org.hibernate.engine.StatefulPersistenceContext.getDatabaseSnapshot(StatefulPersistenceContext.java:232)
at org.hibernate.engine.ForeignKeys.isTransient(ForeignKeys.java:189)
at org.hibernate.event.def.AbstractSaveEventListener.getEntityState(AbstractSaveEventListener.java:487)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:84)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70)
at org.hibernate.impl.SessionImpl.fireSaveOrUpdate(SessionImpl.java:507)
at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:499)
at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:495)
at com.connection.EmpDao.addData(EmpDao.java:12)
at com.connection.controller.doPost(controller.java:52)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1008)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
at java.lang.Thread.run(Thread.java:662)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'test.csl_emp' doesn't exist
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1052)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3609)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3541)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2002)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2163)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2624)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2127)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2293)
at org.hibernate.persister.entity.AbstractEntityPersister.getDatabaseSnapshot(AbstractEntityPersister.java:1012)
... 28 more

In your configuration file add this property:
<property name="hibernate.hbm2ddl.auto" value="update" />
and also, very useful are these:
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />

From Hibernate docs
Change your configuration file property as below
<property name="hibernate.hbm2ddl.auto" value="create"/>
instead of
<property name="hbm2ddl.auto">true</property>

Related

Getting Error:INFO: HHH000206: hibernate.properties not found

I am eclipse IDE..
I have configured hibernate properly but still i am getting this error.
Directory Structure:
HibernateProject-Java Resources-Src
-com.project -Employeee.java -Testjdbc.java(contains main function)
-hibernate.cfg.xml
Employee.java
package com.package;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="employeee")
public class Employeee {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="Empcode")
private int Empcode;
#Column(name="EmpName")
private String EmpName;
#Column(name="EmpDesignation")
private String EmpDesignation;
#Column(name="EmpDOB")
private Date EmpDOB;
#Column(name="EmpJOD")
private Date EmpJOD;
#Column(name="EmpAge")
private int EmpAge;
#Column(name="EmpBasic_Pay")
private double EmpBasic_Pay;
public int getEmpcode() {
return Empcode;
}
public void setEmpcode(int empcode) {
Empcode = empcode;
}
public String getEmpName() {
return EmpName;
}
public void setEmpName(String empName) {
EmpName = empName;
}
public String getEmpDesignation() {
return EmpDesignation;
}
public void setEmpDesignation(String empDesignation) {
EmpDesignation = empDesignation;
}
public Date getEmpDOB() {
return EmpDOB;
}
public void setEmpDOB(Date empDOB) {
EmpDOB = empDOB;
}
public Date getEmpJOD() {
return EmpJOD;
}
public void setEmpJOD(Date empJOD) {
EmpJOD = empJOD;
}
public int getEmpAge() {
return EmpAge;
}
public void setEmpAge(int empAge) {
EmpAge = empAge;
}
public double getEmpBasic_Pay() {
return EmpBasic_Pay;
}
public void setEmpBasic_Pay(double empBasic_Pay) {
EmpBasic_Pay = empBasic_Pay;
}
public Employeee() {
}
public Employeee(int empcode, String empName, String empDesignation, java.util.Date sdate, java.util.Date edate, int empAge,
double empBasic_Pay) {
super();
Empcode = empcode;
EmpName = empName;
EmpDesignation = empDesignation;
EmpDOB = sdate;
EmpJOD = edate;
EmpAge = empAge;
EmpBasic_Pay = empBasic_Pay;
}
#Override
public String toString() {
return "Student [Empcode=" + Empcode + ", EmpName=" + EmpName + ", EmpDesignation=" + EmpDesignation
+ ", EmpDOB=" + EmpDOB + ", EmpJOD=" + EmpJOD + ", EmpAge=" + EmpAge + ", EmpBasic_Pay=" + EmpBasic_Pay
+ "]";
}
}
Testjdbc.java
package com.package;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.wipro.Employeee;
public class TestJDBC {
public static void main(String[] args) {
// create session factory
SessionFactory factory = new Configuration()
.configure("hibernate.cfg.xml")
.addAnnotatedClass(Employeee.class)
.buildSessionFactory();
// create session
Session session = factory.getCurrentSession();
try {
// create a student object
System.out.println("Creating new student object...");
SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");
java.util.Date sdate=sdf.parse("2018/07/22");
java.util.Date edate=sdf.parse("2019/07/22");
//empcode empName empDesignation empDOB empJOD empAge empBasic_Pay;
Employeee emp=new Employeee(101,"ABC","Engineer",sdate,edate,25,250000.00);
// start a transaction
session.beginTransaction();
// save the student object
System.out.println("Saving the student...");
session.save(emp);
// commit transaction
session.getTransaction().commit();
System.out.println("Done!");
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
factory.close();
}
}
}
hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- JDBC Database connection settings -->
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/jdbcassignment?useSSL=false&serverTimezone=UTC</property>
<property name="connection.username">root</property>
<property name="connection.password">tiger</property>
<!-- JDBC connection pool settings ... using built-in test pool -->
<property name="connection.pool_size">1</property>
<!-- Select our SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Echo the SQL to stdout -->
<property name="show_sql">true</property>
<!-- Set the current session context -->
<property name="current_session_context_class">thread</property>
</session-factory>
</hibernate-configuration>
Error:
Aug 25, 2018 6:13:07 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.3.1.Final}
Aug 25, 2018 6:13:07 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Aug 25, 2018 6:13:07 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.3.Final}
Aug 25, 2018 6:13:07 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Aug 25, 2018 6:13:07 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.cj.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/jdbcassignment?useSSL=false&serverTimezone=UTC]
Aug 25, 2018 6:13:07 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=root, password=****}
Aug 25, 2018 6:13:07 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Aug 25, 2018 6:13:07 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 1 (min=1)
Aug 25, 2018 6:13:07 PM org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator initiateService
WARN: HHH000342: Could not obtain connection to query metadata : null
Aug 25, 2018 6:13:07 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Aug 25, 2018 6:13:07 PM org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl makeLobCreatorBuilder
INFO: HHH000422: Disabling contextual LOB creation as connection was null
Aug 25, 2018 6:13:07 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 0, SQLState: 08001
Aug 25, 2018 6:13:07 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Public Key Retrieval is not allowed
Exception in thread "main" org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:275)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.injectServices(DefaultIdentifierGeneratorFactory.java:152)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.injectDependencies(AbstractServiceRegistryImpl.java:286)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:243)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.<init>(InFlightMetadataCollectorImpl.java:179)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:119)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:84)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:474)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:85)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:689)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
at com.wipro.TestJDBC.main(TestJDBC.java:23)
Caused by: org.hibernate.exception.JDBCConnectionException: Error calling Driver#connect
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:48)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.convertSqlException(BasicConnectionCreator.java:118)
at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:41)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.createConnection(BasicConnectionCreator.java:58)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections.addConnections(DriverManagerConnectionProviderImpl.java:363)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections.<init>(DriverManagerConnectionProviderImpl.java:282)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections.<init>(DriverManagerConnectionProviderImpl.java:260)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections$Builder.build(DriverManagerConnectionProviderImpl.java:401)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.buildPool(DriverManagerConnectionProviderImpl.java:112)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:75)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:100)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:246)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.buildJdbcConnectionAccess(JdbcEnvironmentInitiator.java:145)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:66)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:94)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263)
... 14 more
Caused by: java.sql.SQLNonTransientConnectionException: Public Key Retrieval is not allowed
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:110)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:832)
at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456)
at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:240)
at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:207)
at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:38)
... 29 more
Please see if you can help.

Why hibernate returns no entity from db, however given table has data?

I would like to build a small console application executed by tests just of learning Hibernate purposes. Unfortunately, hibernate returns with no data and when a list should be populated by the entities it throws outofindex exception. I assume due to no result coming back. I have been reading the tutorials and questions here, but I cannot find why this happens.
JDBC connection is working well, it is copied from DataGrip.
What other detailed should be checked more? Sorry, I'm totally inexperienced in this world.
Please find the code below.
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQL95Dialect</property>
<property name="connection.url" >jdbc:postgresql://localhost:5432/digitallibraryreports</property>
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="connection.username">postgres</property>
<property name="connection.password">postgres</property>
<property name="connection.pool_size">1</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="use_sql_comments">true</property>
<!-- DB schema will be updated if needed -->
<!-- <property name="hbm2ddl.auto">update</property> -->
</session-factory>
</hibernate-configuration>
Source:
public class ETL {
private static SessionFactory factory;
public ETL(){
try{
factory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex){
System.err.println("Failed to create sessionfactory" + ex);
throw new ExceptionInInitializerError(ex);
}
}
public SessionFactory getSessionFactory() {
return factory;
}
}
Class fetching stuff:
public class FeatureFetcher {
private static SessionFactory sessionFactory;
public FeatureFetcher() {
ETL etl = new ETL();
sessionFactory = etl.getSessionFactory();
}
public void fetchFeatures() {
Session session = sessionFactory.openSession();
EntityManager em = sessionFactory.createEntityManager();
try {
em.getTransaction().begin();
List<Test> testEntityList = em.createQuery("FROM Test", Test.class).getResultList();
if (testEntityList.size() > 0) {
for (Iterator<Test> iterator = testEntityList.iterator(); iterator.hasNext(); ) {
Test testEntity = (Test) iterator.next();
System.out.println("Test Entity name: " + testEntity.getName());
System.out.println("Test Entity id: " + testEntity.getId());
}
em.getTransaction().commit();
em.close();
}
} catch (HibernateException e) {
em.getTransaction().rollback();
e.printStackTrace();
} finally {
em.close();
}
}
}
Entity:
#Entity
#Table(name = "test", schema = "public")
public class Test {
#javax.persistence.Id
#GeneratedValue
#Column(name = "id")
public Integer Id;
#Column(name = "name")
public String Name;
public Integer getId() {
return Id;
}
public void setId(Integer id) {
Id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
}
SQL:
CREATE TABLE public.TEST
(
Id INT PRIMARY KEY,
Name VARCHAR(255)
);
Logs:
May 14, 2017 9:20:30 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.10.Final}
May 14, 2017 9:20:30 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
May 14, 2017 9:20:31 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
May 14, 2017 9:20:31 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
May 14, 2017 9:20:31 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [org.postgresql.Driver] at URL [jdbc:postgresql://localhost:5432/digitallibraryreports]
May 14, 2017 9:20:31 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=postgres, password=****}
May 14, 2017 9:20:31 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
May 14, 2017 9:20:31 PM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 1 (min=1)
May 14, 2017 9:20:31 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.PostgreSQL95Dialect
May 14, 2017 9:20:31 PM org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl useContextualLobCreation
INFO: HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
May 14, 2017 9:20:31 PM org.hibernate.type.BasicTypeRegistry register
INFO: HHH000270: Type registration [java.util.UUID] overrides previous : org.hibernate.type.UUIDBinaryType#6253c26
May 14, 2017 9:20:31 PM org.hibernate.hql.internal.QuerySplitter concreteQueries
WARN: HHH000183: no persistent classes found for query class: FROM Test
May 14, 2017 9:20:31 PM org.hibernate.hql.internal.QueryTranslatorFactoryInitiator initiateService
INFO: HHH000397: Using ASTQueryTranslatorFactory
You need to register entites in the SessionFactory.
You can do it by editing hibernate.cfg.xml by this way:
<session-factory>
...
<mapping class="some.pack.Test" />
...
</session-factory>
You can use Spring to scan a package to add entites, as well. Or, for testing purposes, EntityScanner from here.
Appart that, remove all lines related to the EntityManager and use Session. Remove this:
EntityManager em = sessionFactory.createEntityManager();
Hibernate SessionFactory is not aware of the your entity. You need to add the following resource to the hibernate.cfg.xml file inside the tag replacing the Entity with the correct name of the hbm.xml file.
<session-factory>
.
.
.
<mapping resource="Entity.hbm.xml"/>
</session-factory>

I am trying to connect to a mysql database with hibernate xml mapping but I am getting this error

This is my output it shows that I could not get a constructor from org.hibernate.persister.entity.SingleTableEntityPersister. As far as I can tell it has managed to access the log on to the database. The error starts soon after that.
Jan 21, 2016 9:19:44 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.0.6.Final}
Jan 21, 2016 9:19:44 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Jan 21, 2016 9:19:44 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Jan 21, 2016 9:19:45 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Jan 21, 2016 9:19:45 PM org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver resolveEntity
WARN: HHH90000012: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-mapping. Use namespace http://www.hibernate.org/dtd/hibernate-mapping instead. Support for obsolete DTD/XSD namespaces may be removed at any time.
Jan 21, 2016 9:19:47 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Jan 21, 2016 9:19:47 PM `enter code here`org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/rhs]
Jan 21, 2016 9:19:47 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=root, password=****}
Jan 21, 2016 9:19:47 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Jan 21, 2016 9:19:47 PM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Jan 21, 2016 9:19:48 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
Exception in thread "main" org.hibernate.MappingException: Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:123)
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:77)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:346)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
at JavaUtil.main(JavaUtil.java:20)
Caused by: org.hibernate.HibernateException: Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]
at org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:91)
at org.hibernate.tuple.entity.EntityTuplizerFactory.constructDefaultTuplizer(EntityTuplizerFactory.java:116)
at org.hibernate.tuple.entity.EntityMetamodel.<init>(EntityMetamodel.java:388)
at org.hibernate.persister.entity.AbstractEntityPersister.<init>(AbstractEntityPersister.java:509)
at org.hibernate.persister.entity.SingleTableEntityPersister.<init>(SingleTableEntityPersister.java:124)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:96)
... 6 more
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:88)
... 15 more
Caused by: org.hibernate.PropertyNotFoundException: Could not locate setter method for property [Profession#SALARY]
at org.hibernate.internal.util.ReflectHelper.findSetterMethod(ReflectHelper.java:532)
at org.hibernate.property.access.internal.PropertyAccessBasicImpl.<init>(PropertyAccessBasicImpl.java:44)
at org.hibernate.property.access.internal.PropertyAccessStrategyBasicImpl.buildPropertyAccess(PropertyAccessStrategyBasicImpl.java:27)
at org.hibernate.mapping.Property.getGetter(Property.java:299)
at org.hibernate.tuple.entity.PojoEntityTuplizer.buildPropertyGetter(PojoEntityTuplizer.java:270)
at org.hibernate.tuple.entity.AbstractEntityTuplizer.<init>(AbstractEntityTuplizer.java:145)
at org.hibernate.tuple.entity.PojoEntityTuplizer.<init>(PojoEntityTuplizer.java:63)
... 20 more
This is a simple POJO class
import javax.persistence.*;
public class Profession {
private int EDUCATION;
private int HOURS;
private String JOB_OUTLOOK;
private String JOBTITLE;
private double SALARY;
private String UPWARD_MOBILITY;
public Profession() {
}
public int getEDUCATION() {
return EDUCATION;
}
public void setEDUCATION(int eDUCATION) {
EDUCATION = eDUCATION;
}
public int getHOURS() {
return HOURS;
}
public void setHOURS(int hOURS) {
HOURS = hOURS;
}
public String getJOB_OUTLOOK() {
return JOB_OUTLOOK;
}
public void setJOB_OUTLOOK(String jOB_OUTLOOK) {
JOB_OUTLOOK = jOB_OUTLOOK;
}
public String getJOBTITLE() {
return JOBTITLE;
}
public void setJOBTITLE(String jOBTITLE) {
JOBTITLE = jOBTITLE;
}
public double getSALARY() {
return SALARY;
}
public void setSALRAY(double sALARY) {
SALARY = sALARY;
}
public String getUPWARD_MOBILITY() {
return UPWARD_MOBILITY;
}
public void setUPWARD_MOBILITY(String uPWARD_MOBILITY) {
UPWARD_MOBILITY = uPWARD_MOBILITY;
}
}
This is my main class
import org.hibernate.*;
import org.hibernate.cfg.*;
import java.util.Scanner;
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
public class JavaUtil {
public JavaUtil() {
}
public static void main(String[] args) throws IOException {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
Profession p = new Profession();
// closing session
Transaction tx = session.beginTransaction();
session.save(p);
System.out.println("Object saved successfully.....!!");
tx.commit();
session.close();
factory.close();
}
}
This is my hibernate config file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Related to the connection START -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/rhs </property>
<property name="connection.user">root</property>
<property name="connection.password">root</property>
<!-- Related to the connection END -->
<!-- Related to hibernate properties START -->
<property name="show_sql">true </property>
<property name="dialet">org.hibernate.dialect.MySqlDialect </property>
<property name="hbm2ddl.auto">update </property>
<!-- Related to hibernate properties END -->
<!-- Related to mapping START -->
<mapping resource="profession.hbm.xml" />
<!-- Related to the mapping END -->
</session-factory>
</hibernate-configuration>
This is xml mapping
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Profession" table="profession">
<id name="JOBTITLE" column="JOBTITLE" >
<generator class="assigned" />
</id>
<property name="EDUCATION"/>
<property name="HOURS"/>
<property name="JOB_OUTLOOK"/>
<property name="SALARY"/>
<property name="UPWARD_MOBILITY"/>
</class>
</hibernate-mapping>
Please change your property name to follow the POJO rule
public class Profession {
private int education;
private int hours;
private String jobOutlook;
private String jobTitle;
private double salary;
private String upwardMobility;
.....
}

Batch update returned unexpected row count from update [0]; actual row count: -1; expected: 1

I am new to Hibernate.
I am using NetBeans 7.4 , Hibernate 4.3.6 and Database as Ms Sql Server.
It works fine for fetching data from database but it gives error for Insert , Update , Delete.
My Hibernate Configuration file as :
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="hibernate.connection.url">jdbc:sqlserver://SqlSer:1433;databaseName=HibSample</property>
<property name="hibernate.connection.username">SA</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
<property name="hibernate.show_sql">true</property>
<mapping resource="Entity/Sample.hbm.xml"/>
</session-factory>
</hibernate-configuration>
my HibernateUtil File is as:
public class NewHibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from standard (hibernate.cfg.xml)
// config file.
Configuration configuration = new Configuration();
configuration.configure();
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
// Log the exception.
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
My Reverse Engineering File as:
<hibernate-reverse-engineering>
<schema-selection match-catalog="HibSample" match-schema="dbo"/>
<table-filter match-name="Sample"/>
</hibernate-reverse-engineering>
My Pojo and Mapping Files are :
public class Sample implements java.io.Serializable {
private int id;
private String fullName;
private String address;
public Sample() {
}
public Sample(int id, String fullName) {
this.id = id;
this.fullName = fullName;
}
public Sample(int id, String fullName, String address) {
this.id = id;
this.fullName = fullName;
this.address = address;
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getFullName() {
return this.fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
}
and
<hibernate-mapping>
<class name="Entity.Sample" table="Sample" schema="dbo" catalog="HibSample">
<id name="id" type="int">
<column name="ID" />
<generator class="assigned" />
</id>
<property name="fullName" type="string">
<column name="FullName" length="50" not-null="true" />
</property>
<property name="address" type="string">
<column name="Address" length="50" />
</property>
</class>
</hibernate-mapping>
Main File is :
public class Main
{
public Main(){};
public static void main(String args[])
{
Session session = NewHibernateUtil.getSessionFactory().openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
Sample s = new Sample();
s.setId(3);
s.setFullName("Demo");
s.setAddress("Demo");
Sample s1 = (Sample)session.load(Sample.class, 2);
System.out.println("ID :"+s1.getId());
System.out.println("Full Name : "+s1.getFullName());
System.out.println("Address : "+s1.getAddress());
session.save(s);
if(!tx.wasCommitted())
{
tx.commit();
}
}catch(Exception ex)
{
if(tx != null)
{
tx.rollback();
ex.printStackTrace();
}
}finally{
session.close();
}
System.exit(0);
}
}
Table Data are as follow :
ID Full Name Address
1 XYZ India
2 ABC India
Error IS :
Dec 17, 2014 4:42:42 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
Dec 17, 2014 4:42:42 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.6.Final}
Dec 17, 2014 4:42:42 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Dec 17, 2014 4:42:42 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Dec 17, 2014 4:42:42 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
Dec 17, 2014 4:42:42 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
Dec 17, 2014 4:42:42 PM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
Dec 17, 2014 4:42:42 PM org.hibernate.cfg.Configuration addResource
INFO: HHH000221: Reading mappings from resource: Entity/Demo.hbm.xml
Dec 17, 2014 4:42:42 PM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
Dec 17, 2014 4:42:42 PM org.hibernate.cfg.Configuration addResource
INFO: HHH000221: Reading mappings from resource: Entity/Sample.hbm.xml
Dec 17, 2014 4:42:42 PM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
Dec 17, 2014 4:42:42 PM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Dec 17, 2014 4:42:42 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
Dec 17, 2014 4:42:43 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [com.microsoft.sqlserver.jdbc.SQLServerDriver] at URL [jdbc:sqlserver://150.10.10.233;databaseName=HibSample]
Dec 17, 2014 4:42:43 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=SA, password=****}
Dec 17, 2014 4:42:43 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
Dec 17, 2014 4:42:43 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Dec 17, 2014 4:42:43 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.SQLServerDialect
Dec 17, 2014 4:42:43 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Dec 17, 2014 4:42:43 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Result
ID :2
Full Name : ABC
Address : India
Hibernate: insert into HibSample.dbo.Sample (FullName, Address, ID) values (?, ?, ?)
org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: -1; expected: 1
at org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(Expectations.java:81)
at org.hibernate.jdbc.Expectations$BasicExpectation.verifyOutcome(Expectations.java:73)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:63)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3124)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3581)
at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:104)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:463)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:349)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:350)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:56)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1222)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:425)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:177)
at UI.Main.main(Main.java:45)
Dec 17, 2014 4:42:43 PM org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl release
INFO: HHH000010: On release of batch it still contained JDBC statements
BUILD SUCCESSFUL (total time: 1 second)
I have search all possibilities but can't find the solution.

NumberFormatException getting simplecart items,quantity,price and grandtotal in an array in java servlet

I have implemented simplecart to my project.
On clicking the checkout button it went to PayPal which I didn't wanted it to. So I changed the action URL in simplecart.js file to point to my servlet
action = opts.sandbox ? "cart_checkout" :"cart_checkout",
method = opts.method === "GET" ? "GET" : "POST";
It calls the servlet but I get a NumberFormatException in my servlet
Servlet
package com.kunal.servlet;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class CartCheckout
*/
#WebServlet("/CartCheckout")
public class CartCheckout extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public CartCheckout() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String count=request.getParameter("ItemCount");
ArrayList<String> item_detail=new ArrayList<String>();
int cnt=Integer.parseInt(count);
for(int i=1;i<cnt+1;i++)
{
String name=request.getParameter("item_name_");
item_detail.add(name);
String price=request.getParameter("item_price_");
item_detail.add(price);
String qty=request.getParameter("item_quantity_");
item_detail.add(qty);
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String count=request.getParameter("ItemCount");
ArrayList<String> item_detail=new ArrayList<String>();
int cnt=Integer.parseInt(count);
for(int i=1;i<cnt+1;i++)
{
String name=request.getParameter("item_name_");
item_detail.add(name);
String price=request.getParameter("item_price_");
item_detail.add(price);
String qty=request.getParameter("item_quantity_");
item_detail.add(qty);
}
}
}
Stacktrace
Sep 01, 2014 1:15:51 PM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: /usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib
Sep 01, 2014 1:15:51 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:Agro' did not find a matching property.
Sep 01, 2014 1:15:51 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-nio-8080"]
Sep 01, 2014 1:15:51 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Sep 01, 2014 1:15:51 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-nio-8009"]
Sep 01, 2014 1:15:51 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Sep 01, 2014 1:15:51 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 763 ms
Sep 01, 2014 1:15:51 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Sep 01, 2014 1:15:51 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/8.0.9
Sep 01, 2014 1:15:52 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
Sep 01, 2014 1:15:52 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8009"]
Sep 01, 2014 1:15:52 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 1316 ms
Sep 01, 2014 1:15:59 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [Cart_Checkout] in context with path [/Agro] threw exception
java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:454)
at java.lang.Integer.parseInt(Integer.java:527)
at com.kunal.servlet.CartCheckout.doPost(CartCheckout.java:53)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:644)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:136)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:526)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1078)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:655)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1566)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1523)
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:745)
You should capture the request that is being sent to your webservice.
In the error you can see that you get a NumberFormatException: null. This suggests that your count String is null.
String count=request.getParameter("ItemCount");
This can happen when ItemCount is not a parameter of your request.
It would be good practice to test count (= "ItemCount" parameter) for null values in your code, so that you can return a nice looking error to your client.
It is because your count variable is null you can avoid it by
String count=request.getParameter("ItemCount");
if(count.length()>0){
int cnt=Integer.parseInt(count.trim());
// other logic
}
else{
//do nothing
}
The cause of the problem is quite straightforward:
int cnt=Integer.parseInt(count);
this is pointed out clearly from your stack trace:
at com.kunal.servlet.CartCheckout.doPost(CartCheckout.java:53)
A simple solution would be to check the count against null, hence change your doPost (..) implementation into:
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String count=request.getParameter("ItemCount");
ArrayList<String> item_detail=new ArrayList<String>();
int cnt= count == null 0 : Integer.parseInt(count);
for(int i=1;i<cnt+1;i++)
{
String name=request.getParameter("item_name_");
item_detail.add(name);
String price=request.getParameter("item_price_");
item_detail.add(price);
String qty=request.getParameter("item_quantity_");
item_detail.add(qty);
}
}
In order to ensure that you'll not encounter the same issue with empty strings, you can check also for empty strings. If using other libraries is an option I would suggest using StringUtils.isNotBlank(..)
then your parsing line becomes:
int cnt= StringUtils.isNotBlank(count) 0 : Integer.parseInt(count);

Categories