org.hibernate.exception.SQLGrammarException: could not extract ResultSet - java

I have implemented a simple application in Hibernate-4. This application retrieve the value from a table. But when I try to get the record with this
(Booking) session.get(Booking.class, 3740456);
it gives me exception
INFO: HHH000327: Error performing load command : org.hibernate.exception.SQLGrammarException: could not extract ResultSet
So, to verify into the database regarding table and column name, I copy the query from the log statement and execute it. It gives me proper output.
I checked several questions & answers related to this question, but could able to derive the solution.
Hibernate.cfg.xml
<?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="connection.url">jdbc:oracle:thin:#SHKG9072DB:5030:TMSD10G2</property>
<property name="connection.username">ICTDEV$EDI_APP</property>
<property name="connection.password">p2II9JLIaea06</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hibernate.temp.use_jdbc_metadata_defaults">false</property>
<property name = "hibernate.jdbc.lob.non_contextual_creation">true</property>
<property name="connection.pool_size">1</property>
<property name="current_session_context_class">thread</property>
<mapping class="com.hibernate.demo.Booking"/>
</session-factory>
</hibernate-configuration>
Booking.java
package com.hibernate.demo;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="EDI_IN_BOOKING")
public class Booking {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
private int id;
#Column(name="SITE_AN")
private String site;
#Column(name="EVENT_ID")
private int eventId;
#Column(name="EVENT_DETAIL_ID")
private int eventDetailId;
#Column(name="RECORD_SEQUENCE_ID")
private int recordSequenceId;
#Column(name="RECORD_TYPE_N")
int recordType;
#Column(name="EDI_SENDER_AN")
String sender;
#Column(name="EDI_RECIPIENT_AN")
String recipient;
#Column(name="PARTNER_C")
String partner;
#Column(name="SENDER_SEQUENCE_AN")
String senderSequence;
public String getSite() {
return site;
}
public void setSite(String site) {
this.site = (site);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = (id);
}
public int getEventId() {
return eventId;
}
public void setEventId(int eventId) {
this.eventId = (eventId);
}
public int getEventDetailId() {
return eventDetailId;
}
public void setEventDetailId(int eventDetailId) {
this.eventDetailId = (eventDetailId);
}
public int getRecordSequenceId() {
return recordSequenceId;
}
public void setRecordSequenceId(int recordSequenceId) {
this.recordSequenceId = (recordSequenceId);
}
public int getRecordType() {
return recordType;
}
public void setRecordType(int recordType) {
this.recordType = (recordType);
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = (sender);
}
public String getRecipient() {
return recipient;
}
public void setRecipient(String recipient) {
this.recipient = (recipient);
}
public String getPartner() {
return partner;
}
public void setPartner(String partner) {
this.partner = (partner);
}
public String getSenderSequence() {
return senderSequence;
}
public void setSenderSequence(String senderSequence) {
this.senderSequence = (senderSequence);
}
}
Main.java
package com.hibernate.demo;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class Main {
public static void main(String[] args) {
System.out.println("Hello World");
System.out.println("Trying to create a test connection with the database.");
Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
serviceRegistryBuilder.applySettings(configuration.getProperties());
ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Booking booking = (Booking) session.get(Booking.class, 3740456);
System.out.println(booking.getEventDetailId());
}
}
Table description
desc EDi_IN_BOOKING
ID NOT NULL NUMBER
EVENT_ID NOT NULL NUMBER
EVENT_DETAIL_ID NOT NULL NUMBER
RECORD_SEQUENCE_ID NOT NULL NUMBER
RECORD_TYPE_N NUMBER(1)
SITE_AN VARCHAR2(10)
EDI_SENDER_AN VARCHAR2(35)
EDI_RECIPIENT_AN VARCHAR2(35)
PARTNER_C VARCHAR2(20)
SENDER_SEQUENCE_AN VARCHAR2(15)
Query from log (this gives correct output)
select
booking0_.id as id1_0_0_,
booking0_.EVENT_DETAIL_ID as EVENT_DETAIL_ID2_0_0_,
booking0_.EVENT_ID as EVENT_ID3_0_0_,
booking0_.PARTNER_C as PARTNER_C4_0_0_,
booking0_.EDI_RECIPIENT_AN as EDI_RECIPIENT_AN5_0_0_,
booking0_.RECORD_SEQUENCE_ID as RECORD_SEQUENCE_ID6_0_0_,
booking0_.RECORD_TYPE_N as RECORD_TYPE_N7_0_0_,
booking0_.EDI_SENDER_AN as EDI_SENDER_AN8_0_0_,
booking0_.SENDER_SEQUENCE_AN as SENDER_SEQUENCE_AN9_0_0_,
booking0_.site_an as site_an10_0_0_
from
EDI_IN_BOOKING booking0_
where
booking0_.id=3740456;
exception
INFO: HHH000397: Using ASTQueryTranslatorFactory
Hibernate:
select
booking0_.id as id1_0_0_,
booking0_.EVENT_DETAIL_ID as EVENT_DETAIL_ID2_0_0_,
booking0_.EVENT_ID as EVENT_ID3_0_0_,
booking0_.PARTNER_C as PARTNER_C4_0_0_,
booking0_.EDI_RECIPIENT_AN as EDI_RECIPIENT_AN5_0_0_,
booking0_.RECORD_SEQUENCE_ID as RECORD_SEQUENCE_ID6_0_0_,
booking0_.RECORD_TYPE_N as RECORD_TYPE_N7_0_0_,
booking0_.EDI_SENDER_AN as EDI_SENDER_AN8_0_0_,
booking0_.SENDER_SEQUENCE_AN as SENDER_SEQUENCE_AN9_0_0_,
booking0_.site_an as site_an10_0_0_
from
EDI_IN_BOOKING booking0_
where
booking0_.id=?
May 22, 2015 10:49:43 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 904, SQLState: 42000
May 22, 2015 10:49:43 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: ORA-00904: "BOOKING0_"."SITE_AN": invalid identifier
May 22, 2015 10:49:43 AM org.hibernate.event.internal.DefaultLoadEventListener onLoad
INFO: HHH000327: Error performing load command : org.hibernate.exception.SQLGrammarException: could not extract ResultSet
Exception in thread "main" 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:91)
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:503)
at org.hibernate.event.internal.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:468)
at org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:213)
at org.hibernate.event.internal.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:275)
at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:151)
at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1106)
at org.hibernate.internal.SessionImpl.access$2000(SessionImpl.java:176)
at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.load(SessionImpl.java:2587)
at org.hibernate.internal.SessionImpl.get(SessionImpl.java:991)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:356)
at $Proxy7.get(Unknown Source)
at com.dpworld.demo.Main.main(Main.java:23)
Caused by: java.sql.SQLException: ORA-00904: "BOOKING0_"."SITE_AN": invalid identifier
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:134)
at oracle.jdbc.ttc7.TTIoer.processError(TTIoer.java:289)
at oracle.jdbc.ttc7.Oall7.receive(Oall7.java:589)
at oracle.jdbc.ttc7.TTC7Protocol.doOall7(TTC7Protocol.java:1957)
at oracle.jdbc.ttc7.TTC7Protocol.parseExecuteDescribe(TTC7Protocol.java:850)
at oracle.jdbc.driver.OracleStatement.doExecuteQuery(OracleStatement.java:2555)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:2896)
at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:644)
at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:570)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:82)
... 22 more

