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
Related
I'm just getting started trying to use Hibernate to create a PostgreSQL database but keep getting this exception:
org.hibernate.HibernateException: java.lang.IllegalArgumentException: max size attribute is mandatory
It happens when I run my main method on the line where I try to build a session factory but I can't find anything about this exception anywhere online. I'm wondering anyone has any ideas on what could be causing this.
Main Class:
package com.package.ingestor;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateTest {
public static void main(String[] args){
Student user = new Student();
user.setStudentId(1);
user.setStudentName("Bri Guy");
user.setStudentAge(32);
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
}
}
Hibernate Object:
package com.bossanova.ingestor;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
#Entity
#Table(name = "student", uniqueConstraints={#UniqueConstraint(columnNames={"id"})})
public class Student {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", length=11, nullable=false, unique=true)
private Integer studentId;
#Column(name = "name", length=20, nullable=true)
private String studentName;
#Column(name="age", length=5, nullable=true)
private Integer studentAge;
public Student() { }
public Student(Integer studId, String studName, Integer studAge) {
this.studentId = studId;
this.studentName = studName;
this.studentAge = studAge;
}
public Integer getStudentId() {
return studentId;
}
public void setStudentId(Integer studentId) {
this.studentId = studentId;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public Integer getStudentAge() {
return studentAge;
}
public void setStudentAge(Integer studentAge) {
this.studentAge = studentAge;
}
#Override
public String toString() {
return "Student= Id: " + this.studentId + ", Name: " + this.studentName + ", Age: " + this.studentAge;
}
}
Config file:
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="connection.url">jdbc:postgresql://localhost:5433/hibernatedb</property>
<property name="connection.username">postgres</property>
<property name="connection.password">password</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQL95Dialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</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">create</property>
<mapping class="com.bossanova.ingestor.Student"/>
</session-factory>
</hibernate-configuration>
I solved this for me by switching my Maven dependency from hibernate-agroal to hibernate-core.
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.0.Final</version>
</dependency>
If you are using hibernate-agroal add <type>pom</type> to your dependency
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.
guys i am newbie in hibernate .. i am trying to use annotation in hibernate but it gives me an exception .. here is my code .. any suggestions .. thanks in advance
in hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<hibernate-configuration>
<session-factory>
<!-- Related to the connection START -->
<property name="connection.driver_class">com.mysql.jdbc.Driver </property>
<property name="connection.url">jdbc:mysql://localhost:3306/mydb </property>
<property name="connection.user">root </property>
<property name="connection.password">root</property>
<!-- Related to the connection END -->
<!-- Related to hibernate properties START -->
<property name="show_sql">true</property>
<property name="dialet">org.hibernate.dialet.MYSQLDialet</property>
<property name="hbm2ddl.auto">create</property>
<!-- Related to hibernate properties END-->
<!-- Related to mapping START-->
<mapping resource="user.hbm.xml" />
<!-- Related to the mapping END -->
</session-factory>
</hibernate-configuration>
DataProvider.java
import javax.persistence.*;
#Entity
#Table(name="dataprovider")
public class DataProvider {
#Id #GeneratedValue
#Column(name="id")
private int user_id;
#Column(name="name")
private String user_name;
#Column(name="description")
private String user_desc;
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getUser_desc() {
return user_desc;
}
public void setUser_desc(String user_desc) {
this.user_desc = user_desc;
}
}
in InsertData.java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
public class InsertData {
private static SessionFactory factory;
public static void main(String[] args) {
factory = new AnnotationConfiguration().configure("hibernate.cfg.xml").addAnnotatedClass(DataProvider.class)
.buildSessionFactory();
new InsertData().insertInfo();
}
public void insertInfo() {
Session session = factory.openSession();
DataProvider provider = new DataProvider();
provider.setUser_id(121);
provider.setUser_name("name");
provider.setUser_desc("desc");
Transaction tr = session.beginTransaction();
session.save(provider);
System.out.println("Object Saved");
tr.commit();
session.close();
factory.close();
}
}
the exception
Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory
at org.hibernate.cfg.annotations.Version.<clinit>(Version.java:12)
at org.hibernate.cfg.AnnotationConfiguration.<clinit>(AnnotationConfiguration.java:78)
at InsertData.main(InsertData.java:11)
Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory
All dependencies required by Hibernate are not loaded, if you use maven all jars referenced are automatically loaded in the Application classpath.
As your error is clearly saying , you are missing a reference to the sl4j jar.
https://www.google.co.in/url?sa=t&rct=j&q=&esrc=s&source=web&cd=7&cad=rja&uact=8&ved=0ahUKEwiBxfuDrM_LAhWCVI4KHU2uBZYQFghAMAY&url=http%3A%2F%2Fmvnrepository.com%2Fartifact%2Forg.slf4j%2Fslf4j-api&usg=AFQjCNFZmEX-pLO1rqWxEyCRGohyjvgEFw
The exception is quite clear: the class org.slf4j.LoggerFactory is required by Hibernate, but was not found. You need to add the corresponding Library to your classpath, i.e. you need an slf4j.jar in addition to hibernate.jar.
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_
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)