I have 2 entities like below:
#Entity
public class Driver {
#Id
#GeneratedValue
private Integer id;
private String name;
#OneToMany
private List<Car> cars = new ArrayList<Car>();
public List<Car> getCars() {
return cars;
}
public void setCars(List<Car> cars) {
this.cars = cars;
}
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;
}
}
#Entity
public class Car {
#Id
#GeneratedValue
#Column(name="car_id")
private Integer carId;
#Column(name="car_type")
private String carType;
public Integer getCarId() {
return carId;
}
public void setCarId(Integer carId) {
this.carId = carId;
}
public String getCarType() {
return carType;
}
public void setCarType(String carType) {
this.carType = carType;
}
}
Hibernate configuration is like below:
<!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>
<!-- SQL Dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<!-- Data base setting -->
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.username">hibernate</property>
<property name="hibernate.connection.password">hibernate</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:#localhost:1521:orcl</property>
<property name="show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<mapping class="org.dxc.hibernate.one.to.many.Driver"/>
<mapping class="org.dxc.hibernate.one.to.many.Car"/>
</session-factory>
</hibernate-configuration>
then I wrote following code to insert data into DB:
private static void test1()
{
Driver driver = new Driver();
driver.setName("Bitt");
Car car1 = new Car();
car1.setCarType("SUV");
Car car2 = new Car();
car2.setCarType("Jeep");
Session session = getSessionFactory().openSession();
session.beginTransaction();
session.save(driver);
session.save(car1);
session.save(car2);
session.getTransaction().commit();
session.close();
}
but I go to Oracle just see data in Driver and Car table, but Driver_Car table is empty, I don't know what happened.
the output content in the eclipse console is like below:
INFO: HHH000400: Using dialect: org.hibernate.dialect.Oracle10gDialect
Hibernate: drop table Car cascade constraints
Jun 22, 2017 9:51:12 AM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess#40499e4f] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Hibernate: drop table Driver cascade constraints
Hibernate: drop table Driver_Car cascade constraints
Hibernate: drop sequence hibernate_sequence
Hibernate: create sequence hibernate_sequence start with 1 increment by 1
Jun 22, 2017 9:51:12 AM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess#6b9ce1bf] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Hibernate: create table Car (car_id number(10,0) not null, car_type varchar2(255 char), primary key (car_id))
Hibernate: create table Driver (id number(10,0) not null, name varchar2(255 char), primary key (id))
Hibernate: create table Driver_Car (Driver_id number(10,0) not null, cars_car_id number(10,0) not null)
Hibernate: alter table Driver_Car add constraint UK_esk5nfu72tp8wnrnvgudvsel5 unique (cars_car_id)
Hibernate: alter table Driver_Car add constraint FKskkihgsvn6a35dqroow0yrx3m foreign key (cars_car_id) references Car
Hibernate: alter table Driver_Car add constraint FK9yujoqc8mcau9bvembcfp8kto foreign key (Driver_id) references Driver
Jun 22, 2017 9:51:12 AM org.hibernate.tool.schema.internal.SchemaCreatorImpl applyImportSources
INFO: HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl#4fc5e095'
Hibernate: select hibernate_sequence.nextval from dual
Hibernate: select hibernate_sequence.nextval from dual
Hibernate: select hibernate_sequence.nextval from dual
Hibernate: insert into Driver (name, id) values (?, ?)
Hibernate: insert into Car (car_type, car_id) values (?, ?)
Hibernate: insert into Car (car_type, car_id) values (?, ?)
Can someone help me?
Related
This code here is simply used to determine the relation of OnetoMany and ManyToOne, I use Spring Tool suite 3.9.11 with XAMPP and Server as apache 7.5
This is first file/table customer.java
package com.bean;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "Customer")
public class Customer {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int cid;
private String cname;
private int ccontact;
private String cemail;
private String cpassword;
#OneToMany(mappedBy = "customer")
private List<OrderF> order;
public List<OrderF> getOrder() {
return order;
}
public void setOrder(List<OrderF> order) {
this.order = order;
}
public Customer() {
super();
}
public int getCid() {
return cid;
}
public void setCid(int cid) {
this.cid = cid;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
public int getCcontact() {
return ccontact;
}
public void setCcontact(int ccontact) {
this.ccontact = ccontact;
}
public String getCemail() {
return cemail;
}
public void setCemail(String cemail) {
this.cemail = cemail;
}
public String getCpassword() {
return cpassword;
}
public void setCpassword(String cpassword) {
this.cpassword = cpassword;
}
}
This is my second file/table OrderF.java
package com.bean;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name="Order")
public class OrderF {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int food_id;
private String foodName;
#ManyToOne(cascade = CascadeType.PERSIST)
#JoinColumn(name = "cid")
private Customer customer;
public int getFood_id() {
return food_id;
}
public void setFood_id(int food_id) {
this.food_id = food_id;
}
public String getFoodName() {
return foodName;
}
public void setFoodName(String foodName) {
this.foodName = foodName;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
}
This is my main.java
package com.bean;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class MainClass {
public static void main(String[] args) {
Customer c=new Customer();
c.setCid(1);
OrderF o=new OrderF();
o.setCustomer(c);
o.setFood_id(1);
o.setFoodName("Java");
SessionFactory sessionFactory=new Configuration().configure().buildSessionFactory();
Session session=sessionFactory.openSession();
session.beginTransaction();
session.save(o);
session.getTransaction().commit();
session.close();
}
}
This is hibernate Configuration file hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/spring</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<mapping class="com.bean.Customer"></mapping>
<mapping class="com.bean.OrderF"></mapping>
</session-factory>
</hibernate-configuration>
This is my Console/Error Log:
version for the right syntax to use near 'Order drop foreign key FKk8oprs3d23xg7tjw95wxaft8l' at line 1
Hibernate: drop table if exists Customer
Hibernate: drop table if exists Order
Aug 14, 2020 12:04:34 PM org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: HHH000389: Unsuccessful: drop table if exists Order
Hibernate: create table Customer (cid integer not null auto_increment, ccontact integer not null, cemail varchar(255), cname varchar(255), cpassword varchar(255), primary key (cid))
Aug 14, 2020 12:04:34 PM org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'Order' at line 1
Hibernate: create table Order (food_id integer not null auto_increment, foodName varchar(255), cid integer, primary key (food_id))
Aug 14, 2020 12:04:35 PM org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: HHH000389: Unsuccessful: create table Order (food_id integer not null auto_increment, foodName varchar(255), cid integer, primary key (food_id))
Hibernate: alter table Order add constraint FKk8oprs3d23xg7tjw95wxaft8l foreign key (cid) references Customer (cid)
Aug 14, 2020 12:04:35 PM org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'Order (food_id integer not null auto_increment, foodName varchar(255), cid integ' at line 1
Aug 14, 2020 12:04:35 PM org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: HHH000389: Unsuccessful: alter table Order add constraint FKk8oprs3d23xg7tjw95wxaft8l foreign key (cid) references Customer (cid)
Aug 14, 2020 12:04:35 PM org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'Order add constraint FKk8oprs3d23xg7tjw95wxaft8l foreign key (cid) references Cu' at line 1
Aug 14, 2020 12:04:35 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Hibernate: insert into Order (cid, foodName) values (?, ?)
Aug 14, 2020 12:04:35 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1064, SQLState: 42000
Aug 14, 2020 12:04:35 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'Order (cid, foodName) values (1, 'Java')' at line 1
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not execute statement
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:106)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:109)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:95)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:207)
at org.hibernate.dialect.identity.GetGeneratedKeysDelegate.executeAndExtract(GetGeneratedKeysDelegate.java:57)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:42)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2792)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3363)
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:81)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:597)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:232)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:213)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:256)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:317)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:272)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:178)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:109)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:679)
As an alternative to renaming you can use SQL quoted identifiers:
#Entity
#Table(name="`Order`")
public class OrderF {
// ...
}
Your Order entity's table name is a reserved word in the SQL engine, try renaming the table's name
#Entity
#Table(name="OrderF ")
public class OrderF {...}
I have a datasource that has two schemas: dbo and example.
I've created a table in dbo schema called A, and mapped it in hibernate:
#Entity
#Table(name = "A")
public class ATable {
private Integer id;
#Id
#Column(name = "id")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
It runs without any errors as expected, I then proceeded to move the table to example schema with the following statement (runs successfully):
alter schema example transfer dbo.A
And changed the hibernate class as well:
#Entity
#Table(name = "A", schema = "example")
public class ATable {
private Integer id;
#Id
#Column(name = "id")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
But upon running it, it throws the following exception, and exit the program.
INFO: HHH000262: Table not found: A
Exception in thread "main" org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: missing table [A]
at org.hibernate.tool.schema.internal.SchemaValidatorImpl.validateTable(SchemaValidatorImpl.java:130)
at org.hibernate.tool.schema.internal.SchemaValidatorImpl.performValidation(SchemaValidatorImpl.java:100)
at org.hibernate.tool.schema.internal.SchemaValidatorImpl.doValidation(SchemaValidatorImpl.java:65)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:184)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:65)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:459)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:465)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:711)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:727)
at com.venditio.Application.main(Application.java:21)
I also tried using the following table annotation instead:
#Table(name = "example.A")
But it throws somewhat the same exception:
INFO: HHH000262: Table not found: example.A
Sep 22, 2017 3:53:36 PM org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl processGetTableResults
INFO: HHH000262: Table not found: example.A
Exception in thread "main" org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: missing table [example.A]
at org.hibernate.tool.schema.internal.SchemaValidatorImpl.validateTable(SchemaValidatorImpl.java:130)
at org.hibernate.tool.schema.internal.SchemaValidatorImpl.performValidation(SchemaValidatorImpl.java:100)
at org.hibernate.tool.schema.internal.SchemaValidatorImpl.doValidation(SchemaValidatorImpl.java:65)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:184)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:65)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:459)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:465)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:711)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:727)
at com.venditio.Application.main(Application.java:21)
It seems that I need to somehow configure hibernate to support the extra schema, but don't understand how.
Application:
public class Application {
private static SessionFactory sessionFactory;
public static void main(String[] args) {
Configuration configuration = new Configuration().configure();
sessionFactory = configuration.buildSessionFactory();
sessionFactory.openSession().close();
}
}
And hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!--MSSQL-->
<property name="hibernate.connection.url">jdbc:jtds:sqlserver://localhost:1433/d1</property>
<property name="connection.driver_class">net.sourceforge.jtds.jdbc.Driver</property>
<property name="hibernate.connection.username">a</property>
<property name="hibernate.connection.password">1</property>
<property name="dialect">org.hibernate.dialect.SQLServerDialect</property>
<!--Global-->
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">validate</property>
<property name="hibernate.current_session_context_class">thread</property>
<mapping class="com.a.A" />
</session-factory>
</hibernate-configuration>
Turns out, removing the following line from hibernate.cfg.xml did the trick
<property name="hibernate.hbm2ddl.auto">validate</property>
Hibernate throws an Unable to execute command exception.
The relationship is like a Customer can have many Credits.
INFO: HHH000400: Using dialect: org.hibernate.dialect.Oracle10gDialect
Hibernate:
drop table Credits cascade constraints
Hibernate:
drop table Customer cascade constraints
Jun 03, 2016 3:58:30 PM org.hibernate.tool.schema.internal.ExceptionHandlerLoggedImpl handleException
WARN: GenerationTarget encountered exception accepting command : Unable to execute command [
drop table Customer cascade constraints]
org.hibernate.tool.schema.spi.CommandAcceptanceException: Unable to execute command [
drop table Customer cascade constraints]
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:63)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.applySqlString(SchemaDropperImpl.java:370)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.applySqlStrings(SchemaDropperImpl.java:355)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.dropFromMetadata(SchemaDropperImpl.java:240)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.performDrop(SchemaDropperImpl.java:153)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.doDrop(SchemaDropperImpl.java:125)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.doDrop(SchemaDropperImpl.java:111)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:137)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:64)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:458)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:465)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
at com.Driver.main(Driver.java:15)
Caused by: java.sql.SQLSyntaxErrorException: ORA-00942: table or view does not exist
at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:91)
at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:133)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:206)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:455)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:413)
at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:1034)
at oracle.jdbc.driver.T4CStatement.doOall8(T4CStatement.java:183)
at oracle.jdbc.driver.T4CStatement.executeForRows(T4CStatement.java:942)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1222)
at oracle.jdbc.driver.OracleStatement.executeInternal(OracleStatement.java:1770)
at oracle.jdbc.driver.OracleStatement.execute(OracleStatement.java:1739)
at oracle.jdbc.driver.OracleStatementWrapper.execute(OracleStatementWrapper.java:299)
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:51)
... 13 more
Hibernate:
drop sequence hibernate_sequence
Hibernate: create sequence hibernate_sequence start with 1 increment by 1
Hibernate:
create table Credits (
bill_id number(10,0) not null,
customer_id number(10,0) not null,
liters number(10,0) not null,
price number(10,0) not null,
product varchar2(255 char),
purchase_amount number(10,0) not null,
primary key (bill_id)
)
Hibernate:
create table Customer (
customer_id number(10,0) not null,
customer_name varchar2(255 char),
date varchar2(255 char),
primary key (customer_id)
)
Hibernate:
alter table Credits
add constraint FKac2p66dfr7gaw7aumwj9ixs71
foreign key (CUSTOMER_ID)
references Customer
Jun 03, 2016 3:58:30 PM org.hibernate.tool.schema.internal.ExceptionHandlerLoggedImpl handleException
WARN: GenerationTarget encountered exception accepting command : Unable to execute command [
create table Customer (
customer_id number(10,0) not null,
customer_name varchar2(255 char),
date varchar2(255 char),
primary key (customer_id)
)]
org.hibernate.tool.schema.spi.CommandAcceptanceException: Unable to execute command [
create table Customer (
customer_id number(10,0) not null,
customer_name varchar2(255 char),
date varchar2(255 char),
primary key (customer_id)
)]
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:63)
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlString(SchemaCreatorImpl.java:423)
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlStrings(SchemaCreatorImpl.java:408)
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.createFromMetadata(SchemaCreatorImpl.java:310)
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.performCreation(SchemaCreatorImpl.java:165)
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:134)
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:120)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:148)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:64)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:458)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:465)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
at com.Driver.main(Driver.java:15)
Caused by: java.sql.SQLSyntaxErrorException: ORA-00904: : invalid identifier
at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:91)
at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:133)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:206)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:455)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:413)
at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:1034)
at oracle.jdbc.driver.T4CStatement.doOall8(T4CStatement.java:183)
at oracle.jdbc.driver.T4CStatement.executeForRows(T4CStatement.java:942)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1222)
at oracle.jdbc.driver.OracleStatement.executeInternal(OracleStatement.java:1770)
at oracle.jdbc.driver.OracleStatement.execute(OracleStatement.java:1739)
at oracle.jdbc.driver.OracleStatementWrapper.execute(OracleStatementWrapper.java:299)
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:51)
... 13 more
Jun 03, 2016 3:58:30 PM org.hibernate.tool.schema.internal.ExceptionHandlerLoggedImpl handleException
WARN: GenerationTarget encountered exception accepting command : Unable to execute command [
alter table Credits
add constraint FKac2p66dfr7gaw7aumwj9ixs71
foreign key (CUSTOMER_ID)
references Customer]
org.hibernate.tool.schema.spi.CommandAcceptanceException: Unable to execute command [
alter table Credits
add constraint FKac2p66dfr7gaw7aumwj9ixs71
foreign key (CUSTOMER_ID)
references Customer]
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:63)
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlString(SchemaCreatorImpl.java:423)
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlStrings(SchemaCreatorImpl.java:408)
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.createFromMetadata(SchemaCreatorImpl.java:359)
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.performCreation(SchemaCreatorImpl.java:165)
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:134)
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:120)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:148)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:64)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:458)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:465)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
at com.Driver.main(Driver.java:15)
Caused by: java.sql.SQLSyntaxErrorException: ORA-00942: table or view does not exist
at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:91)
at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:133)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:206)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:455)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:413)
at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:1034)
at oracle.jdbc.driver.T4CStatement.doOall8(T4CStatement.java:183)
at oracle.jdbc.driver.T4CStatement.executeForRows(T4CStatement.java:942)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1222)
at oracle.jdbc.driver.OracleStatement.executeInternal(OracleStatement.java:1770)
at oracle.jdbc.driver.OracleStatement.execute(OracleStatement.java:1739)
at oracle.jdbc.driver.OracleStatementWrapper.execute(OracleStatementWrapper.java:299)
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:51)
... 13 more
Jun 03, 2016 3:58:30 PM org.hibernate.tool.schema.internal.SchemaCreatorImpl applyImportSources
INFO: HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl#bf4e60'
Hibernate:
select
hibernate_sequence.nextval
from
dual
Hibernate:
select
hibernate_sequence.nextval
from
dual
Hibernate:
insert
into
Customer
(customer_name, date, customer_id)
values
(?, ?, ?)
Jun 03, 2016 3:58:30 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1747, SQLState: 42000
Jun 03, 2016 3:58:30 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: ORA-01747: invalid user.table.column, table.column, or column specification
Jun 03, 2016 3:58:30 PM org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl release
INFO: HHH000010: On release of batch it still contained JDBC statements
Jun 03, 2016 3:58:30 PM org.hibernate.internal.SessionImpl$5 mapManagedFlushFailure
ERROR: HHH000346: Error during managed flush [could not execute statement]
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:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:207)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:45)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2921)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3421)
at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:89)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:560)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:434)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:337)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1295)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:468)
at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3135)
at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2352)
at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:485)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:147)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java:38)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:231)
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:65)
at com.Driver.main(Driver.java:36)
Caused by: java.sql.SQLSyntaxErrorException: ORA-01747: invalid user.table.column, table.column, or column specification
at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:91)
at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:133)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:206)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:455)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:413)
at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:1034)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:194)
at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:953)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1222)
at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3387)
at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:3468)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeUpdate(OraclePreparedStatementWrapper.java:1350)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:204)
... 18 more
Customer.java
package com;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
#Entity
public class Customer {
private int customer_id;
private String customer_name;
private String date;
private List <Credits> credits;
#Id
#GeneratedValue
public int getCustomer_id() {
return customer_id;
}
public void setCustomer_id(int customer_id) {
this.customer_id = customer_id;
}
public String getCustomer_name() {
return customer_name;
}
public void setCustomer_name(String customer_name) {
this.customer_name = customer_name;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
#OneToMany(targetEntity=Credits.class, mappedBy="customer", cascade=CascadeType.ALL, fetch=FetchType.EAGER)
public List<Credits> getCredits() {
return credits;
}
public void setCredits(List<Credits> credits) {
this.credits = credits;
}
}
Credits.java
package com;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
#Entity
public class Credits {
private int bill_id;
private int customer_id;
private int purchase_amount;
private int price;
private int liters;
private String product;
private Customer customer;
#Id
#GeneratedValue
public int getBill_id() {
return bill_id;
}
public void setBill_id(int bill_id) {
this.bill_id = bill_id;
}
public int getCustomer_id() {
return customer_id;
}
public void setCustomer_id(int cust_id) {
this.customer_id = cust_id;
}
public int getPurchase_amount() {
return purchase_amount;
}
public void setPurchase_amount(int purchase_amount) {
this.purchase_amount = purchase_amount;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getLiters() {
return liters;
}
public void setLiters(int liters) {
this.liters = liters;
}
public String getProduct() {
return product;
}
public void setProduct(String product) {
this.product = product;
}
#ManyToOne
#JoinColumn(name="CUSTOMER_ID")
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
}
Driver.java
package com;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class Driver {
public static void main(String[] args) {
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
configuration.addAnnotatedClass(Customer.class);
configuration.addAnnotatedClass(Credits.class);
SessionFactory sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
Customer customer = new Customer();
customer.setCustomer_name("Rahul Shaw");
customer.setDate("03-06-2016");
session.save(customer);
Credits credits = new Credits();
credits.setLiters(15);
credits.setPrice(10);
credits.setProduct("OIL");
credits.setPurchase_amount(500);
credits.setCustomer(customer);
//session.save(customer);
session.save(credits);
session.getTransaction().commit();
}
}
Helper.java
package com;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class Helper {
public static SessionFactory getSession() {
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
configuration.addAnnotatedClass(Customer.class);
configuration.addAnnotatedClass(Credits.class);
SessionFactory sessionFactory = configuration.buildSessionFactory();
return sessionFactory;
}
}
Try Changing dialect according to your version.
Oracle (any version) org.hibernate.dialect.OracleDialect
Oracle9i org.hibernate.dialect.Oracle9iDialect
Oracle10g org.hibernate.dialect.Oracle10gDialect
try or google search your version of dialect.
I have two simple tables Customers and Orders with relation oneToMany from customer to Orders table.
This is my Customers.java
#Entity
public class Customers implements Serializable {
#Id
#GeneratedValue
private int cID;
private String name;
private String email;
// getter and setters
}
And this is Orders.java:
#Entity
public class Orders implements Serializable {
#Id
#GeneratedValue
private int orderID;
private int cId;
#Column(nullable = false)
#Temporal(TemporalType.DATE)
private Date date;
#ManyToOne(cascade = CascadeType.ALL)
private Customers customers;
// getter and setters
}
Now, i am going to insert two record in Orders table:
public static void main(String[] args) {
SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
Orders orders1 = new Orders();
Orders orders2 = new Orders();
Customers customer = new Customers();
customer.setName("c1");
customer.setEmail("abc#gmail.com");
orders1.setDate(new Date());
orders2.setDate(new Date());
orders1.setCustomers(customer);
orders2.setCustomers(customer);
session.save(orders1);
session.save(orders2);
session.getTransaction().commit();
session.close();
sessionFactory.close();
}
This is the result in console:
Hibernate: alter table Orders drop foreign key FK_hmbx2rg9tsgqikb3kodqp90c4
Hibernate: drop table if exists Customers
Hibernate: drop table if exists Orders
Hibernate: create table Customers (cID integer not null auto_increment, email varchar(255), name varchar(255), primary key (cID))
Hibernate: create table Orders (orderID integer not null auto_increment, cId integer not null, date date not null, customers_cID integer, primary key (orderID))
Hibernate: alter table Orders add constraint FK_hmbx2rg9tsgqikb3kodqp90c4 foreign key (customers_cID) references Customers (cID)
Feb 24, 2015 1:58:52 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Hibernate: insert into Customers (email, name) values (?, ?)
Hibernate: insert into Orders (cId, customers_cID, date) values (?, ?, ?)
Hibernate: insert into Orders (cId, customers_cID, date) values (?, ?, ?)
And this is the result tables:
Why the cID in Orders table (which is a foreign key references to customers) is 0?
It should be 1.
It think in your orders table customers_cId is the actual foreign key reference column to the customers table. As you haven't gave any column name explicitly, it internally took column name as customers_cId by joining the variables from both the entities. customers from the orders and cId from the customers entity.
Just to verify you can try giving some other name using #JoinColumn annotation.
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name="order_cId")
private Customers customers;
And cId in orders table is just one more independent column, as you have not set any value to it, its taking the default value as 0. Try setting some random value to it.
I want to create list of embedded objects with Hibernate and MySql.
But I cought bunch of errors:
Hibernate: alter table USERS drop foreign key FK_qymdwjo8d0eu0lhfd3ngfs74d
2014-07-09 15:40:47 ERROR SchemaExport:425 - HHH000389: Unsuccessful: alter table USERS drop foreign key FK_qymdwjo8d0eu0lhfd3ngfs74d
2014-07-09 15:40:47 ERROR SchemaExport:426 - Can't DROP 'FK_qymdwjo8d0eu0lhfd3ngfs74d'; check that column/key exists
Hibernate: drop table if exists USERS
2014-07-09 15:40:48 ERROR SchemaExport:425 - HHH000389: Unsuccessful: drop table if exists USERS
2014-07-09 15:40:48 ERROR SchemaExport:426 - Cannot delete or update a parent row: a foreign key constraint fails
Hibernate: drop table if exists hibernate_unique_key
Hibernate: create table USERS (id integer not null, city varchar(35), pincode varchar(35), state varchar(35), street varchar(35), description varchar(35), joinedDate date, name varchar(35), ADDRESSES_ID bigint not null, primary key (ADDRESSES_ID))
2014-07-09 15:40:48 ERROR SchemaExport:425 - HHH000389: Unsuccessful: create table USERS (id integer not null, city varchar(35), pincode varchar(35), state varchar(35), street varchar(35), description varchar(35), joinedDate date, name varchar(35), ADDRESSES_ID bigint not null, primary key (ADDRESSES_ID))
2014-07-09 15:40:48 ERROR SchemaExport:426 - Table 'users' already exists
Hibernate: alter table USERS add constraint FK_qymdwjo8d0eu0lhfd3ngfs74d foreign key (id) references USERS (ADDRESSES_ID)
2014-07-09 15:40:48 ERROR SchemaExport:425 - HHH000389: Unsuccessful: alter table USERS add constraint FK_qymdwjo8d0eu0lhfd3ngfs74d foreign key (id) references USERS (ADDRESSES_ID)
2014-07-09 15:40:48 ERROR SchemaExport:426 - Cannot add foreign key constraint
Hibernate: create table hibernate_unique_key ( next_hi integer )
Hibernate: insert into hibernate_unique_key values ( 0 )
2014-07-09 15:40:48 INFO SchemaExport:405 - HHH000230: Schema export complete
Hibernate: insert into USERS (city, pincode, state, street, description, joinedDate, name) values (?, ?, ?, ?, ?, ?, ?)
Hibernate: select next_hi from hibernate_unique_key for update
Hibernate: update hibernate_unique_key set next_hi = ? where next_hi = ?
Hibernate: insert into USERS (id, ADDRESSES_ID, city, pincode, state, street) values (?, ?, ?, ?, ?, ?)
2014-07-09 15:40:48 WARN SqlExceptionHelper:144 - SQL Error: 1054, SQLState: 42S22
2014-07-09 15:40:48 ERROR SqlExceptionHelper:146 - Unknown column 'ADDRESSES_ID' in 'field list'
2014-07-09 15:40:48 INFO AbstractBatchImpl:208 - HHH000010: On release of batch it still contained JDBC statements
org.hibernate.exception.SQLGrammarException: could not execute statement
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:80)
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.executeUpdate(ResultSetReturnImpl.java:190)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:62)
at org.hibernate.persister.collection.AbstractCollectionPersister.recreate(AbstractCollectionPersister.java:1311)
at org.hibernate.action.internal.CollectionRecreateAction.execute(CollectionRecreateAction.java:67)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:463)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:349)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:350)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:56)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1222)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:425)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:177)
at com.demo.hibernate.HibernateDemo.createUser(HibernateDemo.java:59)
at com.demo.hibernate.HibernateDemo.main(HibernateDemo.java:37)
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:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'ADDRESSES_ID' in 'field list'
Here is main():
public static void main(String[] args) {
try {
HibernateDemo demo = new HibernateDemo();
UserDetails user = new UserDetails();
Address address = new Address();
address.setStreet("Name");
address.setCity("Kiev");
address.setPincode("00000");
address.setState("My state");
Address addr = new Address();
addr.setStreet("new name");
addr.setCity("Lviv");
addr.setPincode("79040");
addr.setState("state");
user.getListOfAddresses().add(address);
user.getListOfAddresses().add(addr);
user.setUserName("Carl");
user.setJoinedDate(new Date());
user.setDescription("it is cool guy");
user.setAddress(address);
demo.createUser(user);
demo.listUsers();
user.setUserName("Bruno Shults");
demo.updateUser(user);
demo.listUsers();
} catch (Exception e) {
e.printStackTrace();
} finally {
System.runFinalizersOnExit(true);
System.exit(1);
}
UserDetails class:
#Entity
#Table(name = "USERS")
public class UserDetails {
#Id
#GeneratedValue
#Column(name = "id")
private int userId;
#Column(name = "name", length = 35)
private String userName;
#Temporal(TemporalType.DATE)
private Date joinedDate;
#Column(length = 35)
private Address address;
#Column(length = 35)
private String description;
#ElementCollection
#JoinTable(name = "USERS", joinColumns = #JoinColumn(name = "id"))
#GenericGenerator(name = "hilo-gen", strategy = "hilo")
#CollectionId(columns = {#Column(name = "ADDRESSES_ID")}, generator = "hilo-gen", type = #Type(type = "long"))
private Collection<Address> listOfAddresses = new ArrayList<Address>();
// getters and setters
Address class:
#Embeddable
public class Address {
#Column(length = 35)
private String street;
#Column(length = 35)
private String city;
#Column(length = 35)
private String state;
#Column(length = 35)
private String pincode;
// getters and setters
cfg xml file:
<hibernate-configuration>
<session-factory>
<!--Database connection settings-->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/hibernatedb</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">secret</property>
<!--JDBC connection pool-->
<property name="hibernate.connection.pool_size">2</property>
<!--SQL dialect-->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!--Disable the second level cache-->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCachingRegionFactory</property>
<!--Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!--Drop and recreate the database schema on startup-->
<property name="hbm2ddl.auto">create</property>
<!--<property name="hbm2ddl.auto">update</property>-->
<!-- List of XML mapping files -->
<mapping class="com.demo.dto.UserDetails"/>
Here is DB struckture looking:
and diagram:
I couldn't figure out why it creates hibernate_unique_key table? It shouldn't.
Any suggestions?
well these lines
Hibernate: create table hibernate_unique_key ( next_hi integer )
Hibernate: insert into hibernate_unique_key values ( 0 )
appear because of
#GenericGenerator(name = "hilo-gen", strategy = "hilo")
in your address
hilo: Generates a Integer, long or short type of ids. This uses a High – Low algorithm. As the name suggests, it depends upon the highest table id and then reads the possible lowest available value.
Read more about it here