Is your database configured with case sensitive columns? That could be one reason why Oracle is throwing an "invalid identifier" error
Check your table creating script.

Why is site_an in lowercase in the select such as booking0_.site_an as site_an10_0_0_ while all other column names are in uppercase. I think it may be an uppercase "i" issue.
select
booking0_.id as id1_0_0_,
booking0_.EVENT_DETAIL_ID as EVENT_DETAIL_ID2_0_0_,
booking0_.EVENT_ID as EVENT_ID3_0_0_,
booking0_.PARTNER_C as PARTNER_C4_0_0_,
booking0_.EDI_RECIPIENT_AN as EDI_RECIPIENT_AN5_0_0_,
booking0_.RECORD_SEQUENCE_ID as RECORD_SEQUENCE_ID6_0_0_,
booking0_.RECORD_TYPE_N as RECORD_TYPE_N7_0_0_,
booking0_.EDI_SENDER_AN as EDI_SENDER_AN8_0_0_,
booking0_.SENDER_SEQUENCE_AN as SENDER_SEQUENCE_AN9_0_0_,
booking0_.site_an as site_an10_0_0_

Related

Caused by: java.sql.SQLSyntaxErrorException: Unknown column 'laptop_lid' in 'field list'

i started learning hibernate framework,but i had some problems when i started learning relational mapping : One To One
that's my **Hibernate.cfg.xml
**
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/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>
<!-- Assume test is the database name -->
<property name = "hibernate.connection.url">jdbc:mysql://localhost:3306/aliens </property>
<property name = "hibernate.connection.username">root</property>
<property name = "hibernate.connection.password">root</property>
<property name = "hbm2ddl">update</property>
<property name = "show_sql">true</property>
<!-- List of XML mapping files -->
<mapping class= "com.jee.projetHibernate.Student"/>
<mapping class= "com.jee.projetHibernate.Laptop"/>
</session-factory>
</hibernate-configuration>
that's my Student class
package com.jee.projetHibernate;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name = "student")
public class Student {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="userid")
private int id;
#Column(name="username")
private String name;
#OneToOne
private Laptop laptop;
public Laptop getLaptop() {
return laptop;
}
public void setLaptop(Laptop laptop) {
this.laptop = laptop;
}
public Student() {
super();
}
public Student(int id, String name) {
super();
this.id = id;
this.name = name;
}
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;
}
#Override
public String toString() {
return "Student [id=" + id + ", name=" + name + "]";
}
}
that's my Laptop class
package com.jee.projetHibernate;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "laptop")
public class Laptop {
#Id
private int lid;
private String lname;
public int getLid() {
return lid;
}
public void setLid(int lid) {
this.lid = lid;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
}
and taht's my app.java
package com.jee.projetHibernate;
import javax.imageio.spi.ServiceRegistry;
import org.hibernate.*;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.*;
import com.mysql.cj.Session;
import com.mysql.cj.xdevapi.SessionFactory;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
Laptop lap2=new Laptop();
lap2.setLid(3);
lap2.setLname("macbook");
Student alien=new Student();
alien.setName("marah");
alien.setLaptop(lap2);
Configuration conf =new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(Student.class).addAnnotatedClass(Laptop.class);
StandardServiceRegistry serviceRegistry= new StandardServiceRegistryBuilder().applySettings(conf.getProperties()).build();
org.hibernate.SessionFactory sf=conf.buildSessionFactory();
org.hibernate.Session session=sf.openSession();
Transaction tx=session.beginTransaction();
//to save data in database
session.save(lap2);
session.save(alien);
tx.commit();
//to fetch or get data from database
/*
* alien2=(Student)session.get(Student.class, 17); System.out.println(alien2);
*/
//save method belongs to session interface that belongs to hibernate
/*
* Configuration conf=new
* Configuration().configure().addAnnotatedClass(Aliens.class);
* org.hibernate.SessionFactory sf=conf.buildSessionFactory();
* org.hibernate.Session session= sf.openSession(); Transaction
* tx=session.beginTransaction(); session.save(alien); tx.commit();
*/
}
}
i expected that 2 tables are going to get values that i inserted in my java code , but all i'm getting is an error
INFO: HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
Hibernate: insert into laptop (lname, lid) values (?, ?)
Hibernate: insert into student (laptop_lid, username) values (?, ?)
oct. 28, 2022 3:30:57 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1054, SQLState: 42S22
oct. 28, 2022 3:30:57 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Unknown column 'laptop_lid' in 'field list'
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not execute statement
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:63)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:37)
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.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:200)
at org.hibernate.dialect.identity.GetGeneratedKeysDelegate.executeAndExtract(GetGeneratedKeysDelegate.java:58)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:43)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3279)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3885)
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:84)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:645)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:282)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:263)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:317)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:330)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:287)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:193)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:123)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:194)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:179)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:75)
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:107)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:672)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:665)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:660)
at com.jee.projetHibernate.App.main(App.java:44)
Caused by: java.sql.SQLSyntaxErrorException: Unknown column 'laptop_lid' in 'field list'
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1098)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1046)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeLargeUpdate(ClientPreparedStatement.java:1371)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdate(ClientPreparedStatement.java:1031)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:197)
... 23 more

