PersistStudent.Java
package com.jpaExample;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class PersistStudent {
public static void main(String[] args)
{
EntityManagerFactory emf= Persistence.createEntityManagerFactory("Student_details");
EntityManager em=emf.createEntityManager();
em.getTransaction().begin();
StudentEntity s=em.find(StudentEntity.class,2);
//em.remove(s);
System.out.println("Before update");
System.out.println(s.getId());
System.out.println(s.getName());
System.out.println(s.getMarks());
s.setMarks(92);
System.out.println("after update");
System.out.println(s.getId());
System.out.println(s.getName());
System.out.println(s.getMarks());
em.getTransaction().commit();
emf.close();
em.close();
}
}
StudentEntity.java
package com.jpaExample;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="studentdetails")
public class StudentEntity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
private int marks;
public StudentEntity()
{
super();
}
public StudentEntity(int id, String name, int marks)
{
this.id=id;
this.name=name;
this.marks=marks;
}
public int getId()
{
return id;
}
public void setId(int id)
{
this.id=id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getMarks() {
return marks;
}
public void setMarks(int marks) {
this.marks = marks;
}
}
Persistence.xml which i placed inside META-INF
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="Student_details" transaction-type ="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.jpaExample.StudentEntity</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="oracle.jdbc.driver.OracleDriver"></property>
<property name="javax.persistence.jdbc.url" value="jdbc:oracle:thin:#localhost:1521:xe"></property>
<property name="javax.persistence.jdbc.user" value="student"></property>
<property name="javax.persistence.jdbc.password" value="student"></property>
</properties>
</persistence-unit>
</persistence>
whenever I try to run this code I am getting this error, I am using oracle as a JDBC driver it's saying as SQL grammatic error.org.hibernate.exception.SQLGrammarException: JDBC exception executing SQL [select s1_0.id, s1_0.marks, s1_0.name from studentdetails as s1_0 where s1_0.id = ?]
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: JDBC exception executing SQL [select s1_0.id, s1_0.marks, s1_0.name from studentdetails as s1_0 where s1_0.id = ?]
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:154)
May 05, 2021 3:18:54 PM org.hibernate.jpa.boot.spi.ProviderChecker hibernateProviderNamesContain
WARN: HHH015016: Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb.HibernatePersistence]; [org.hibernate.jpa.HibernatePersistenceProvider] will be used instead.
May 05, 2021 3:18:54 PM org.hibernate.jpa.internal.util.LogHelper logPersistenceUnitInformation
INFO: HHH000204: Processing PersistenceUnitInfo [name: Student_details]
May 05, 2021 3:18:54 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {6.0.0.Alpha4}
May 05, 2021 3:18:54 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
May 05, 2021 3:18:55 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
May 05, 2021 3:18:55 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [oracle.jdbc.driver.OracleDriver] at URL [jdbc:oracle:thin:#localhost:1521:xe]
May 05, 2021 3:18:55 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=student, password=****}
May 05, 2021 3:18:55 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
May 05, 2021 3:18:55 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
May 05, 2021 3:18:55 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.Oracle10gDialect
May 05, 2021 3:18:57 PM org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator initiateService
INFO: HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
May 05, 2021 3:18:57 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 933, SQLState: 42000
May 05, 2021 3:18:57 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: ORA-00933: SQL command not properly ended
May 05, 2021 3:18:57 PM org.hibernate.event.internal.DefaultLoadEventListener doOnLoad
INFO: HHH000327: Error performing load command : org.hibernate.exception.SQLGrammarException: JDBC exception executing SQL [select s1_0.id, s1_0.marks, s1_0.name from studentdetails as s1_0 where s1_0.id = ?]
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: JDBC exception executing SQL [select s1_0.id, s1_0.marks, s1_0.name from studentdetails as s1_0 where s1_0.id = ?]
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:154)
at org.hibernate.internal.SessionImpl.find(SessionImpl.java:2805)
at org.hibernate.internal.SessionImpl.find(SessionImpl.java:2737)
at com.jpaExample.PersistStudent.main(PersistStudent.java:17)
Caused by: org.hibernate.exception.SQLGrammarException: JDBC exception executing SQL [select s1_0.id, s1_0.marks, s1_0.name from studentdetails as s1_0 where s1_0.id = ?]
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:63)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:99)
at org.hibernate.sql.results.jdbc.internal.DeferredResultSetAccess.executeQuery(DeferredResultSetAccess.java:111)
at org.hibernate.sql.results.jdbc.internal.DeferredResultSetAccess.getResultSet(DeferredResultSetAccess.java:54)
at org.hibernate.sql.results.jdbc.internal.JdbcValuesResultSetImpl.processNext(JdbcValuesResultSetImpl.java:113)
at org.hibernate.sql.results.jdbc.internal.AbstractJdbcValues.next(AbstractJdbcValues.java:33)
at org.hibernate.sql.results.internal.RowProcessingStateStandardImpl.next(RowProcessingStateStandardImpl.java:67)
at org.hibernate.sql.results.spi.ListResultsConsumer.consume(ListResultsConsumer.java:56)
at org.hibernate.sql.results.spi.ListResultsConsumer.consume(ListResultsConsumer.java:23)
at org.hibernate.sql.exec.internal.JdbcSelectExecutorStandardImpl.executeQuery(JdbcSelectExecutorStandardImpl.java:191)
at org.hibernate.sql.exec.internal.JdbcSelectExecutorStandardImpl.list(JdbcSelectExecutorStandardImpl.java:71)
at org.hibernate.loader.ast.internal.SingleIdLoadPlan.load(SingleIdLoadPlan.java:123)
at org.hibernate.loader.ast.internal.SingleIdEntityLoaderStandardImpl.load(SingleIdEntityLoaderStandardImpl.java:62)
at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:4432)
at org.hibernate.event.internal.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:567)
at org.hibernate.event.internal.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:535)
at org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:208)
at org.hibernate.event.internal.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:330)
at org.hibernate.event.internal.DefaultLoadEventListener.doOnLoad(DefaultLoadEventListener.java:108)
at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:74)
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:118)
at org.hibernate.internal.SessionImpl.fireLoadNoChecks(SessionImpl.java:1142)
at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1131)
at org.hibernate.internal.SessionImpl.access$2000(SessionImpl.java:167)
at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.doLoad(SessionImpl.java:2239)
at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.lambda$load$1(SessionImpl.java:2220)
at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.perform(SessionImpl.java:2176)
at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.load(SessionImpl.java:2220)
at org.hibernate.internal.SessionImpl.find(SessionImpl.java:2770)
... 2 more
Caused by: java.sql.SQLSyntaxErrorException: ORA-00933: SQL command not properly ended
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:447)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:396)
at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:951)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:513)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:227)
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:531)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:208)
at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:886)
at oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:1175)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1296)
at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3613)
at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:3657)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeQuery(OraclePreparedStatementWrapper.java:1495)
at org.hibernate.sql.results.jdbc.internal.DeferredResultSetAccess.executeQuery(DeferredResultSetAccess.java:102)
... 28 more
Oracle does not have a separator between the table name and alias in the from clause, so I guess you are either using a wrong/unsupported native query or the configured Hibernate dialect is wrong.
Related
For some reason it does not find Polica even tho i have mapped it in code, created seperate file to map it etc. What is the problem?
In file PolicaDAO2 i am also getting createQuery deprecated for some reason if anyone knows solution to this aswell let me know. I tried multiple things aswell as you can see in the file under findall() function
Exception:
Aug 09, 2022 12:41:34 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate ORM core version 6.1.2.Final
Aug 09, 2022 12:41:40 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using built-in connection pool (not intended for production use)
Aug 09, 2022 12:41:40 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: Loaded JDBC driver class: com.mysql.cj.jdbc.Driver
Aug 09, 2022 12:41:40 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001012: Connecting with JDBC URL [jdbc:mysql://127.0.0.1:3306/Wallboard]
Aug 09, 2022 12:41:40 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {password=****, user=root}
Aug 09, 2022 12:41:40 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Aug 09, 2022 12:41:40 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH10001115: Connection pool size: 20 (min=1)
Aug 09, 2022 12:41:43 PM org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl logSelectedDialect
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Aug 09, 2022 12:41:47 PM org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator initiateService
INFO: HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
Aug 09, 2022 12:41:47 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using built-in connection pool (not intended for production use)
Aug 09, 2022 12:41:47 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: Loaded JDBC driver class: com.mysql.cj.jdbc.Driver
Aug 09, 2022 12:41:47 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001012: Connecting with JDBC URL [jdbc:mysql://127.0.0.1:3306/Wallboard]
Aug 09, 2022 12:41:47 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {password=****, user=root}
Aug 09, 2022 12:41:47 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Aug 09, 2022 12:41:47 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH10001115: Connection pool size: 20 (min=1)
Aug 09, 2022 12:41:48 PM org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl logSelectedDialect
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Aug 09, 2022 12:41:48 PM org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator initiateService
INFO: HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
Exception in thread "main" java.lang.IllegalArgumentException: org.hibernate.query.sqm.UnknownEntityException: Could not resolve root entity 'Polica'
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:138)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:175)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:182)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:761)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:663)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:127)
at digiwallboard.DAO.PolicaDAO2.findAll(PolicaDAO2.java:81)
at digiwallboard.Service.PolicaService.findAll(PolicaService.java:18)
at Main.main(Main.java:27)
Caused by: org.hibernate.query.sqm.UnknownEntityException: Could not resolve root entity 'Polica'
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitRootEntity(SemanticQueryBuilder.java:1628)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitRootEntity(SemanticQueryBuilder.java:243)
at org.hibernate.grammars.hql.HqlParser$RootEntityContext.accept(HqlParser.java:1874)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitEntityWithJoins(SemanticQueryBuilder.java:1548)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitFromClause(SemanticQueryBuilder.java:1539)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitQuery(SemanticQueryBuilder.java:833)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitQuerySpecExpression(SemanticQueryBuilder.java:629)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitQuerySpecExpression(SemanticQueryBuilder.java:243)
at org.hibernate.grammars.hql.HqlParser$QuerySpecExpressionContext.accept(HqlParser.java:1218)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitSimpleQueryGroup(SemanticQueryBuilder.java:623)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitSimpleQueryGroup(SemanticQueryBuilder.java:243)
at org.hibernate.grammars.hql.HqlParser$SimpleQueryGroupContext.accept(HqlParser.java:1131)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitSelectStatement(SemanticQueryBuilder.java:399)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitStatement(SemanticQueryBuilder.java:358)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.buildSemanticModel(SemanticQueryBuilder.java:285)
at org.hibernate.query.hql.internal.StandardHqlTranslator.translate(StandardHqlTranslator.java:81)
at org.hibernate.internal.AbstractSharedSessionContract.lambda$createQuery$2(AbstractSharedSessionContract.java:748)
at org.hibernate.query.internal.QueryInterpretationCacheStandardImpl.createHqlInterpretation(QueryInterpretationCacheStandardImpl.java:141)
at org.hibernate.query.internal.QueryInterpretationCacheStandardImpl.resolveHqlInterpretation(QueryInterpretationCacheStandardImpl.java:128)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:745)
... 5 more
Main.java
import digiwallboard.Util.HibernateUtil;
import digiwallboard.Entity.*;
import java.util.List;
import digiwallboard.DAO.*;
import digiwallboard.Service.PolicaService;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
PolicaService policaService = new PolicaService();
List<Polica> pol = policaService.findAll();
for(Polica p : pol) {
System.out.println("-" + p.toString());
}
}
}
PolicaDAO2.java
package digiwallboard.DAO;
import java.util.List;
import javax.persistence.TypedQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import digiwallboard.Entity.Polica;
public class PolicaDAO2 implements PolicaDaoInterface<Polica, String> {
private Session currentSession;
private Transaction currentTransaction;
public PolicaDAO2() {
}
public Session openCurrentSession() {
currentSession = getSessionFactory().openSession();
return currentSession;
}
public Session openCurrentSessionwithTransaction() {
currentSession = getSessionFactory().openSession();
currentTransaction = currentSession.beginTransaction();
return currentSession;
}
public void closeCurrentSession() {
currentSession.close();
}
public void closeCurrentSessionwithTransaction() {
currentTransaction.commit();
currentSession.close();
}
private static SessionFactory getSessionFactory() {
Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
configuration.addAnnotatedClass(Polica.class);
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
SessionFactory sessionFactory = configuration.buildSessionFactory(builder.build());
return sessionFactory;
}
public Session getCurrentSession() {
return currentSession;
}
public void setCurrentSession(Session currentSession) {
this.currentSession = currentSession;
}
public Transaction getCurrentTransaction() {
return currentTransaction;
}
public void setCurrentTransaction(Transaction currentTransaction) {
this.currentTransaction = currentTransaction;
}
#SuppressWarnings("deprecation")
public void persist(Polica entity) {
getCurrentSession().save(entity);
}
#SuppressWarnings({ "unchecked", "deprecation" })
public List<Polica> findAll() {
Session session = openCurrentSession();
TypedQuery<Polica> result = (TypedQuery<Polica>) openCurrentSession().createQuery("FROM Polica");
List<Polica> result = query.getResultList();
closeCurrentSession();
/*
Query query = getCurrentSession().createQuery("select * from Polica");
List<Polica> pol = (List<Polica>) getCurrentSession().createNativeQuery("from Polica").list();
return pol;
*/
return result;
/*
TypedQuery<Polica> query = createQuery( "select * from Polica");
return query.getResultList();
*/
}
}
PolicaDaoInterface.java
package digiwallboard.DAO;
import java.io.Serializable;
import java.util.List;
public interface PolicaDaoInterface<T, Id extends Serializable> {
public List<T> findAll();
}
Polica.java
EDIT: IF YOU ARE USING HIBERNATE 6.0+ DO NOT USE JAVAX.PERSISTENCE LIKE I DID HERE THIS IS ONE OF THE REASONS I WAS GETTING THE EXCEPTION INSTEAD USE JAKARTA.PERSISTENCE
package digiwallboard.Entity;
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 = "Polica")
public class Polica {
#Id
#Column(name="id")
private int id;
#Column(name="ime_pol")
private String ime_pol;
public Polica() {
}
public Polica(int id, String ime_pol) {
super();
this.id = id;
this.ime_pol = ime_pol;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getIme_pol() {
return ime_pol;
}
public void setIme_pol(String ime_pol) {
this.ime_pol = ime_pol;
}
#Override
public String toString() {
return "Polica [id=" + id + ", ime_pol=" + ime_pol + "]";
}
}
PolicaService.java
package digiwallboard.Service;
import java.util.List;
import digiwallboard.DAO.PolicaDAO2;
import digiwallboard.Entity.Polica;
public class PolicaService {
private static PolicaDAO2 policaDao;
public PolicaService() {
policaDao = new PolicaDAO2();
}
public List<Polica> findAll() {
policaDao.openCurrentSession();
List<Polica> police = policaDao.findAll();
policaDao.closeCurrentSession();
return police;
}
}
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>
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">Root123</property>
<property name="hibernate.connection.url">jdbc:mysql://127.0.0.1:3306/Wallboard</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<!-- <mapping class="springfoxdemo.java.swagger.Polica" resource="springfoxdemo/java/swagger/Polica.hbm.xml"/> -->
<mapping class="digiwallboard.Entity.Polica"/>
</session-factory>
</hibernate-configuration>
hibernate.hbm.xml
<?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="digiwallboard.Entity.Polica" table="Polica">
<id name="id" type="int" column="id">
<column name="id" />
</id>
<property name="ime_pol" column="ime_pol"
type="String">
</property>
</class>
</hibernate-mapping>
First of all, to avoid deprecation warnings, you should use the type safe variant of createQuery:
TypedQuery<Polica> result = openCurrentSession().createQuery("FROM Polica", Polica.class);
It's hard to say why your code is not working, but I have a few ideas what you could try. Note that you don't reference the hibernate.hbm.xml file anywhere and you commented out the reference to some other file Polica.hbm.xml, though the contents are unnecessary anyway as the annotations on the entity class are enough.
You are correctly listing the class through <mapping class="digiwallboard.Entity.Polica"/>, so it should be picked up by Hibernate. My guess is, that either some of your hbm.xml files that you might reference in your real app are interfering somehow, i.e. registering the entity type under a different name, or that your configuration is not picked up for some reason.
You can check which entities Hibernate found by inspecting getSessionFactory().getMetamodel().getEntities(), and if you find your entity there, check what EntityType#getName() reports, as that is the under which you can use the entity in HQL.
I have Eclipse and Hibernate that connect to Azure Sql Server (Microsoft Azure for Students). I uploaded to a git the project that works perfectly on the school pc with Windows but here on my Mac can not connect to server ... The only difference is the Hibernate Library & JDBC library, the code it's the same. :(
output:
Jan 11, 2017 4:03:51 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.1.3.Final}
Jan 11, 2017 4:03:51 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Jan 11, 2017 4:03:51 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Jan 11, 2017 4:03:52 PM org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver resolveEntity
WARN: HHH90000012: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-configuration. Use namespace http://www.hibernate.org/dtd/hibernate-configuration instead. Support for obsolete DTD/XSD namespaces may be removed at any time.
Jan 11, 2017 4:03:52 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Jan 11, 2017 4:03:52 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Jan 11, 2017 4:03:52 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.microsoft.sqlserver.jdbc.SQLServerDriver] at URL [jdbc:sqlserver://usedproy.database.windows.net:1433;database=used;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;]
Jan 11, 2017 4:03:52 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=usuario#usedproy, password=****}
Jan 11, 2017 4:03:52 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Jan 11, 2017 4:03:52 PM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Failed to create sessionFactory object.org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
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:264)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:228)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:207)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:207)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:83)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:418)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:87)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:692)
at probandohibernate.PersonFactory.<clinit>(PersonFactory.java:31)
at probandohibernate.ProbandoHibernate.insert(ProbandoHibernate.java:55)
at probandohibernate.ProbandoHibernate.main(ProbandoHibernate.java:23)
Caused by: org.hibernate.exception.JDBCConnectionException: Error calling Driver#connect
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:115)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator$1$1.convert(BasicConnectionCreator.java:101)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.convertSqlException(BasicConnectionCreator.java:123)
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.PooledConnections.addConnections(PooledConnections.java:106)
at org.hibernate.engine.jdbc.connections.internal.PooledConnections.<init>(PooledConnections.java:40)
at org.hibernate.engine.jdbc.connections.internal.PooledConnections.<init>(PooledConnections.java:19)
at org.hibernate.engine.jdbc.connections.internal.PooledConnections$Builder.build(PooledConnections.java:138)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.buildPool(DriverManagerConnectionProviderImpl.java:110)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:74)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:207)
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:88)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:254)
... 15 more
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: SQL Server did not return a response. The connection has been closed. ClientConnectionId:c2231f63-42b7-473b-8cab-e16e8473cb31
at com.microsoft.sqlserver.jdbc.SQLServerConnection.terminate(SQLServerConnection.java:1667)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.terminate(SQLServerConnection.java:1654)
at com.microsoft.sqlserver.jdbc.TDSReader.readPacket(IOBuffer.java:4844)
at com.microsoft.sqlserver.jdbc.TDSCommand.startResponse(IOBuffer.java:6154)
at com.microsoft.sqlserver.jdbc.TDSCommand.startResponse(IOBuffer.java:6106)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.sendLogon(SQLServerConnection.java:2907)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.logon(SQLServerConnection.java:2234)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.access$000(SQLServerConnection.java:41)
at com.microsoft.sqlserver.jdbc.SQLServerConnection$LogonCommand.doExecute(SQLServerConnection.java:2220)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:5696)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1715)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1326)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:991)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:827)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1012)
at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:38)
... 30 more
Exception in thread "main" java.lang.NullPointerException
at probandohibernate.ProbandoHibernate.insert(ProbandoHibernate.java:82)
at probandohibernate.ProbandoHibernate.main(ProbandoHibernate.java:23)
Hibernate conf:
<?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 name="Hibernate">
<property name="hibernate.dialect">org.hibernate.dialect.SQLServer2008Dialect</property>
<property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="hibernate.connection.url">jdbc:sqlserver://***.database.windows.net:1433;database=****;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;</property>
<property name="hibernate.connection.username">***#***</property>
<property name="hibernate.connection.password">***</property>
<property name="show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping class="probandohibernate.modelo.Empleados"/>
</session-factory>
</hibernate-configuration>
Java Class:
package probandohibernate.modelo;
/**
*
* #author leo
*/
import java.sql.Date;
import javax.persistence.*;
/**
*
* #author John
*/
#Entity
#Table(name = "Empleados")
public class Empleados {
#Id
#GeneratedValue(strategy= GenerationType.IDENTITY) //Editado
private Long id;
#Column(name = "Nombre")
private String nombre;
#Column(name = "Apellidos")
private String apellido;
#Column(name = "FechaNacimiento")
private Date fechaNacimiento;
#Column(name = "Movil")
private String movil;
public Empleados() {
}
public Empleados(String nombre, String apellido, Date fechaNacimiento, String movil) {
this.nombre = nombre;
this.apellido = apellido;
this.fechaNacimiento = fechaNacimiento;
this.movil = movil;
}
public Long getId() {
return id;
}
public String getNombre() {
return nombre;
}
public String getApellido() {
return apellido;
}
public Date getFechaNacimiento() {
return fechaNacimiento;
}
public String getMovil() {
return movil;
}
public void setId(Long id) {
this.id = id;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public void setApellido(String apellido) {
this.apellido = apellido;
}
public void setFechaNacimiento(Date fechaNacimiento) {
this.fechaNacimiento = fechaNacimiento;
}
public void setMovil(String movil) {
this.movil = movil;
}
#Override
public String toString() {
return "Empleado [id=" + id + ", nombre=" + nombre + ", apellido=" + apellido + ", fechaNacimiento="
+ fechaNacimiento + ", movil=" + movil + "]";
}
}
Hibernate Class:
package probandohibernate;
/**
*
* #author leo
*/
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import probandohibernate.modelo.Empleados;
public class PersonFactory {
private static ServiceRegistry serviceRegistry;
private static final SessionFactory sessionFactory;
static {
try {
Configuration configuration=new Configuration()
.configure(); // configures settings from hibernate.cfg.xml
configuration.addAnnotatedClass(Empleados.class);
StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
// If you miss the below line then it will complaing about a missing dialect setting
serviceRegistryBuilder.applySettings(configuration.getProperties());
serviceRegistry = serviceRegistryBuilder.build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
ex.printStackTrace();
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
private static void read(){
Session session = null;
try {
try {
sessionFactory = PersonFactory.getSessionFactory();
session = sessionFactory.openSession();
#SuppressWarnings("unchecked")
List<Empleados> list = session.createQuery("from Empleados")
.list();
for (Empleados p : list)
System.out.println(p);
} catch (Exception e) {
e.printStackTrace();
}
} finally {
session.close();
}
}
Libraries:
Update:
I just disabled the firewall of Sierra and of Avast and a get this Exception.
Jan 13, 2017 12:40:54 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.1.0.Final}
Jan 13, 2017 12:40:54 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Jan 13, 2017 12:40:54 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Jan 13, 2017 12:40:54 AM org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver resolveEntity
WARN: HHH90000012: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-configuration. Use namespace http://www.hibernate.org/dtd/hibernate-configuration instead. Support for obsolete DTD/XSD namespaces may be removed at any time.
Jan 13, 2017 12:40:54 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Jan 13, 2017 12:40:54 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Jan 13, 2017 12:40:54 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.microsoft.sqlserver.jdbc.SQLServerDriver] at URL [jdbc:sqlserver://usedproy.database.windows.net:1433;database=used;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;]
Jan 13, 2017 12:40:54 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=usuario#usedproy, password=****}
Jan 13, 2017 12:40:54 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Jan 13, 2017 12:40:54 AM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Failed to create sessionFactory object.org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
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:244)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:208)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:189)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:217)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:189)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:83)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:418)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:87)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:692)
at probandohibernate.PersonFactory.<clinit>(PersonFactory.java:34)
at probandohibernate.ProbandoHibernate.insert(ProbandoHibernate.java:65)
at probandohibernate.ProbandoHibernate.main(ProbandoHibernate.java:30)
Caused by: org.hibernate.exception.JDBCConnectionException: Error calling Driver#connect
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:115)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator$1$1.convert(BasicConnectionCreator.java:101)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.convertSqlException(BasicConnectionCreator.java:123)
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.PooledConnections.addConnections(PooledConnections.java:106)
at org.hibernate.engine.jdbc.connections.internal.PooledConnections.<init>(PooledConnections.java:40)
at org.hibernate.engine.jdbc.connections.internal.PooledConnections.<init>(PooledConnections.java:19)
at org.hibernate.engine.jdbc.connections.internal.PooledConnections$Builder.build(PooledConnections.java:138)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.buildPool(DriverManagerConnectionProviderImpl.java:110)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:74)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:217)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:189)
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:88)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:234)
... 15 more
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Connection reset ClientConnectionId:93c921a0-b8bf-48fe-b3da-0064cc309d63
at com.microsoft.sqlserver.jdbc.SQLServerConnection.terminate(SQLServerConnection.java:1667)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.terminate(SQLServerConnection.java:1654)
at com.microsoft.sqlserver.jdbc.TDSChannel.read(IOBuffer.java:1789)
at com.microsoft.sqlserver.jdbc.TDSReader.readPacket(IOBuffer.java:4838)
at com.microsoft.sqlserver.jdbc.TDSCommand.startResponse(IOBuffer.java:6154)
at com.microsoft.sqlserver.jdbc.TDSCommand.startResponse(IOBuffer.java:6106)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.sendLogon(SQLServerConnection.java:2907)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.logon(SQLServerConnection.java:2234)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.access$000(SQLServerConnection.java:41)
at com.microsoft.sqlserver.jdbc.SQLServerConnection$LogonCommand.doExecute(SQLServerConnection.java:2220)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:5696)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1715)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1326)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:991)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:827)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1012)
at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:38)
... 30 more
Exception in thread "main" java.lang.NullPointerException
at probandohibernate.ProbandoHibernate.insert(ProbandoHibernate.java:92)
at probandohibernate.ProbandoHibernate.main(ProbandoHibernate.java:30)
- More info:
If help something with JDBC doesn't work too
Code of JDBC:
package es.iesnervion.model;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MakingStatement {
public static void main(String[] args) {
// Carga el driver
try {
// Carga la clase del driver
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
// Define the data source for the driver
String sourceURL = "jdbc:sqlserver://******.database.windows.net:1433;database=***;user=***#usedproy;password=****;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;";
String miSelect = "SELECT ID, Nombre FROM Empleados";
// Crear una connexi�n con el DriverManager
Connection connexionBaseDatos =
DriverManager.getConnection(sourceURL);
Statement sentencia = connexionBaseDatos.createStatement();
ResultSet nombresProductos = sentencia.executeQuery(miSelect);
// Mostrar los datos del ResultSet
System.out.println("Productos -> PVP");
System.out.println("------------------------------------------");
while (nombresProductos.next())
System.out.println(nombresProductos.getString("Nombre")+ " -> " +
nombresProductos.getInt("ID"));
// Cerrar conexi�n
connexionBaseDatos.close();
}
catch (ClassNotFoundException cnfe) {
System.err.println(cnfe);
}
catch (SQLException sqle) {
sqle.printStackTrace();
}
}
}
According to your comments, the issue seems to be the same as the SO thread SQL Server JDBC Error on Java 8: The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption, please follow the answer for the existing SO thread & the reference for properties configuration of connection string to try to solve it. Any update, please feel free to let me know.
After a lot of reading and trying solutions from around the web, I've decided to ask for help because none of the solutions tried worked for me.
I have a very simple class which has a LocalDateTime variable.
I have created a MySQL table where I want to store the object containing this variable. For the LocalDateTime variable I've tried DateTime and TimeStamp types.
As far as I read, Hibernate 5 is supposed to support java.time.localdatetime. As I said, I've tried to use timestamp type and date, as long as timestamp and datetime as Mysql column types.
Always the same error.
This is a new project I am starting and I want to start using new Java 8 DateTime.
Here I attach all the classes and configuration files.
This is the Fecha.java, the object I want to map on my Mysql Table.
#Entity
#Table(name = "Fecha", catalog = "qtx590", uniqueConstraints = { #UniqueConstraint(columnNames = { "_id" }) })
public class Fecha implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "_id", nullable = false, unique = true)
private int _id;
#Column(name = "_idEmpresa", nullable = false)
private int _idEmpresa;
#Column(name = "_idTurno", nullable = false)
private int _idTurno;
#Column(name = "Momento", nullable = false)
#Temporal(TemporalType.TIMESTAMP)
private LocalDateTime momento;
public Fecha() {
this._id = 99999;
this._idEmpresa = 99999;
this._idTurno = 99999;
this.momento = LocalDateTime.now();
}
public Fecha(int _id, int _idEmpresa, int idTurno, LocalDateTime momento) {
this._id = _id;
this._idEmpresa = _idEmpresa;
this._idTurno = idTurno;
this.momento = momento;
}
public String getMomentoString() {
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
return this.momento.format(format);
}
public int get_id() {
return _id;
}
public void set_id(int _id) {
this._id = _id;
}
public int get_idEmpresa() {
return _idEmpresa;
}
public void set_idEmpresa(int _idEmpresa) {
this._idEmpresa = _idEmpresa;
}
public int get_idTurno() {
return _idTurno;
}
public void set_idTurno(int idTurno) {
this._idTurno = idTurno;
}
public LocalDateTime getmomento() {
return momento;
}
public void setmomento(LocalDateTime momento) {
this.momento = momento;
}
}
This is the HibernateConnectorClass
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateConnector {
private static HibernateConnector me;
private Configuration cfg;
private SessionFactory sessionFactory;
private HibernateConnector() throws HibernateException {
cfg = new Configuration();
sessionFactory = cfg.configure().buildSessionFactory();
}
public static synchronized HibernateConnector getInstance() throws HibernateException {
if (me == null) {
me = new HibernateConnector();
}
return me;
}
public Session getSession() throws HibernateException {
Session session = sessionFactory.openSession();
if (!session.isConnected()) {
this.reconnect();
}
return session;
}
private void reconnect() throws HibernateException {
this.sessionFactory = cfg.buildSessionFactory();
}
}
This is the test class to test it:
public class Prueba {
public static void main(String[] args) {
// TODO Auto-generated method stub
FechaDAO fechaDAO = new FechaDAO();
Fecha f = new Fecha();
System.out.println(f.getmomento());
fechaDAO.insertar(f);
System.out.println("FIN");
}
}
The hibernate.cfg.xml is working fine ( I know it because I tested it with other entity / table.
This is the specific for Fecha Object
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated 31-ago-2015 12:58:20 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="Fecha" table="Fecha">
<id name="_id" type="java.lang.Integer" access="field">
<column name="_id" />
<generator class="increment" />
</id>
<property name="_idEmpresa" type="java.lang.Integer" access="field">
<column name="_idEmpresa" />
</property>
<property name="_idTurno" type="java.lang.Integer">
<column name="_idTurno" />
</property>
<property name="momento" type="java.time.LocalDateTime">
<column name="Momento" />
</property>
</class>
</hibernate-mapping>
And this the error:
2015-09-02T13:47:16.719
sep 02, 2015 1:47:16 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.0.0.Final}
sep 02, 2015 1:47:16 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
sep 02, 2015 1:47:16 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
sep 02, 2015 1:47:16 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.0.Final}
sep 02, 2015 1:47:17 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
sep 02, 2015 1:47:17 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://qtx590.li-bra.es:3306/qtx590]
sep 02, 2015 1:47:17 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=qtx590, password=****}
sep 02, 2015 1:47:17 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
sep 02, 2015 1:47:17 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
sep 02, 2015 1:47:17 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
sep 02, 2015 1:47:17 PM org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
Hibernate: select max(_id) from Fecha
Hibernate: insert into Fecha (_idEmpresa, _idTurno, Momento, _id) values (?, ?, ?, ?)
sep 02, 2015 1:47:18 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 0, SQLState: 22001
sep 02, 2015 1:47:18 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Data truncation: Incorrect datetime value: '’' for column 'Momento' at row 1
sep 02, 2015 1:47:18 PM org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl release
INFO: HHH000010: On release of batch it still contained JDBC statements
sep 02, 2015 1:47:18 PM org.hibernate.internal.SessionImpl$5 mapManagedFlushFailure
ERROR: HHH000346: Error during managed flush [could not execute statement]
org.hibernate.exception.DataException: could not execute statement
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:52)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:109)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:95)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:207)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:45)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2823)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3323)
at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:89)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:447)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:333)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:335)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1224)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:464)
at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:2890)
at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2266)
at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:485)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:146)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java:38)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:230)
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:65)
at FechaDAO.insertar(FechaDAO.java:26)
at Prueba.main(Prueba.java:16)
Caused by: com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect datetime value: '’' for column 'Momento' at row 1
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2983)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1631)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1723)
at com.mysql.jdbc.Connection.execSQL(Connection.java:3283)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1332)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1604)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1519)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1504)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:204)
... 19 more
Hibernate: insert into Fecha (_idEmpresa, _idTurno, Momento, _id) values (?, ?, ?, ?)
sep 02, 2015 1:47:18 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 0, SQLState: 22001
sep 02, 2015 1:47:18 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Data truncation: Incorrect datetime value: '’' for column 'Momento' at row 1
sep 02, 2015 1:47:18 PM org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl release
INFO: HHH000010: On release of batch it still contained JDBC statements
Exception in thread "main" org.hibernate.exception.DataException: could not execute statement
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:52)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:109)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:95)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:207)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:45)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2823)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3323)
at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:89)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:447)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:333)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:335)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1224)
at FechaDAO.insertar(FechaDAO.java:32)
at Prueba.main(Prueba.java:16)
Caused by: com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect datetime value: '’' for column 'Momento' at row 1
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2983)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1631)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1723)
at com.mysql.jdbc.Connection.execSQL(Connection.java:3283)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1332)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1604)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1519)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1504)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:204)
... 11 more
IIRC for Hibernate5 to map java.time.* no #Temporal annotation is needed/accepted. Hibernate5 have sufficient information to judge the mapping from the type of the property. This is stated in their document.
Java 8 support in Hibernate 5 but this is not portable to other JPA implementations. Add dependencies as below and no more configurations
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-java8</artifactId>
<version>5.1.0.Final</version>
</dependency>
For further reading : Hibernate 5: How to persist LocalDateTime & Co with Hibernate
This question already has answers here:
Hibernate - does it change the structure of a database?
(3 answers)
Closed 8 years ago.
Using Java and hibernate, I was wondering that if I can change the Database definition after creation, just by making changes to my existing Entity Class. Will the Changes be reflected in the Database??? Is it Possible??? I tried and Failed. I have tried
<property name="hibernate.hbm2ddl.auto">update</property>
But getting error, if it is still possible, here is my code.
/**
* Description of bankbranchcontactdetailsBean
*
* #author Vishal Jain # TurtleTec Inc.
*/
package com.beans;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.TableGenerator;
import javax.persistence.Id;
import javax.persistence.Column;
import javax.persistence.Temporal;
import javax.persistence.UniqueConstraint;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import java.io.Serializable;
import java.util.Date;
#Entity(name = "bankbranchcontactdetails")
#Table(name = "bankbranchcontactdetails", schema = "stserptest", uniqueConstraints = { #UniqueConstraint(columnNames = "BankBranchContactId") })
#TableGenerator(name = "bankbranchcontactdetailsgen", table = "bankbranchcontactdetails", pkColumnName = "BankBranchContactId")
public class bankbranchcontactdetailsBean extends SuperBeanClass implements
SuperBeanInterface, Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(columnDefinition = "INT(10) UNSIGNED", name = "BankBranchContactId", precision = 10, scale = 0, nullable = false, unique = true)
private Integer Id;
#Column(columnDefinition = "INT(10) UNSIGNED", name = "BankBranchId", precision = 10, scale = 0, nullable = false)
private Integer _BankBranchId;
#Column(columnDefinition = "ENUM('PHONE','MOBILE','FAX','TELEX')", name = "ContactTypeModified", length = 6, nullable = false)
private String _ContactTypeModified;
#Column(columnDefinition = "VARCHAR(20)", name = "Contact", length = 20, nullable = false)
private String _Contact;
#Column(columnDefinition = "INT(10) UNSIGNED", name = "NewField", precision = 10, scale = 0, nullable = true)
private Integer _NewField;
public bankbranchcontactdetailsBean() {
_BankBranchId = 0;
_ContactType = "";
_Contact = "";
_NewField = 0;
}
public bankbranchcontactdetailsBean(Integer __BankBranchId,
String __ContactTypeModified String __Contact, Integer __MyCompanyId) {
_BankBranchId = __BankBranchId;
_ContactTypeModified = __ContactTypeModified;
_Contact = __Contact;
_MyCompanyId = __MyCompanyId;
}
public int getBankBranchContactId() {
return Id;
}
public Integer getBankBranchId() {
return _BankBranchId;
}
public String getContactType() {
return _ContactTypeModified;
}
public String getContact() {
return _Contact;
}
public Integer getNewField() {
return _NewField;
}
public void setBankBranchContactId(int NewValue) {
Id = NewValue;
}
public void setBankBranchId(Integer NewValue) {
_BankBranchId = NewValue;
}
public void setContactType(String NewValue) {
_ContactTypeModified = NewValue;
}
public void setContact(String NewValue) {
_Contact = NewValue;
}
public void setNewField(Integer NewValue) {
_NewField = NewValue;
}
}
<?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.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mysql?zeroDateTimeBehavior=convertToNull</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">V32</property>
<property name="hibernate.default_schema">stserptest</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.archive.autodetection">class</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<mapping class="com.stserp.beans.bankbranchcontactdetailsBean" />
</session-factory>
</hibernate-configuration>
/**
* Description of ManagerClass
*
* #author Vishal Jain
*/
package com.beans;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class ManagerClass {
private static SessionFactory factory = null;
private static ManagerClass _ManagerClass = null;
public static SessionFactory createSessionFactory() {
SessionFactory sessionFactory;
Configuration configuration = new Configuration();
configuration.configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
}
public static SessionFactory getSessionFactory() {
return factory;
}
public static ManagerClass getInstance() throws ExceptionInInitializerError {
try {
if (factory == null) {
factory = createSessionFactory();
}
if (_ManagerClass == null) {
_ManagerClass = new ManagerClass();
}
} catch (Throwable ex) {
JOptionPane.showMessageDialog(
null,
"Failed to create sessionFactory object...\n"
+ ex.getMessage(), "Error...", 0);
throw new ExceptionInInitializerError(ex);
} finally {
return _ManagerClass;
}
}
public ArrayList<Integer> SaveBeansList(Session session, String entityName,
ArrayList<? extends SuperBeanClass> BeansList)
throws HibernateException {
ArrayList<Integer> IDs = null;
try {
IDs = new ArrayList<Integer>();
for (SuperBeanClass element : BeansList) {
IDs.add((Integer) session.save(entityName, element));
}
} catch (HibernateException e) {
throw e;
}
return IDs;
}
public ArrayList<? extends SuperBeanClass> LoadTable(Session session,
String TableName) throws HibernateException {
ArrayList<? extends SuperBeanClass> beansList = null;
try {
beansList = (ArrayList<? extends SuperBeanClass>) session
.createQuery("FROM " + TableName).list();
} catch (HibernateException e) {
throw e;
}
return beansList;
}
public ArrayList<?> LoadConditional(Session session, String _query)
throws HibernateException {
ArrayList<?> beansList = null;
try {
beansList = (ArrayList<? extends SuperBeanClass>) session
.createQuery(_query).list();
} catch (HibernateException e) {
throw e;
}
return beansList;
}
public SuperBeanInterface LoadById(Session session, Class className,
Integer ID) throws HibernateException {
SuperBeanInterface BeanInterface = null;
try {
BeanInterface = (SuperBeanInterface) session.get(className, ID);
} catch (HibernateException e) {
throw e;
}
return BeanInterface;
}
public void DeleteById(Session session, Class className, Integer ID)
throws HibernateException {
try {
session.delete(session.get(className, ID));
} catch (HibernateException e) {
throw e;
}
}
}
/**
* Description of SuperBeanClass
*
* #author Vishal Jain
*/
package com.beans;
public class SuperBeanClass {
public SuperBeanClass() {
}
}
/**
* Description of SuperBeanInterface
*
* #author Vishal Jain
*/
package com.beans;
public interface SuperBeanInterface {
}
Here the field 'ContactType' has been Changed to 'ContactTypeModified' and a new Field 'NewField' has been added to the Entity Class. No manual changes have been made to the Database. I am getting Error upon the execution of the program which is as Follows :
Aug 14, 2014 10:13:59 AM org.hibernate.annotations.common.Version <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.2.Final}
Aug 14, 2014 10:13:59 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.2.6.Final}
Aug 14, 2014 10:13:59 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Aug 14, 2014 10:13:59 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Aug 14, 2014 10:13:59 AM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
Aug 14, 2014 10:13:59 AM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
Aug 14, 2014 10:13:59 AM 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!
Aug 14, 2014 10:13:59 AM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Aug 14, 2014 10:13:59 AM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000402: Using Hibernate built-in connection pool (not for production use!)
Aug 14, 2014 10:13:59 AM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20
Aug 14, 2014 10:13:59 AM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000006: Autocommit mode: false
Aug 14, 2014 10:13:59 AM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/mysql?zeroDateTimeBehavior=convertToNull]
Aug 14, 2014 10:13:59 AM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000046: Connection properties: {user=root, password=****}
Aug 14, 2014 10:13:59 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Aug 14, 2014 10:13:59 AM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Aug 14, 2014 10:13:59 AM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000228: Running hbm2ddl schema update
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000102: Fetching database metadata
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000396: Updating schema
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: bankbranchcontactdetails
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: bankbranchcontactdetails
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: bankbranchcontactdetails
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
ERROR: HHH000388: Unsuccessful: create table stserptest.bankbranchcontactdetails (BankBranchContactId INT(10) UNSIGNED not null auto_increment, BankBranchId INT(10) UNSIGNED not null, Contact VARCHAR(20) not null, ContactTypeModified ENUM('PHONE','MOBILE','FAX','TELEX') not null, EntryDate TIMESTAMP, MyCompanyId INT(10) UNSIGNED not null, NewField INT(10) UNSIGNED, UserId INT(10) UNSIGNED, isDeleted ENUM('YES','NO'), primary key (BankBranchContactId))
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
ERROR: Table 'bankbranchcontactdetails' already exists
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000232: Schema update complete
Aug 14, 2014 10:14:00 AM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
Aug 14, 2014 10:14:00 AM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
Aug 14, 2014 10:14:00 AM 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!
Aug 14, 2014 10:14:00 AM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Aug 14, 2014 10:14:00 AM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000402: Using Hibernate built-in connection pool (not for production use!)
Aug 14, 2014 10:14:00 AM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20
Aug 14, 2014 10:14:00 AM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000006: Autocommit mode: false
Aug 14, 2014 10:14:00 AM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/mysql?zeroDateTimeBehavior=convertToNull]
Aug 14, 2014 10:14:00 AM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000046: Connection properties: {user=root, password=****}
Aug 14, 2014 10:14:00 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Aug 14, 2014 10:14:00 AM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Aug 14, 2014 10:14:00 AM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000228: Running hbm2ddl schema update
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000102: Fetching database metadata
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000396: Updating schema
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: bankbranchcontactdetails
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: bankbranchcontactdetails
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: bankbranchcontactdetails
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
ERROR: HHH000388: Unsuccessful: create table stserptest.bankbranchcontactdetails (BankBranchContactId INT(10) UNSIGNED not null auto_increment, BankBranchId INT(10) UNSIGNED not null, Contact VARCHAR(20) not null, ContactTypeModified ENUM('PHONE','MOBILE','FAX','TELEX') not null, EntryDate TIMESTAMP, MyCompanyId INT(10) UNSIGNED not null, NewField INT(10) UNSIGNED, UserId INT(10) UNSIGNED, isDeleted ENUM('YES','NO'), primary key (BankBranchContactId))
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
ERROR: Table 'bankbranchcontactdetails' already exists
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000232: Schema update complete
Hibernate:
insert
into
stserptest.bankbranchcontactdetails
(BankBranchId, Contact, ContactTypeModified, EntryDate, MyCompanyId, NewField, UserId, isDeleted)
values
(?, ?, ?, ?, ?, ?, ?, ?)
Aug 14, 2014 10:14:00 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1054, SQLState: 42S22
Aug 14, 2014 10:14:00 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Unknown column 'ContactTypeModified' in 'field list'
Hibernate can modify the db structure if you set it into update mode
<property name="hbm2ddl.auto">update</property>
However it might be better to use something like liquibase or Flyaway that will keep track of the versioning of the tables over time.
In my experience relying on hibernate to keep the schema in sync with the entity models won't work in the long run, especially if you have any kind of branching in your project. You would be opening yourself up for dataloss, unless you instruct it on how to mutate the columns to preserve all of the information inside. Hibernate can very well just choose to drop a column and add a new one, when all you wanted was to rename; this would be bad.
However if you are using an embedded in-memory db (like hsqldb) and do not care about persisting data between executions, then yes you can simply setup hibernate to use the create or create-drop mode and it will construct the tables to match your entities.
I'm trying to set up a small working sample of JPA, however when I run the code I get the follwing error:
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import encje.Klient;
import encje.Zamowienie;
public class SzkolenieJPA {
public static void main(String[] args) {
EntityManagerFactory fabryka = Persistence.createEntityManagerFactory("jpaHibernateTest");
EntityManager menadzer = fabryka.createEntityManager();
Klient przykladowy = menadzer.find(Klient.class, 1);
for(Zamowienie z : przykladowy.getZamowienia())
System.out.println(z.getAdres() + " "+ z.getData() + " "+ przykladowy.getNazwisko());
menadzer.close();
}
}
package encje;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.persistence.*;
#Entity
#Table(name="klient")
public class Klient {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#Column(name="imie", length=50, nullable=false)
private String imie;
#Column(name="nazwisko", length=50, nullable=false)
private String nazwisko;
#OneToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL, mappedBy="klient")
private Set<Zamowienie> zamowienia;
public Klient(){
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getImie() {
return imie;
}
public void setImie(String imie) {
this.imie = imie;
}
public String getNazwisko() {
return nazwisko;
}
public void setNazwisko(String nazwisko) {
this.nazwisko = nazwisko;
}
public Set<Zamowienie> getZamowienia() {
return zamowienia;
}
public void setZamowienia(Set<Zamowienie> zamowienia) {
this.zamowienia = zamowienia;
}
}
package encje;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.*;
import javax.persistence.Table;
#Entity
#Table(name="zamowienie")
public class Zamowienie {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#Column(name="data")
#Temporal(TemporalType.DATE)
private Date data;
#Column(name="imie", length=50)
private String adres;
#ManyToOne
#JoinColumn(name="klient", nullable=false)
private Klient klient;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Date getData() {
return data;
}
public void setData(Date data) {
this.data = data;
}
public String getAdres() {
return adres;
}
public void setAdres(String adres) {
this.adres = adres;
}
public Klient getKlient() {
return klient;
}
public void setKlient(Klient klient) {
this.klient = klient;
}
}
persistence.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="jpaHibernateTest" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.connection.username" value="root" />
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
<property name="hibernate.connection.password" value="" />
<property name="hibernate.connection.url" value="jdbc:mysql://localhost/szkolenie" />
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
</properties>
</persistence-unit>
CREATE TABLE IF NOT EXISTS `klient` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`imie` varchar(50) COLLATE utf8_polish_ci NOT NULL,
`nazwisko` varchar(50) COLLATE utf8_polish_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci AUTO_INCREMENT=4 ;
INSERT INTO `klient` (`id`, `imie`, `nazwisko`) VALUES
(1, 'janek', 'kowalski'),
(2, 'marian', 'nowak'),
(3, 'andrzej', 'nowak');
CREATE TABLE IF NOT EXISTS `zamowienie` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`data` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`adres` text NOT NULL,
`klient` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `klient_zamowienie` (`klient`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ;
INSERT INTO `zamowienie` (`id`, `data`, `adres`, `klient`) VALUES
(1, '2014-06-13 14:45:54', 'Adres', 1),
(2, '2014-06-14 11:58:43', 'zamowienie mariana nowaka', 2),
(3, '2014-06-02 08:31:22', 'zamowienie andrzeja nowaka', 3),
(4, '2014-06-14 11:59:11', 'zamowienie andrzeja nowaka nr 2', 3);
my errors:
juin 14, 2014 7:51:22 PM org.hibernate.ejb.HibernatePersistence logDeprecation
WARN: HHH015016: Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb.HibernatePersistence]; use [org.hibernate.jpa.HibernatePersistenceProvider] instead.
juin 14, 2014 7:51:22 PM org.hibernate.ejb.HibernatePersistence logDeprecation
WARN: HHH015016: Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb.HibernatePersistence]; use [org.hibernate.jpa.HibernatePersistenceProvider] instead.
juin 14, 2014 7:51:22 PM org.hibernate.ejb.HibernatePersistence logDeprecation
WARN: HHH015016: Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb.HibernatePersistence]; use [org.hibernate.jpa.HibernatePersistenceProvider] instead.
juin 14, 2014 7:51:22 PM org.hibernate.jpa.internal.util.LogHelper logPersistenceUnitInformation
INFO: HHH000204: Processing PersistenceUnitInfo [
name: jpaHibernateTest
...]
juin 14, 2014 7:51:22 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.5.Final}
juin 14, 2014 7:51:22 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
juin 14, 2014 7:51:22 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
juin 14, 2014 7:51:22 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
juin 14, 2014 7:51:22 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
juin 14, 2014 7:51:22 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost/szkolenie]
juin 14, 2014 7:51:22 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=root, password=****}
juin 14, 2014 7:51:22 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
juin 14, 2014 7:51:22 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
juin 14, 2014 7:51:23 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
juin 14, 2014 7:51:23 PM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
juin 14, 2014 7:51:23 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
juin 14, 2014 7:51:23 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1054, SQLState: 42S22
juin 14, 2014 7:51:23 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Unknown column 'zamowienia1_.imie' in 'field list'
juin 14, 2014 7:51:23 PM org.hibernate.event.internal.DefaultLoadEventListener onLoad
INFO: HHH000327: Error performing load command : org.hibernate.exception.SQLGrammarException: could not extract ResultSet
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1763)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1694)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.find(AbstractEntityManagerImpl.java:1141)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.find(AbstractEntityManagerImpl.java:1068)
at SzkolenieJPA.main(SzkolenieJPA.java:15)
Caused by: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:123)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:89)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.getResultSet(AbstractLoadPlanBasedLoader.java:449)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeQueryStatement(AbstractLoadPlanBasedLoader.java:202)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:137)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:102)
at org.hibernate.loader.entity.plan.AbstractLoadPlanBasedEntityLoader.load(AbstractLoadPlanBasedEntityLoader.java:186)
at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:4126)
at org.hibernate.event.internal.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:502)
at org.hibernate.event.internal.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:467)
at org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:212)
at org.hibernate.event.internal.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:274)
at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:150)
at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1070)
at org.hibernate.internal.SessionImpl.access$2000(SessionImpl.java:176)
at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.load(SessionImpl.java:2551)
at org.hibernate.internal.SessionImpl.get(SessionImpl.java:955)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.find(AbstractEntityManagerImpl.java:1110)
... 2 more
Caused by: com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: Unknown column 'zamowienia1_.imie' in 'field list'
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2985)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1631)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1723)
at com.mysql.jdbc.Connection.execSQL(Connection.java:3283)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1332)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1467)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:80)
... 18 more
some suggestions or little bit of help please
The problem is with the entity Zamowienie you are mapping the field adres to a column named imie:
#Column(name="imie", length=50)
private String adres;
I think it should be:
#Column(name="adres", length=50)
private String adres;