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.
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 am a beginner and I am doing some inheritance exercises in hibernate. I have two classes, a superclass and a subclass, both are joined by inheritance SINGLE_TABLE.
The problem is that when I want to persist an object of the subclass to the database, hibernate tries to make an "INSERT" in the table of the superclass. And this produces the error "unknown column "color "in 'field list'", since the "color" column does not exist in the table of the superclass.
I have not mapped associations between both tables. Should I do that? My textbooks do not specify it. Otherwise, what should I do?
SUPERCLASS: --------------------------------------------------------------------
#Entity
#Table(name="autos")
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(
name = "pe_discriminador",
discriminatorType = DiscriminatorType.STRING)
#DiscriminatorValue(value = "a1")
public class auto implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="marca")
private String marca;
#Column(name="modelo")
private String modelo;
public auto(){
}
public auto(int id, String marca, String modelo) {
this.id = id;
this.marca = marca;
this.modelo = modelo;
}
public long getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getMarca() {
return marca;
}
public void setMarca(String marca) {
this.marca = marca;
}
public String getModelo() {
return modelo;
}
public void setModelo(String modelo) {
this.modelo = modelo;
}
#Override
public String toString() {
return "auto{" + "id=" + id + ", marca=" + marca + ", modelo=" + modelo + '}';
}
}
SUBCLASS ----------------------------------------------------------------------
#Entity
#Table(name="autos")
#DiscriminatorValue("a2")
public class auto2 extends auto{
int id2;
public auto2() {
}
public auto2(int id2, String color, double motor, int id, String marca, String modelo) {
this.id2=id2;
this.color=color;
this.motor=motor;
setMarca(marca);
setModelo(modelo);
}
#Column(name="color")
private String color;
#Column(name="motor")
private double motor;
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public double getMotor() {
return motor;
}
public void setMotor(double motor) {
this.motor = motor;
}
#Override
public String toString() {
return "auto2{" + ", color=" + color + ", motor=" + motor + '}';
}
}
HIBERNATE ERROR LOG:----------------------------------------------------------
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
oct 21, 2018 10:22:51 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
oct 21, 2018 10:22:52 AM org.hibernate.cfg.AnnotationBinder bindClass
WARN: HHH000139: Illegal use of #Table in a subclass of a SINGLE_TABLE hierarchy: entidades.auto2
Hibernate: insert into autos (marca, modelo, color, id2, motor, pe_discriminador) values (?, ?, ?, ?, ?, 'a2')
oct 21, 2018 10:22:54 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1054, SQLState: 42S22
oct 21, 2018 10:22:54 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Unknown column 'color' in 'field list'
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not execute statement
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:63)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:99)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:178)
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:3072)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3663)
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:81)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:645)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:282)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:263)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:317)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:359)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:292)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:200)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:131)
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:709)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:701)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:696)
at testeo.TestAuto.main(TestAuto.java:225)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'color' in 'field list'
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
at com.mysql.jdbc.Util.getInstance(Util.java:408)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:944)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3978)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3914)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2530)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2683)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2495)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1903)
at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2124)
at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2058)
at com.mysql.jdbc.PreparedStatement.executeLargeUpdate(PreparedStatement.java:5158)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2043)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:175)
... 22 more
0) Prequel to Answer
Before we jump into the answer, I would like to point out something: The example code looks a bit messy. For example the indentation could be more intuitive and typically classes are named in PascalCase (that is camelCase with a capital first letter). Many style guides are out there that can help you (e.g. by Google). Believe me: It makes coding more fun!
1) Actual Answer
There are multiple strategies to save class hierarchies with hibernate:
Single table: All classes in the hierarchy are persisted into one table (with potentially many columns)
Table per class: Each concrete class is persisted into its own table
Joined: Each concrete class as well as the super class are persisted into a table each
You chose a SINGLE_TABLE inheritance strategy. That means, all classes and sub-classes that belong to this hierarchy will be persisted into one table (table per class hierarchy).
From your description of the error, it seems that your database schema, fits a different strategy.
a) Table per class strategy
If you have, one table per concrete subclass (that means: no table for the abstract super class), try:
#Entity
#Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Auto {
b) Join strategy
If the abstract superclass and your concrete subclasses each have a table, then go with:
#Entity
#Inheritance(strategy = InheritanceType.JOINED)
public class Auto{
#Id
private int id;
// getters, setters, ...
}
#Entity
#PrimaryKeyJoinColumn(name = "id")
public class RaceAuto extends Auto {
// ...
}
In both cases, you will not need a discriminator column. The Hibernate documentation can be misleading if you want to use annotations. I found this blog post quite helpful.
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?
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 am trying to build an app that has to objects, book and review, a book can have multiple reviews.
I could see the list of books, but when I entered the book page I could see the title and other attributes of the book but not the attributes of the reviews.
Now i modified the code and i get a 404 error with the warning:
WARNING: No mapping found for HTTP request with URI [/app/] in DispatcherServlet with name 'SpringDispatcher'
I want to mention that i don't have Set variable and method implemented in Review class.
I am using annotation and no xml file in my implementation, please help me
Review.java
#Entity
#Table(name = "REVIEW")
public class Review {
#Id
#GeneratedValue
#Column(name = "ID")
private int id;
#Column(name = "R_DATE")
private Date r_date;
#Column(name = "R_AUTHOR")
private String r_author;
#Column(name = "R_TEXT")
private String r_text;
#Column(name = "R_RATING")
private int r_rating;
#Column(name = "R_BOOKID")
#JoinColumn(name = "BOOKID", nullable = false)
private int r_bookid;
#ManyToOne
private Book book;
public Review(String author, String text, Date date, int rating, int bookid, Book book)
{
super();
this.r_author = author;
this.r_text = text;
this.r_date = date;
this.r_rating = rating;
this.r_bookid = bookid;
this.book= book;
}
...
public Book getBook() {
return book;
}
public void setBook(Book book) {
this.book = book;
}
#Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
Book.java
#Entity
#Table(name = "BOOK")
public class Book {
#Id
#GeneratedValue
#Column(name = "BOOKID")
private int bookId;
#Column(name = "BOOKRATING")
private int bookRating;
#Column(name = "BOOKCATEGORY")
private String bookCategory;
#Column(name = "BOOKAUTHOR")
private String bookAuthor;
#Column(name = "BOOKTITLE")
private String bookTitle;
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private Set<Review> review = new HashSet<Review>(0);
public Book(){
}
public Book(String title)
{
this.bookTitle = title;
}
...
public Set<Review> getReviews() {
return review;
}
public void setReviews(Set<Review> review) {
this.review = review;
}
#Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
The server log:
INFO: Refreshing WebApplicationContext for namespace 'SpringDispatcher-servlet': startup date [Mon May 04 17:01:08 EEST 2015]; root of context hierarchy
May 04, 2015 5:01:08 PM org.springframework.web.context.support.AnnotationConfigWebApplicationContext loadBeanDefinitions
INFO: Registering annotated classes: [class com.bookr.app.config.ApplicationContextConfig]
May 04, 2015 5:01:09 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
May 04, 2015 5:01:09 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.5.Final}
May 04, 2015 5:01:09 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
May 04, 2015 5:01:09 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
May 04, 2015 5:01:10 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
May 04, 2015 5:01:10 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
May 04, 2015 5:01:10 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
May 04, 2015 5:01:10 PM org.hibernate.tuple.PojoInstantiator <init>
INFO: HHH000182: No default (no-argument) constructor for class: com.bookr.app.model.Review (class must be instantiated by Interceptor)
May 04, 2015 5:01:11 PM org.springframework.orm.hibernate4.HibernateTransactionManager afterPropertiesSet
INFO: Using DataSource [org.apache.commons.dbcp2.BasicDataSource#3f0938ef] of Hibernate SessionFactory for HibernateTransactionManager
May 04, 2015 5:01:11 PM org.springframework.web.servlet.DispatcherServlet initServletBean
INFO: FrameworkServlet 'SpringDispatcher': initialization completed in 2577 ms
May 04, 2015 5:01:11 PM org.apache.catalina.core.StandardContext reload
INFO: Reloading Context with name [/app] is completed
May 04, 2015 5:01:11 PM org.springframework.web.servlet.PageNotFound noHandlerFound
WARNING: No mapping found for HTTP request with URI [/app/] in DispatcherServlet with name 'SpringDispatcher'
May 04, 2015 5:01:12 PM org.springframework.web.servlet.PageNotFound noHandlerFound
WARNING: No mapping found for HTTP request with URI [/app/] in DispatcherServlet with name 'SpringDispatcher'
The controller
package com.bookr.app.controller;
import com.bookr.app.dao.BookDAO;
import com.bookr.app.dao.ReviewDAO;
import com.bookr.app.model.Book;
import com.bookr.app.model.Review;
/**
* Handles requests for the application home page.
*/
#RestController
#RequestMapping("/app")
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
#Autowired
private BookDAO bookDao;
#Autowired
private ReviewDAO reviewDao;
#RequestMapping(value = "/")
public ModelAndView book(Locale locale)
{
List<Book> listBook = bookDao.list();
ModelAndView model = new ModelAndView("book");
model.addObject("bookList", listBook);
logger.info("Welcome home! The client locale is {}.", locale , "and the books will be listed");
return model;
}
#RequestMapping(value = "/book", method = RequestMethod.GET)
public ModelAndView viewBook(HttpServletRequest request) {
int bookId = Integer.parseInt(request.getParameter("id"));
Book book = bookDao.get(bookId);
Set<Review> review = book.getReviews();
ModelAndView model = new ModelAndView("viewBook");
model.addObject("book", book);
model.addObject("review", review);
return model;
}
}
Thank you very much