Exception in thread "main" org.hibernate.hql.ast.QuerySyntaxException: Users is not mapped [from Users]

I am new to hibernate. I am trying to fetch data using the query class but facing the subjected issue. I have checked in hibernate forum but didn't find an answer.
Entity class:
package com.base.test;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="DBUSER")
public class Users implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#Column(name="USERID")
private String userId;
#Column(name="USERNAME")
private String userName;
#Column(name="CREATEDBY")
private String createdBy;
#Column(name="CREATEDDATE")
private Date createdDate;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
}
Test Class:
package com.base.test;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import com.base.util.HibernateUtil;
public class Test {
#SuppressWarnings("unchecked")
public static void main(String[] args) {
Session session=HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Query query = session.createQuery("from Users");
List<Users> usersList = query.list();
for(Users user:usersList){
System.out.println("Id: " + user.getUserId());
System.out.println("Name: " + user.getUserName());
System.out.println("Created By: " + user.getCreatedBy());
System.out.println("Created Date: " + user.getCreatedDate());
}
}
}
HibernateUtil class:
package com.base.util;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
return new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
} catch (HibernateException ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
}
Error Log:
3157 [main] INFO org.hibernate.impl.SessionFactoryImpl - building session factory
3160 [main] INFO org.hibernate.type.BasicTypeRegistry - Type registration [materialized_blob] overrides previous : org.hibernate.type.MaterializedBlobType#983d95
3160 [main] INFO org.hibernate.type.BasicTypeRegistry - Type registration [clob] overrides previous : org.hibernate.type.ClobType#f30494
3160 [main] INFO org.hibernate.type.BasicTypeRegistry - Type registration [java.sql.Clob] overrides previous : org.hibernate.type.ClobType#f30494
3160 [main] INFO org.hibernate.type.BasicTypeRegistry - Type registration [materialized_clob] overrides previous : org.hibernate.type.MaterializedClobType#b1cc87
3160 [main] INFO org.hibernate.type.BasicTypeRegistry - Type registration [wrapper_materialized_blob] overrides previous : org.hibernate.type.WrappedMaterializedBlobType#eaf40c
3160 [main] INFO org.hibernate.type.BasicTypeRegistry - Type registration [blob] overrides previous : org.hibernate.type.BlobType#13c6641
3160 [main] INFO org.hibernate.type.BasicTypeRegistry - Type registration [java.sql.Blob] overrides previous : org.hibernate.type.BlobType#13c6641
3160 [main] INFO org.hibernate.type.BasicTypeRegistry - Type registration [characters_clob] overrides previous : org.hibernate.type.PrimitiveCharacterArrayClobType#5d391d
3160 [main] INFO org.hibernate.type.BasicTypeRegistry - Type registration [wrapper_characters_clob] overrides previous : org.hibernate.type.CharacterArrayClobType#50a649
Dec 14, 2017 3:08:29 PM net.sf.ehcache.config.ConfigurationFactory parseConfiguration
WARNING: No configuration found. Configuring ehcache from ehcache-failsafe.xml found in the classpath: jar:file:/C:/Suhel's%20Folder/Work/POC/jars/ehcache.jar!/ehcache-failsafe.xml
3288 [main] INFO org.hibernate.impl.SessionFactoryObjectFactory - Not binding factory to JNDI, no JNDI name configured
Exception in thread "main" org.hibernate.hql.ast.QuerySyntaxException: Users is not mapped [from Users]
at org.hibernate.hql.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:180)
at org.hibernate.hql.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:111)
at org.hibernate.hql.ast.tree.FromClause.addFromElement(FromClause.java:93)
at org.hibernate.hql.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:327)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3441)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3325)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:733)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:584)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:301)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:244)
at org.hibernate.hql.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:254)
at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:185)
at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136)
at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:101)
at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:80)
at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:124)
at org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:156)
at org.hibernate.impl.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:135)
at org.hibernate.impl.SessionImpl.createQuery(SessionImpl.java:1770)
at com.base.test.Test.main(Test.java:16)
Table Structure:
desc DBUSER
Name Null Type
----------- ---- ------------
USERID VARCHAR2(15)
USERNAME VARCHAR2(15)
CREATEDBY VARCHAR2(15)
CREATEDDATE DATE
Here is hibernate.cfg.xml:
<?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">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:#localhost:1522/DevDB</property>
<property name="hibernate.connection.username">devWork</property>
<property name="hibernate.connection.password">dev$123</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
<!-- <property name="cache.provider_class">org.hibernate.cache.EhCache</property> -->
<property name="hibernate.cache.use_second_level_cache">true</property>
<mapping class="com.base.test.Users"></mapping>
</session-factory>
</hibernate-configuration>
Can someone please help me see where I am going wrong.
I found the solution.
HQL I used is:
Query query = session.createQuery("from Users");
Instead It will be
Query query = session.createQuery("from com.base.test.Users");
That is we have to give to give fully qualified path of the Entity, along with it. This is irrespective of the location of the file where it is used. That is the file inwhere it is used can be in a different/same package as the Entity object.
Same Problem is there when we use #NamedQueries. So below is wrong:
#NamedQueries({
#NamedQuery(
name = "findUsers",
query = "from Users "
)
})
Below is correct:
#NamedQueries({
#NamedQuery(
name = "findUsers",
query = "from com.base.test.Users "
)
})

