Hibernate - Unable to execute command - java

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.

Related

SQLSyntaxErrorException in JPA One to many relationship

I have two entity classes, Order class and OrderLineItems class. I am trying to create a one-many relationship between Order and OrderLineItems, i.e One Order can have multiple OrderLineItems. The code I have is given below.
#Entity
#Table(name = "order")
#Getter
#Setter
#AllArgsConstructor
#NoArgsConstructor
#Builder
public class Order {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long orderId;
private String orderNumber;
#OneToMany(mappedBy = "order")
private List<OrderLineItems> orderLineItems;
}
#Entity
#Getter
#Setter
#Table(name = "order_line_items")
#AllArgsConstructor
#NoArgsConstructor
#Builder
public class OrderLineItems {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long orderLineItemsId;
private String skuCode;
private BigDecimal price;
private Integer quantity;
#ManyToOne(optional = false)
private Order order;
}
The above code results in a SqlSyntaxErrorException. The relevant part of trace is given below. What am I doing wrong?
2022-04-16 12:39:22.643 INFO 85559 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL8Dialect
Hibernate: create table order (order_id bigint not null auto_increment, order_number varchar(255), primary key (order_id)) engine=InnoDB
2022-04-16 12:39:23.098 WARN 85559 --- [ main] o.h.t.s.i.ExceptionHandlerLoggedImpl : GenerationTarget encountered exception accepting command : Error executing DDL "create table order (order_id bigint not null auto_increment, order_number varchar(255), primary key (order_id)) engine=InnoDB" via JDBC Statement
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "create table order (order_id bigint not null auto_increment, order_number varchar(255), primary key (order_id)) engine=InnoDB" via JDBC Statement
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlString(AbstractSchemaMigrator.java:581) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlStrings(AbstractSchemaMigrator.java:526) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.createTable(AbstractSchemaMigrator.java:293) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
at org.hibernate.tool.schema.internal.GroupedSchemaMigratorImpl.performTablesMigration(GroupedSchemaMigratorImpl.java:74) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.performMigration(AbstractSchemaMigrator.java:220) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.doMigration(AbstractSchemaMigrator.java:123) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:196) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:85) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:335) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:471) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1498) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58) ~[spring-orm-5.3.18.jar:5.3.18]
.............
Caused by: java.sql.SQLSyntaxErrorException: 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 'order (order_id bigint not null auto_increment, order_number varchar(255), prima' at line 1
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120) ~[mysql-connector-java-8.0.28.jar:8.0.28]
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-java-8.0.28.jar:8.0.28]
at com.mysql.cj.jdbc.StatementImpl.executeInternal(StatementImpl.java:763) ~[mysql-connector-java-8.0.28.jar:8.0.28]
at com.mysql.cj.jdbc.StatementImpl.execute(StatementImpl.java:648) ~[mysql-connector-java-8.0.28.jar:8.0.28]
at com.zaxxer.hikari.pool.ProxyStatement.execute(ProxyStatement.java:94) ~[HikariCP-4.0.3.jar:na]
at com.zaxxer.hikari.pool.HikariProxyStatement.execute(HikariProxyStatement.java) ~[HikariCP-4.0.3.jar:na]
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:54) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
... 34 common frames omitted
#Table(name = "order"): order is reserved word in MySQL. Change table name to something else, f.e. "orders" and it will work :)

Unable to create a table in hibernate using OneToMany and ManyToOne relationship(also unable to create Foreign Key)

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 {...}

How to get dependent objects

