Today i was trying to add Customer to database using Hibernate Annotation but i dont know why i am facing a reference Problem with a table !
Please read the Exception below
ERROR: Referential integrity constraint violation:
"FKOFMCQE0O4K2TFOXB308SKTMQ3: PUBLIC.CUSTOMER FOREIGN
KEY(CUS_BILLINGADDRESSID) REFERENCES
PUBLIC.CUSTOMERBILLINGADDRESS(CUS_BILLINGADDRESSID) ('CBA00001')"; SQL
statement:
update Customer set cus_emailid=?, cus_mobileno=?, cus_name=?, cus_billingaddressid=?, cus_cartid=?, cus_loginid=?,
cus_shippingaddressid=? where cus_id=? [23506-193]
Apr 01, 2017 7:09:57 PM org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl release
INFO: HHH000010: On release of batch it still contained JDBC statements
Apr 01, 2017 7:09:57 PM org.hibernate.internal.ExceptionMapperStandardImpl
mapManagedFlushFailure
ERROR: HHH000346: Error during managed flush [org.hibernate.exception.ConstraintViolationException: could not
execute statement]
Apr 01, 2017 7:09:57 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/TechNXT] threw exception [Request processing failed; nested
exception is javax.persistence.PersistenceException:
org.hibernate.exception.ConstraintViolationException: could not
execute statement] with root cause
org.h2.jdbc.JdbcSQLException: Referential integrity constraint violation: "FKOFMCQE0O4K2TFOXB308SKTMQ3: PUBLIC.CUSTOMER FOREIGN
KEY(CUS_BILLINGADDRESSID) REFERENCES
PUBLIC.CUSTOMERBILLINGADDRESS(CUS_BILLINGADDRESSID) ('CBA00001')"; SQL
statement:
update Customer set cus_emailid=?, cus_mobileno=?, cus_name=?, cus_billingaddressid=?, cus_cartid=?, cus_loginid=?,
cus_shippingaddressid=? where cus_id=? [23506-192]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
at org.h2.message.DbException.get(DbException.java:179)
at org.h2.message.DbException.get(DbException.java:155)
at org.h2.constraint.ConstraintReferential.checkRowOwnTable(ConstraintReferential.java:372)
at org.h2.constraint.ConstraintReferential.checkRow(ConstraintReferential.java:314)
at org.h2.table.Table.fireConstraints(Table.java:967)
at org.h2.table.Table.fireAfterRow(Table.java:985)
at org.h2.command.dml.Update.update(Update.java:151)
at org.h2.command.CommandContainer.update(CommandContainer.java:98)
at org.h2.command.Command.executeUpdate(Command.java:258)
at org.h2.server.TcpServerThread.process(TcpServerThread.java:344)
at org.h2.server.TcpServerThread.run(TcpServerThread.java:158)
at java.lang.Thread.run(Unknown Source)
Here is my Two model Tables
NOTE : i have generated getters and Setters but not posting so making as small as possible
1. Customer table which has a references of the other table
#Entity
public class Customer {
#Id
private String cus_id;
private String cus_name;
private String cus_emailid;
private String cus_mobileno;
#OneToOne(cascade=CascadeType.REFRESH)
#JoinColumn(name="cus_loginid")
private CustomerDetails customerdetails;
#OneToOne(cascade=CascadeType.REFRESH)
#JoinColumn(name="cus_billingaddressid")
private CustomerBillingAddress customerbillingaddress;
#OneToOne(cascade=CascadeType.REFRESH)
#JoinColumn(name="cus_shippingaddressid")
private CustomerShippingAddress customershippingaddress;
#OneToOne(cascade=CascadeType.REFRESH)
#JoinColumn(name="cus_cartid")
private CustomerCart customercart;
My Customer Billing Address Model
#Entity
public class CustomerBillingAddress {
#Id
private String cus_billingaddressid;
private String cus_houseno;
private String cus_street;
private String cus_area;
private String cus_city;
private String cus_state;
private String cus_country;
private String cus_pincode;
#OneToOne(mappedBy="customerbillingaddress")
private Customer customer;
Similarly Other Models
And Finally My DAO method which add the Customer to db
here is the code !
#Transactional
public String addCustomer(Customer customer) {
System.out.println("CustomerDao -TechNXT\n");
Session ses = sf.openSession();
customer.setCus_id(generateCustomerid());
customer.setCustomerbillingaddress(new CustomerBillingAddress());
customer.setCustomershippingaddress(new CustomerShippingAddress());
customer.setCustomercart(new CustomerCart());
customer.getCustomerdetails().setCus_loginid(generateCustomerLoginid());
customer.getCustomerbillingaddress().setCus_billingaddressid(generateCustomerBillingid());
customer.getCustomershippingaddress().setCus_shippingaddressid(generateCustomershippingid());
customer.getCustomercart().setCus_cartid(generateCustomerCartid());
customer.getCustomerdetails().setCus_isenabled(true);
customer.getCustomerdetails().setCus_role("ROLE_USER");
Transaction tr = ses.beginTransaction();
ses.save(customer);
tr.commit();
ses.close();
return customer.getCustomerdetails().getCus_loginid();
}
Well i have being trying stuffs since 3hrs but failed to get a solution of it !!
Sorry for taking your precious time.
and Thanking you in advance for helping me !
can you mark the #Table annontation on your class
like
#Table(name ="Customer")
I'm using Hibernate 4.3 with JDK 1.8. I have defined two entity classes Purchase and Payment, first inheriting from the abstract StuffTransaction which is in turn a subclass of Transaction, and the second, i.e. Payment, is a direct subclass of Transaction. All of theses classes have the two properties of "deptor" and "creditor", defined as follows:
#Entity(name = "ac_transactions")
public abstract class Transaction implements Serializable, Comparable<Transaction>, Data {
protected long id;
protected String title;
...
private static final long serialVersionUID = -952911952174854827L;
#ManyToOne
public abstract Account getDeptor();
#ManyToOne
public abstract Account getCreditor();
public abstract void setDeptor(Account a);
public abstract void setCreditor(Account a);
...
}
and:
public abstract class StuffTransaction extends Transaction {
private static final long serialVersionUID = 9002942588702189794L;
...
}
and:
#Entity
public class Purchase extends StuffTransaction {
private transient Person buyer, seller;
#Override
public void setDeptor(Account a) {
buyer = (Person) a;
}
#Override
public void setCreditor(Account a) {
seller = (Person) a;
}
#ManyToOne #JoinColumn(insertable = false, updatable = false)
public Person getDeptor() {
return buyer;
}
#ManyToOne #JoinColumn(insertable = false, updatable = false)
public Person getCreditor() {
return seller;
}
...
}
and:
#Entity
public class Payment extends Transaction {
private transient Account sink;
private transient Account source;
#ManyToOne #JoinColumn(insertable = false, updatable = false)
public Person getDeptor() {
return (Person) sink;
}
#ManyToOne #JoinColumn(insertable = false, updatable = false)
public Person getCreditor() {
return (Person) source;
}
private transient Transaction concern;
#OneToOne
public Transaction getConcern() {
return concern;
}
...
}
You can see that everything is logically the same between Purchase and Payment. And my table is created this way:
CREATE TABLE `ac_transactions` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`title` varchar(255) DEFAULT NULL,
`dsc` varchar(255) DEFAULT NULL,
`val` bigint(20) DEFAULT NULL,
`year` int(11) DEFAULT NULL,
`month` int(11) DEFAULT NULL,
`day` int(11) DEFAULT NULL,
`opponentName` varchar(255) DEFAULT NULL,
`deptor_id` int(11) DEFAULT NULL,
`creditor_id` int(11) DEFAULT NULL,
`visible` tinyint(1) DEFAULT NULL,
`DTYPE` varchar(45) DEFAULT NULL,
`valueChangePercentageChain` tinyblob,
`type` tinyint(1) DEFAULT NULL,
`salePoint` tinyint(1) DEFAULT NULL,
`confirmed` tinyint(1) DEFAULT NULL,
`concern_id` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=108 DEFAULT CHARSET=utf8;
But the problem is that the following statements are not behaving the same way:
getSession().get(Purchase.class, id);
.vs.
getSession().get(Payment.class, id);
where getSession() is defined so that it opens a new or returns a previously opened session. The first statement works perfectly, but the second throws the following exception:
INFO: HHH000327: Error performing load command : org.hibernate.exception.SQLGrammarException: could not extract ResultSet
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at aaserver.ConnectionThread.run(ConnectionThread.java:111)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
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.extract(ResultSetReturnImpl.java:89)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.getResultSet(AbstractLoadPlanBasedLoader.java:449)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeQueryStatement(AbstractLoadPlanBasedLoader.java:202)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:137)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:102)
at org.hibernate.loader.entity.plan.AbstractLoadPlanBasedEntityLoader.load(AbstractLoadPlanBasedEntityLoader.java:186)
at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:4120)
at org.hibernate.event.internal.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:502)
at org.hibernate.event.internal.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:467)
at org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:212)
at org.hibernate.event.internal.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:274)
at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:150)
at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1066)
at org.hibernate.internal.SessionImpl.access$2000(SessionImpl.java:176)
at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.load(SessionImpl.java:2540)
at org.hibernate.internal.SessionImpl.get(SessionImpl.java:951)
at aaserver.DataUnit$Transactions.getPayment(DataUnit.java:347)
at aaserver.DataUnit$Transactions.get(DataUnit.java:353)
at aaserver.ConnectionThread.deleteDocs(ConnectionThread.java:307)
... 8 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'transactio3_.creditor' 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:422)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
at com.mysql.jdbc.Util.getInstance(Util.java:387)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:942)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3966)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3902)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2526)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2673)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2549)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1861)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1962)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:80)
... 26 more
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:209)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at java.net.SocketInputStream.read(SocketInputStream.java:223)
at util.Toolkit.readObject(Toolkit.java:222)
at aaserver.ServerFrame.main(ServerFrame.java:1101)
The SQL generated for the two statements of course differ. For the first, I have:
select purchase0_.id as id2_3_0_, purchase0_.creditor_id as credito15_3_0_, purchase0_.day as day3_3_0_, purchase0_.month as month4_3_0_, purchase0_.year as year5_3_0_, purchase0_.deptor_id as deptor_16_3_0_, purchase0_.dsc as dsc6_3_0_, purchase0_.opponentName as opponent7_3_0_, purchase0_.title as title8_3_0_, purchase0_.val as val9_3_0_, purchase0_.visible as visible10_3_0_, purchase0_.confirmed as confirm11_3_0_, purchase0_.salePoint as salePoi12_3_0_, purchase0_.type as type13_3_0_, purchase0_.valueChangePercentageChain as valueCh14_3_0_, account1_.id as id2_4_1_, account1_.dsc as dsc3_4_1_, account1_.groupName as groupNam4_4_1_, account1_.name as name5_4_1_, account1_.visible as visible6_4_1_, account1_.currentCap as currentC7_4_1_, account1_.workHour as workHour8_4_1_, account1_.DTYPE as DTYPE1_4_1_, account2_.id as id2_4_2_, account2_.dsc as dsc3_4_2_, account2_.groupName as groupNam4_4_2_, account2_.name as name5_4_2_, account2_.visible as visible6_4_2_, account2_.currentCap as currentC7_4_2_, account2_.workHour as workHour8_4_2_, account2_.DTYPE as DTYPE1_4_2_ from ac_transactions purchase0_ left outer join accounts account1_ on purchase0_.creditor_id=account1_.id left outer join accounts account2_ on purchase0_.deptor_id=account2_.id where purchase0_.id=? and purchase0_.DTYPE='Purchase'
and for the second:
select payment0_.id as id2_3_0_, payment0_.creditor_id as credito15_3_0_, payment0_.day as day3_3_0_, payment0_.month as month4_3_0_, payment0_.year as year5_3_0_, payment0_.deptor_id as deptor_16_3_0_, payment0_.dsc as dsc6_3_0_, payment0_.opponentName as opponent7_3_0_, payment0_.title as title8_3_0_, payment0_.val as val9_3_0_, payment0_.visible as visible10_3_0_, payment0_.concern_id as concern19_3_0_, account1_.id as id2_4_1_, account1_.dsc as dsc3_4_1_, account1_.groupName as groupNam4_4_1_, account1_.name as name5_4_1_, account1_.visible as visible6_4_1_, account1_.currentCap as currentC7_4_1_, account1_.workHour as workHour8_4_1_, account1_.DTYPE as DTYPE1_4_1_, account2_.id as id2_4_2_, account2_.dsc as dsc3_4_2_, account2_.groupName as groupNam4_4_2_, account2_.name as name5_4_2_, account2_.visible as visible6_4_2_, account2_.currentCap as currentC7_4_2_, account2_.workHour as workHour8_4_2_, account2_.DTYPE as DTYPE1_4_2_, transactio3_.id as id2_3_3_, transactio3_.creditor_id as credito15_3_3_, transactio3_.day as day3_3_3_, transactio3_.month as month4_3_3_, transactio3_.year as year5_3_3_, transactio3_.deptor_id as deptor_16_3_3_, transactio3_.dsc as dsc6_3_3_, transactio3_.opponentName as opponent7_3_3_, transactio3_.title as title8_3_3_, transactio3_.val as val9_3_3_, transactio3_.visible as visible10_3_3_, transactio3_.creditor as credito17_3_3_, transactio3_.deptor as deptor18_3_3_, transactio3_.concern_id as concern19_3_3_, transactio3_.confirmed as confirm11_3_3_, transactio3_.salePoint as salePoi12_3_3_, transactio3_.type as type13_3_3_, transactio3_.valueChangePercentageChain as valueCh14_3_3_, transactio3_.DTYPE as DTYPE1_3_3_ from ac_transactions payment0_ left outer join accounts account1_ on payment0_.creditor_id=account1_.id left outer join accounts account2_ on payment0_.deptor_id=account2_.id left outer join ac_transactions transactio3_ on payment0_.concern_id=transactio3_.id where payment0_.id=? and payment0_.DTYPE='Payment'
And this second one runs into error.
I don't think that there is a problem with my Hibernate config since everything is working very well, except for this case.
Any idea?
EDIT: I added the SQL generated for both cases.
EDIT 2: Added some more detail about Payment definition.
The SQL shows that it's trying to access
transactio3_.creditor
where transactio3 is the alias for ac_transactions
ac_transactions transactio3_
There's no field creditor in the table, hence the error.
There is an additional outer-join in the second SQL-Statement that's causing the Problem, so the mappings aren't equal.
Edit:
The Mapping
#OneToOne
public Transaction getConcern() {
return concern;
}
should either have a mappedBy attribute or additional #JoinColumn-Mapping (not sure which is right in your case as the Transaction-Class doesn't show the other end of the relationship)
So either
#OneToOne
#JoinColumn(name = "creditor_id")
or
#OneToOne(mappedBy = "transaction")
The hibernate.hbm2ddl.auto="update"property is not doing changes in table after changes done in Entity class.
First I have created an Entity as follows
#Entity
#Table(name="EMPLOYEE_SB")
public class Employee {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="EMP_ID")
private int empId;
#Column(name="EMP_NAME")
private String empName;
//Getter Setter
}
After running application table creation done successfully
Hibernate: create table EMPLOYEE_SB (EMP_ID number(10,0) not null, EMP_NAME varchar2(255 char), primary key (EMP_ID))
Now I have added new field in Entity class as follows
#Entity
#Table(name="EMPLOYEE_SB")
public class Employee {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="EMP_ID")
private int empId;
#Column(name="EMP_NAME")
private String empName;
#Column(name="PHONE")
private String phone;
// Getter and Setter
}
This time the application throw an exception
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL via JDBC Statement
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67)
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlString(AbstractSchemaMigrator.java:524)
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlStrings(AbstractSchemaMigrator.java:470)
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.createTable(AbstractSchemaMigrator.java:273)
at org.hibernate.tool.schema.internal.GroupedSchemaMigratorImpl.performTablesMigration(GroupedSchemaMigratorImpl.java:71)
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.performMigration(AbstractSchemaMigrator.java:203)
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.doMigration(AbstractSchemaMigrator.java:110)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:183)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:72)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:309)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:445)
at com.hibernate.app.HibernateUtil.getSessionFactory(HibernateUtil.java:57)
at com.hibernate.app.MainTestApp.main(MainTestApp.java:8)
Caused by: java.sql.SQLException: ORA-00955: name is already used by an existing object
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:331)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:288)
at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:745)
at oracle.jdbc.driver.T4CStatement.doOall8(T4CStatement.java:210)
at oracle.jdbc.driver.T4CStatement.executeForRows(T4CStatement.java:961)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1190)
at oracle.jdbc.driver.OracleStatement.executeInternal(OracleStatement.java:1726)
at oracle.jdbc.driver.OracleStatement.execute(OracleStatement.java:1696)
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:54)
... 12 more
So in my Oracle database I have two tables which have a foreign key constraint properly defined.
Here are the DDL for the two tables.
CREATE TABLE "BI***********"."PROJECT"
(
"PROJECT_ID" NUMBER(10,0) NOT NULL,
"PROJECT_CODE" VARCHAR2(20) NOT NULL,
"PRODUCT_ID" NUMBER(10,0) NOT NULL,
"DESCRIPTION" VARCHAR2(45) NOT NULL,
CONSTRAINT PROJECT_PK PRIMARY KEY ("PROJECT_ID"),
CONSTRAINT "PROJECT_FK1" FOREIGN KEY ("PRODUCT_ID")
REFERENCES "BI***********"."PRODUCT" ("PRODUCT_ID")
);
CREATE TABLE "BI***********"."PRODUCT"
(
"PRODUCT_ID" NUMBER(10,0) NOT NULL,
"PRODUCT_NAME" VARCHAR2(20) NOT NULL,
"DESCRIPTION" VARCHAR2(45) NOT NULL,
CONSTRAINT PRODUCT_PK PRIMARY KEY ("PRODUCT_ID")
);
And here is the corresponding Java code with the Hibernate Annotations:
#Entity
#Table (name="project")
#SequenceGenerator(name="seq_project",sequenceName="BI***********.SEQ_PROJECT", allocationSize=1, initialValue=1)
public class Project {
//Fields
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seq_project")
#Column(name="PROJECT_ID")
private int id;
#Column(name="PROJECT_CODE")
private String projectCode;
#Column(name="PRODUCT_ID")
private int productId;
#Column(name="DESCRIPTION")
private String description;
#Entity
#Table (name="product")
#SequenceGenerator(name="seq_product",sequenceName="BI***********.SEQ_PRODUCT", allocationSize=1, initialValue=1)
public class Product {
//Fields
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seq_product")
#Column(name="PRODUCT_ID")
private int id;
#Column(name="PRODUCT_NAME")
private String productName;
#Column(name="DESCRIPTION")
private String description;
However, when I try to add to the tables with hibernate I'm receiving the following error code:
Hibernate: insert into project (DESCRIPTION, PRODUCT_ID, PROJECT_CODE, PROJECT_ID) values (?, ?, ?, ?)
Jun 08, 2016 9:06:49 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 2291, SQLState: 23000
Jun 08, 2016 9:06:49 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: ORA-02291: integrity constraint (BIMB2013WMMEE.PROJECT_FK1) violated - parent key not found
Jun 08, 2016 9:06:49 AM org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl release
INFO: HHH000010: On release of batch it still contained JDBC statements
Jun 08, 2016 9:06:49 AM org.hibernate.internal.SessionImpl$5 mapManagedFlushFailure
ERROR: HHH000346: Error during managed flush [could not execute statement]
Jun 08, 2016 9:06:49 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:oracle:thin:#endeavour.us.manh.com:1523/pso11r2f]
Exception in thread "main" org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:59)
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.luv2code.demo.CreateClientDemo.main(CreateClientDemo.java:37)
Caused by: java.sql.SQLIntegrityConstraintViolationException: ORA-02291: integrity constraint (BIMB2013WMMEE.PROJECT_FK1) violated - parent key not found
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:447)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:396)
at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:951)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:513)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:227)
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:531)
Look at your error
Caused by: java.sql.SQLIntegrityConstraintViolationException: ORA-02291: integrity constraint (BIMB2013WMMEE.PROJECT_FK1) violated - parent key not found
Your foreign key in "project" references a primary key in "product" that doesn't exists. You have to make the link between your tables
You have to change your annotations for something like that
#Entity
#Table (name="project")
#SequenceGenerator(name="seq_project",sequenceName="BI***********.SEQ_PROJECT", allocationSize=1, initialValue=1)
public class Project {
//Fields
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seq_project")
#Column(name="PROJECT_ID")
private int id;
#Column(name="PROJECT_CODE")
private String projectCode;
#OneToOne(fetch=FetchType.EAGER, cascade=CascadeType.ALL)
#JoinColumn(name="PRODUCT_ID",insertable=true,
updatable=true,nullable=false,unique=true)
private Product product;
#Column(name="DESCRIPTION")
private String description;
#Entity
#Table (name="product")
#SequenceGenerator(name="seq_product",sequenceName="BI***********.SEQ_PRODUCT", allocationSize=1, initialValue=1)
public class Product {
//Fields
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seq_product")
#Column(name="PRODUCT_ID")
private int id;
#Column(name="PRODUCT_NAME")
private String productName;
#Column(name="DESCRIPTION")
private String description
#OneToOne (mappedBy="PRODUCT_ID",fetch=FetchType.EAGER)
private Project project;
or you can use #PrimaryKeyJoinColumn annotation with
#PrimaryKeyJoinColumn
private Project project;
You'll find more informations about relationships here
My guess is that you need to give the Product class to your Project class, instead of the productId Integer you are using right now.
CONSTRAINT "PROJECT_FK1" FOREIGN KEY ("PRODUCT_ID")
REFERENCES "BI***********"."PRODUCT" ("PRODUCT_ID")
The foreign key states that there is a reference between the two tables, while in your code you only pass an integer, and not the full Product class as an object
Thus i would think that you need to replace:
#Column(name="PRODUCT_ID")
private int productId;
in your Project class with the following:
#Column(name="PRODUCT_ID")
#OneToOne
private Product product;
You have an error in the cfg.xml file. Change hbm2dll to hbm2ddl in
"hibernate.hbm2dll.auto">create
Then life will be beautiful again. I know this because I made the same mistake and spent some hours to figure it out.
How do I define an entity for the following table. I've got something that isn't working and I just want to see what I'm supposed to do.
USE [BAMPI_TP_dev]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[MemberSelectedOptions](
[OptionId] [int] NOT NULL,
[SeqNo] [smallint] IDENTITY(1,1) NOT NULL,
[OptionStatusCd] [char](1) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
This is what I have already that isn't working.
#Entity
#Table(schema="dbo", name="MemberSelectedOptions")
public class MemberSelectedOption extends BampiEntity implements Serializable {
#Embeddable
public static class MSOPK implements Serializable {
private static final long serialVersionUID = 1L;
#Column(name="OptionId")
int optionId;
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="SeqNo", unique=true, nullable=false)
BigDecimal seqNo;
//Getters and setters here...
}
private static final long serialVersionUID = 1L;
#EmbeddedId
MSOPK pk = new MSOPK();
#Column(name="OptionStatusCd")
String optionStatusCd;
//More Getters and setters here...
}
I get the following ST.
[5/25/10 15:49:40:221 EDT] 0000003d JDBCException E org.slf4j.impl.JCLLoggerAdapter error Cannot insert explicit value for identity column in table 'MemberSelectedOptions' when IDENTITY_INSERT is set to OFF.
[5/25/10 15:49:40:221 EDT] 0000003d AbstractFlush E org.slf4j.impl.JCLLoggerAdapter error Could not synchronize database state with session
org.hibernate.exception.SQLGrammarException: could not insert: [com.bob.proj.ws.model.MemberSelectedOption]
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:90)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2285)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2678)
at org.hibernate.action.EntityInsertAction.execute(EntityInsertAction.java:79)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:279)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:263)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:167)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1028)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:366)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:137)
at com.bcbst.bamp.ws.dao.MemberSelectedOptionDAOImpl.saveMemberSelectedOption(MemberSelectedOptionDAOImpl.java:143)
at com.bcbst.bamp.ws.common.AlertReminder.saveMemberSelectedOptions(AlertReminder.java:76)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
It appears that your problem is not an hibernate problems:
Perhaps you have defined a value for "SeqNo" and then tried to saved it
Or in the design view of your database, you should ensure that you set the "IDENTITY" property to "yes" for the column "SeqNo"
And you should do so by executing this after your code :
set IDENTITY_INSERT dbo.MemberSelectedOptions
ON
You can't use generators on composite keys