Exception in thread "main" org.hibernate.exception.SQLGrammarException: ORA-00917: missing comma

package org.javab.hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.javab.Vehicle;
import org.javab.Twowheel;
import org.javab.Fourwheel;
public class Transport {
public static void main(String[] args) {
// TODO Auto-generated method stub
Twowheel Twowheel = new Twowheel();
Twowheel.setTwowheel("two");
Twowheel.setVehicleid(1);
Twowheel.setVehiclename("bike and cycle");
Fourwheel Fourwheel = new Fourwheel();
Fourwheel.setVehicleid(2);
Fourwheel.setFourwheel("four");
Fourwheel.setVehiclename("car and bus");
Vehicle Vehicle = new Vehicle();
Vehicle.setVehiclename("vehicle name");
Vehicle.setVehicleid(3);
#SuppressWarnings("deprecation")
SessionFactory sessionfactory =new Configuration().configure().buildSessionFactory();
Session session =sessionfactory.openSession();
session.beginTransaction();
session.save(Vehicle);
session.save(Fourwheel);
session.save(Twowheel);
session.getTransaction().commit();
session.close();
}
}
The model class i have are below..
package org.javab;
import javax.persistence.*;
#Entity
#Inheritance(strategy=InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(
name="vehicle d type",
discriminatorType=DiscriminatorType.STRING)
public class Vehicle {
#Id /*#GeneratedValue(strategy=GenerationType.AUTO,generator = "SEQ")
#SequenceGenerator(name = "SEQ", sequenceName = "VEHICLE_SEQ", initialValue = 1)*/
public int getVehicleid() {
return vehicleid;
}
public void setVehicleid(int vehicleid) {
this.vehicleid = vehicleid;
}
public String getVehiclename() {
return vehiclename;
}
public void setVehiclename(String vehiclename) {
this.vehiclename = vehiclename;
}
private int vehicleid;
private String vehiclename;
}
Class TwoWheel
package org.javab;
import javax.persistence.Entity;
#Entity
public class Twowheel extends Vehicle {
private String Twowheel;
public String getTwowheel() {
return Twowheel;
}
public void setTwowheel(String twowheel) {
Twowheel = twowheel;
}
}
Class FourWheel
package org.javab;
import javax.persistence.Entity;
#Entity
public class Fourwheel extends Vehicle{
private String fourwheel;
public String getFourwheel() {
return fourwheel;
}
public void setFourwheel(String fourwheel) {
this.fourwheel = fourwheel;
}
}
the Exception which i have been getting is ...
log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Hibernate: insert into Vehicle (vehiclename, vehicle d type, vehicleid) values (?, 'Vehicle', ?)
Exception in thread "main" org.hibernate.exception.SQLGrammarException: ORA-00917: missing comma
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:82)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:47)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:129)
at org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:81)
at com.sun.proxy.$Proxy14.executeUpdate(Unknown Source)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:56)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2849)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3290)
at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:80)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:272)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:264)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:186)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:326)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:52)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1081)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:315)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:175)
at org.javab.hibernate.Transport.main(Transport.java:42)
Caused by: java.sql.SQLSyntaxErrorException: ORA-00917: missing comma
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:440)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:396)
at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:837)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:445)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:191)
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:523)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:207)
at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:1010)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1315)
at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3576)
at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:3657)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeUpdate(OraclePreparedStatementWrapper.java:1350)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:122)
... 16 more
hibernate.cfg.xml.
<!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>
<!-- Database connection settings -->
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:#sae.corpxxxxxxxxxxxe.com:1600/crmrtld</property>
<property name="connection.username">XXXXXXXXX</property>
<property name="connection.password">XXXXXXXXXXXXXXXXXr</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
<!-- Disable the second-level cache -->
<!-- <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property> -->
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<!-- Name the annotated Entity -->
<mapping class="org.javab.Userdetails"></mapping>
<mapping class="org.javab.Vehicle"></mapping>
<mapping class="org.javab.Fourwheel"></mapping>
<mapping class="org.javab.Twowheel"></mapping>
</session-factory>
</hibernate-configuration>
it was working fine with the 10g dialect and everything,,
please also help me with generating id..i cant generate id in oracle?
now i just hardcoded them just to make it work..
DiscriminatorColumn is supposed to be name of the column. And in your case the name is "vehicle d type". And it's not allowed to use space in name of column.
So use some reasonable name for DiscriminatorColumn. Note that this column must exist in SQL table.
Also note that for the inherited classes you need to specify #DiscriminatorValue("class-specific-value") so hibernate can distinguish which class it actually is.