I'm trying to get the accounts existing in a bank, but the list is empty even though the link between the two exist in the database.
Knowing that the interaction between the database and my program works fine, except that bank.getAccounts() returns an empty list.
here is my code.
What i'm trying to do is:
public class Main {
public static void main(String[] args) {
Bank bank = new Bank();
bank.setName("XXX");
bank.setStreet("XXX");
bank.setPc("XXX");
bank.save();
Account c = new account();
c.setBalance(10);
c.setBank(bank);
c.save();
account c2 = new account();
c2.setBalance(20);
c2.setBank(bank);
c2.save();
for(account c : bank.getAccounts())
System.out.println("account n°: " + c.getId() + ", balance: " + c.getBalance());
}
}
The Bank class is:
#Entity
#Table(name = "BANK")
public class Bank implements Serializable {
/**
*
*/
private static final long serialVersionUID = 8199961750065782869L;
static private BankDAO dao;
private long id;
private String name;
private String street;
private String pc;
private Set<Account> accounts;
public Bank() {
super();
this.accounts = new HashSet<>();
}
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getPc() {
return pc;
}
public void setPc(String pc) {
this.pc = pc;
}
#OneToMany(cascade = CascadeType.ALL, mappedBy="bank")
public Set<Account> getAccounts() {
return accounts;
}
public void setAccounts(Set<Account> accounts) {
this.accounts = accounts;
}
// Equals and hashCode implementations deleted
#Transient
private BankDAO getDao() {
if(Bank.dao == null)
dao = BankDAO.getDAO();
return Bank.dao;
}
public long save() {
Bank.dao = this.getDao();
return dao.save(this);
}
public int delete() {
Bank.dao = this.getDao();
return dao.delete(this);
}
}
The Accounts class code:
#Entity
#Table(name = "Account")
public class Account implements Serializable{
private static final long serialVersionUID = 7224745445343369682L;
static private AccountDAO dao;
public long id;
public int balance;
public Bank bank;
public Account() {
super();
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="bank_id", nullable=false)
#Id
public Bank getBank() {
return bank;
}
public void setBank(Bank bank) {
this.bank = bank;
}
#Transient
private AccountDAO getDao() {
if(Account.dao == null)
dao = AccountDAO.getDAO();
return Account.dao;
}
/*
* save the state of the object: save or update
* #return: the id of the object
*/
public long save() {
Account.dao = this.getDao();
return dao.save(this);
}
public int delete() {
Account.dao = this.getDao();
return dao.delete(this);
}
}
Log is:
Feb 13, 2018 11:38:54 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.12.Final}
Feb 13, 2018 11:38:54 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Feb 13, 2018 11:38:54 PM org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver resolveEntity
WARN: HHH90000012: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-configuration. Use namespace http://www.hibernate.org/dtd/hibernate-configuration instead. Support for obsolete DTD/XSD namespaces may be removed at any time.
Feb 13, 2018 11:38:54 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Feb 13, 2018 11:38:55 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Feb 13, 2018 11:38:55 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [org.postgresql.Driver] at URL [jdbc:postgresql://localhost:5432/hibernateDataBase]
Feb 13, 2018 11:38:55 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=postgres, password=****}
Feb 13, 2018 11:38:55 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Feb 13, 2018 11:38:55 PM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 1 (min=1)
Feb 13, 2018 11:38:55 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
Feb 13, 2018 11:38:55 PM org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl useContextualLobCreation
INFO: HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
Feb 13, 2018 11:38:55 PM org.hibernate.type.BasicTypeRegistry register
INFO: HHH000270: Type registration [java.util.UUID] overrides previous : org.hibernate.type.UUIDBinaryType#67080771
Feb 13, 2018 11:38:55 PM org.hibernate.mapping.RootClass checkCompositeIdentifier
WARN: HHH000038: Composite-id class does not override equals(): business.Account
Feb 13, 2018 11:38:55 PM org.hibernate.mapping.RootClass checkCompositeIdentifier
WARN: HHH000039: Composite-id class does not override hashCode(): business.Account
Hibernate: alter table ACCOUNT drop constraint FKc0nxjvf82u84r0b01m367tss3Feb 13, 2018 11:38:56 PM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess#10650953] 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 if exists BANK cascade
Hibernate: drop table if exists ACCOUNT cascade
Hibernate: drop sequence if exists hibernate_sequence
Hibernate: create sequence hibernate_sequence start 1 increment 1
Feb 13, 2018 11:38:56 PM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess#7db82169] 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 BANK (id int8 not null, pc varchar(255), name varchar(255), street varchar(255), primary key (id))
Hibernate: create table ACCOUNT (id int8 not null, balance int4 not null, bank_id int8 not null, primary key (id, bank_id))
Hibernate: alter table ACCOUNT add constraint FKc0nxjvf82u84r0b01m367tss3 foreign key (bank_id) references BANK
Feb 13, 2018 11:38:56 PM org.hibernate.tool.schema.internal.SchemaCreatorImpl applyImportSources
INFO: HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl#3276732'
Hibernate: select nextval ('hibernate_sequence')
Hibernate: insert into BANK (pc, name, street, id) values (?, ?, ?, ?)
Hibernate: select account_.id, account_.bank_id, account_.balance as balance2_1_ from ACCOUNT account_ where account_.id=? and account_.bank_id=?
Hibernate: select nextval ('hibernate_sequence')
Hibernate: insert into ACCOUNT (balance, id, bank_id) values (?, ?, ?)
Hibernate: select account_.id, account_.bank_id, account_.balance as balance2_1_ from ACCOUNT account_ where account_.id=? and account_.bank_id=?
Hibernate: select nextval ('hibernate_sequence')
Hibernate: insert into ACCOUNT (balance, id, bank_id) values (?, ?, ?)
Bank bank = new Bank();
bank.setName("XXX");
bank.setStreet("XXX");
bank.setPc("XXX");
bank.save(); -- checkpoint 1
Account c = new account();
c.setBalance(10);
c.setBank(bank); -- checkpoint 2
c.save();
account c2 = new account();
c2.setBalance(20);
c2.setBank(bank);
c2.save(); -- checkpoint 3
It wont work that way as as you can see # checkpioint 1 you have you Bank object and nothing will change its state. I gues you would like to Bank->account poulate by checkpoint 2 and 3 but this is not going to happen.
What you have to do is to put that relations manually by simply
bank.getAccounts().add(c1);
However in order to relations to work like you would expect (as bank is already initialized so no lazy fetch will occure), you need to actually fetch your bank again via eg query. Then, newly returned bank will have unitialized collections proxies and will indeed perform additional select (if not eager fetch specified) to get collections of accounts associated with that bank.
I found the problem.
i was using find(id) method to fetch the bank from the database, when i use load(id) or get(id) it works fine.
Best regards.

Missing data while using hibernate to insert data into database

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?

ERROR SchemaExport with Hibernate

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

Categories

Resources