Hibernate Annotation Error (org.hibernate.exception.SQLGrammarException: could not insert: [com.hib.ex.entity.Node])

I'm a beginner in Hibernate Annotation and I'd like to implement an example but it gives me the following error message :
****************WRITING****************
log4j:WARN No appenders could be found for logger (org.hibernate.type.BasicTypeRegistry).
log4j:WARN Please initialize the log4j system properly.
Hibernate: insert into Node (group, name) values (?, ?)
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not insert: [com.hib.ex.entity.Node]
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:64)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2345)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2852)
at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:71)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273)
at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:320)
at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:203)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:129)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210)
at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:56)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195)
at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:50)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:713)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:701)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:697)
at com.hib.ex.dao.HibExDao.saveNode(HibExDao.java:19)
at com.hib.ex.main.Run.main(Run.java:18)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'group, name) values (null, 'zakaria')' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:532)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
at com.mysql.jdbc.Util.getInstance(Util.java:381)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1030)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3558)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3490)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1959)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2109)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2643)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2077)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2362)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2280)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2265)
at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:94)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:57)
... 17 more
This is the entity class Node :
package com.hib.ex.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="Node")
public class Node {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
#Column
private String name;
#Column
private Integer group;
public Node() {
super();
// TODO Auto-generated constructor stub
}
public Node(Integer id, String name, Integer group) {
super();
this.id = id;
this.name = name;
this.group = group;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getGroup() {
return group;
}
public void setGroup(Integer group) {
this.group = group;
}
}
This is the DAO class HibExDao :
package com.hib.ex.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.hib.ex.entity.HyperEdge;
import com.hib.ex.entity.Node;
public class HibExDao {
public void saveNode(Node noeud) {
SessionFactory sf = HibExUtil.getSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
session.save(noeud);
session.getTransaction().commit();
session.close();
}
public List listNode() {
SessionFactory sf = HibExUtil.getSessionFactory();
Session session = sf.openSession();
List nodes = session.createQuery("FROM Node").list();
session.close();
return nodes;
}
public Node readNode(Integer id) {
SessionFactory sf = HibExUtil.getSessionFactory();
Session session = sf.openSession();
Node noeud = (Node) session.get(Node.class, id);
session.close();
return noeud;
}
}
This is the hibernate.cfg.xml 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>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/exhiber</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="connection.pool_size">1</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="current_session_context_class">thread</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping class="com.hib.ex.entity.Node" />
<mapping class="com.hib.ex.entity.HyperEdge" />
</session-factory>
</hibernate-configuration>
And this is the execution class Run :
package com.hib.ex.main;
import java.util.List;
import com.hib.ex.dao.HibExDao;
import com.hib.ex.entity.Node;
public class Run {
public static void main(String[] args) {
HibExDao dao = new HibExDao();
System.out.println("****************WRITING****************");
Node n1 = new Node();
n1.setName("zakaria");
dao.saveNode(n1);
System.out.println("Node saved!");
Node n2 = new Node();
n2.setName("anas");
dao.saveNode(n2);
System.out.println("Node saved!");
System.out.println("\n****************READING****************");
List nodes = dao.listNode();
System.out.println("Name in Node number 2 is: " + dao.readNode(2).getName());
}
}
What is the problem? And can I solve it?
Thanks!
The cause is clearly mentioned:
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'group, name) values (null, 'zakaria')' at line 1
Your entity contains an attribute that contribute to this issue:
#Column
private Integer group;
The answer is simple group is a reserved SQL keyword (see GROUP BY clause`)
To resolve this, you need to rename to column name and map it correctly to your entity attribute.
Also, you are not populating the group field, hence it's NULL. Perhaps MySQL doesn't accept NULL for this column?
I hope this helps.
If you want to use the reserved keyword, you can do it using the following specification:
In JPA 2.0:
#Column(name="\"group\"")
In Hibernate:
#Column(name="'group'")
Reference.
To work you have to set the group property or allow it to be null ( nullable=true)

Hibernate error org.hibernate.exception.SQLGrammarException with MySQL

I'm creating a project in Java and MySQL with Hibernate, I can get data from the database, but I can't save data into it because shows error, I'm trying to create this project with MVC and annotations very simple, without Spring or nothing, just Hibernate. This are my classes:
Quote.java
package stock.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Id;
import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.Date;
import java.sql.Time;
#SuppressWarnings("serial")
#Entity
#Table(name = "quote")
public class Quote implements Serializable{
public Quote(Long idQuote, int idCompany, BigDecimal price, Long volume,
Date lastDate, Time lastTime, Long avgVolume, BigDecimal marketCap,
BigDecimal change, BigDecimal percChange, String marketPeriod) {
super();
this.idQuote = idQuote;
this.idCompany = idCompany;
this.price = price;
this.volume = volume;
this.lastDate = lastDate;
this.lastTime = lastTime;
this.avgVolume = avgVolume;
this.marketCap = marketCap;
this.change = change;
this.percChange = percChange;
this.marketPeriod = marketPeriod;
}
public Quote() {
}
#Id
#Column(name = "id_quote")
private Long idQuote;
#Id
#Column(name = "id_company")
private int idCompany;
private BigDecimal price;
private Long volume;
#Column(name = "last_date")
private Date lastDate;
#Column(name = "last_time")
private Time lastTime;
#Column(name ="avg_volume")
private Long avgVolume;
#Column(name = "market_cap")
private BigDecimal marketCap;
private BigDecimal change;
#Column(name = "perc_change")
private BigDecimal percChange;
#Column(name = "market_period")
private String marketPeriod;
public Long getIdQuote() {
return idQuote;
}
public void setIdQuote(Long idQuote) {
this.idQuote = idQuote;
}
public int getIdCompany() {
return idCompany;
}
public void setIdCompany(int idCompany) {
this.idCompany = idCompany;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public Long getVolume() {
return volume;
}
public void setVolume(Long volume) {
this.volume = volume;
}
public Date getLastDate() {
return lastDate;
}
public void setLastDate(Date lastDate) {
this.lastDate = lastDate;
}
public Time getLastTime() {
return lastTime;
}
public void setLastTime(Time lastTime) {
this.lastTime = lastTime;
}
public Long getAvgVolume() {
return avgVolume;
}
public void setAvgVolume(Long avgVolume) {
this.avgVolume = avgVolume;
}
public BigDecimal getMarketCap() {
return marketCap;
}
public void setMarketCap(BigDecimal marketCap) {
this.marketCap = marketCap;
}
public BigDecimal getChange() {
return change;
}
public void setChange(BigDecimal change) {
this.change = change;
}
public BigDecimal getPercChange() {
return percChange;
}
public void setPercChange(BigDecimal percChange) {
this.percChange = percChange;
}
public String getMarketPeriod() {
return marketPeriod;
}
public void setMarketPeriod(String marketPeriod) {
this.marketPeriod = marketPeriod;
}
}
QuoteDaoImpl.java
package stock.dao;
import java.sql.Time;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import stock.model.Quote;
#SuppressWarnings("rawtypes")
public class QuoteDaoImpl implements QuoteDao{
private Session session;
public QuoteDaoImpl(Session session) {
this.session = session;
}
#Override
public void setQuote(Quote quote) {
session.save(quote);
}
}
QuoteController.java
package stock.controller;
import java.math.BigDecimal;
import java.sql.Date;
import java.sql.Time;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import stock.dao.QuoteDao;
import stock.dao.QuoteDaoImpl;
import stock.model.Quote;
#SuppressWarnings("deprecation")
public class QuoteController {
private QuoteDao quoteDao;
private static final SessionFactory sessionFactory;
private Session session;
static {
try {
// Initialize factory using contents of hibernate.cfg.xml
sessionFactory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
#SuppressWarnings("unused")
private static SessionFactory getSessionFactory() {
return sessionFactory;
}
private void openSession(){
session = sessionFactory.openSession();
session.beginTransaction();
quoteDao = new QuoteDaoImpl(session);
}
private void closeSession(){
session.getTransaction().commit();
session.close();
}
public QuoteController() {
this.openSession();
}
public void setQuote(){
Quote qte = new Quote();
qte.setIdQuote(new Long("20130418140532"));
qte.setIdCompany(4);
qte.setLastDate(new Date(20130418));
qte.setLastTime(new Time(140532));
qte.setPrice(new BigDecimal(2.35));
quoteDao.setQuote(qte);
this.closeSession();
}
}
hibernate.cfg.xml
<?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>
<!-- Session Thread -->
<property name="current_session_context_class">thread</property>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/stock</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- <property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property> -->
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">validate</property>
<!-- configuration pool via c3p0-->
<property name="c3p0.acquire_increment">1</property>
<property name="c3p0.idle_test_period">3600</property> <!-- seconds -->
<property name="c3p0.min_size">3</property>
<property name="c3p0.max_size">5</property>
<property name="c3p0.max_statements">0</property>
<property name="c3p0.timeout">3605</property> <!-- seconds -->
<property name="hibernate.c3p0.preferredTestQuery">select 1;</property>
<!-- Mapping files -->
<mapping class="stock.model.Company"/>
<mapping class="stock.model.Quote"/>
<!-- <mapping class="stock.model.QuoteInfo"/> -->
</session-factory>
</hibernate-configuration>
As you can see in the configuration file, I've tried with org.hibernate.dialect.MySQLDialect and org.hibernate.dialect.MySQLInnoDBDialect but shows the same error.
And the error shown is:
ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'change, last_date, last_time, market_cap, market_period, perc_change, price, vol' at line 1
Exception in thread "main" org.hibernate.exception.SQLGrammarException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'change, last_date, last_time, market_cap, market_period, perc_change, price, vol' at line 1
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:82)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:129)
at org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:81)
at sun.proxy.$Proxy10.executeUpdate(Unknown Source)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:56)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3028)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3469)
at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:88)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:362)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:354)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:275)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:326)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:52)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1213)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:402)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:175)
at stock.controller.QuoteController.closeSession(QuoteController.java:46)
at stock.controller.QuoteController.setQuote(QuoteController.java:72)
at stock.view.Test.main(Test.java:13)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'change, last_date, last_time, market_cap, market_period, perc_change, price, vol' at line 1
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 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:4096)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4028)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2490)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2651)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2683)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2144)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2444)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2362)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2347)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:122)
... 18 more
The table quote is:
CREATE TABLE `quote` (
`id_quote` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT 'Codigo identificación quote\\nYYYYMMDDHHMMSS',
`id_company` int(11) NOT NULL DEFAULT '0' COMMENT 'Id compañia ',
`price` decimal(10,4) NOT NULL COMMENT 'Precio actual de la acción',
`volume` bigint(20) NOT NULL COMMENT 'volumen actual de la acción',
`last_date` date NOT NULL COMMENT 'fecha de la acción',
`last_time` time NOT NULL COMMENT 'hora de la acción',
`avg_volume` bigint(20) NOT NULL COMMENT 'volumen promedio actual de la acción sobre los últimos 30 días',
`market_cap` decimal(10,4) DEFAULT NULL COMMENT 'El valor total de la compañia en el mercado actualmente',
`change` decimal(5,2) DEFAULT NULL COMMENT 'Valor que la acción ha cambiado con respecto al inicio del día',
`perc_change` decimal(5,2) DEFAULT NULL COMMENT 'Porcentaje que la acción ha cambiado con respecto al inicio del día',
`market_period` varchar(2) DEFAULT NULL COMMENT 'Periodo de la acción\\nAH: After Hours\\nPM: Pre-Market\\nNH: Horas normales',
PRIMARY KEY (`id_quote`,`id_company`),
KEY `quote_ibfk_1` (`id_company`),
CONSTRAINT `quote_ibfk_1` FOREIGN KEY (`id_company`) REFERENCES `company` (`id_company`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
Thanks for your help.
try to add to the field private Long idQuote; columnDefintion like "bigInt(8)", may do the trick

Categories