Hibernate Foreign Key Error - java

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.

Related

Hibernate SQL Reference Exception

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")

hibernate.hbm2ddl.auto = "update" is not working. why?

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

Many-to-Many self-reference hibernate annotation(with two entity)

I need help with my application.
I'm using Hibernate+Postgresql + Maven.
And I want to create relation many to many in database without #ManyToMany annotation, but with two #OneToMany annotations, but I have some trouble with it. I have User entity and Friendship entity.
#Entity
#Table(name="USER")
#SuppressWarnings("unused")
public class User {
#Id
#GeneratedValue
#Column(name="USER_ID")
private Long user_id;
#Column(name="NAME")
private String name;
#Column(name="SOURNAME")
private String sourname;
#Column(name="BIRTHDAY")
private String birthday;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.user1", cascade= CascadeType.ALL)
private Set<Friendship> friendship = new HashSet<Friendship>(0);
#OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.user2")
private Set<Friendship> friendships = new HashSet<Friendship>(0);
//getters and setters
}
#Entity
#Table(name="FRIENDSHIP")
#AssociationOverrides({
#AssociationOverride(name = "pk.user1", joinColumns = #JoinColumn(name = "user_id")),
#AssociationOverride(name = "pk.user2", joinColumns = #JoinColumn(name = "user_id")) })
#SuppressWarnings("unused")
public class Friendship {
#EmbeddedId
private FriendshipId pk = new FriendshipId();
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "CREATED_DATE", nullable = false, length = 10)
private Date createdDate;
public FriendshipId getPk() {
return pk;
}
public void setPk(FriendshipId pk) {
this.pk = pk;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
#Transient
public User getUser1(){return getPk().getUser1();}
#Transient
public User getUser2(){
return getPk().getUser2();
}
public void setUser1(User user1){ getPk().setUser1(user1); }
public void setUser2(User user2){getPk().setUser2(user2);}
}
#Embeddable
public class FriendshipId implements Serializable{
#ManyToOne
private User user1;
#ManyToOne
private User user2;
public User getUser1() {
return user1;
}
public void setUser1(User user1) {
this.user1 = user1;
}
public User getUser2() {
return user2;
}
public void setUser2(User user2) {
this.user2 = user2;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
FriendshipId that = (FriendshipId) o;
if (user1 != null ? !user1.equals(that.user1) : that.user2 != null) return false;
if (user2 != null ? !user2.equals(that.user2) : that.user2 != null) return false;
return true;
}
public int hashCode() {
int result;
result = (user1 != null ? user1.hashCode() : 0);
result = 31 * result + (user2 != null ? user2.hashCode() : 0);
return result;
}
}
and I have this stacktrace:
Caused by: org.hibernate.MappingException: Repeated column in mapping for entity: model.Friendship column: user_id (should be mapped with insert="false" update="false")
at org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:696)
at org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:737)
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:493)
at org.hibernate.mapping.RootClass.validate(RootClass.java:270)
at org.hibernate.cfg.Configuration.validate(Configuration.java:1324)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1782)
help me!
UPD:
#Entity
#Table(name="FRIENDSHIP")
#AssociationOverrides({
#AssociationOverride(name = "pk.user1", joinColumns = #JoinColumn(name = "user_id_1")),
#AssociationOverride(name = "pk.user2", joinColumns = #JoinColumn(name = "user_id_2")) })
#SuppressWarnings("unused")
public class Friendship
and stacktrace now:
INFO: HHH000227: Running hbm2ddl schema export
Hibernate: alter table FRIENDSHIP drop constraint FK_82a932pmyph72ritrnbumysli
апр 08, 2016 10:21:26 AM org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: HHH000389: Unsuccessful: alter table FRIENDSHIP drop constraint FK_82a932pmyph72ritrnbumysli
апр 08, 2016 10:21:26 AM org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: constraint "fk_82a932pmyph72ritrnbumysli" in table "friendship" not exist
Hibernate: alter table FRIENDSHIP drop constraint FK_nlu74mncjyeaokaaj0c5eomrp
Hibernate: drop table if exists FRIENDSHIP cascade
апр 08, 2016 10:21:26 AM org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: HHH000389: Unsuccessful: alter table FRIENDSHIP drop constraint FK_nlu74mncjyeaokaaj0c5eomrp
апр 08, 2016 10:21:26 AM org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: constraint "fk_nlu74mncjyeaokaaj0c5eomrp" in table "friendship" not exist
апр 08, 2016 10:21:26 AM org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: HHH000389: Unsuccessful: drop table if exists USER cascade
апр 08, 2016 10:21:26 AM org.hibernate.tool.hbm2ddl.SchemaExport perform
Hibernate: drop table if exists USER cascade
ERROR: syntax error (approximate location: "USER")
Position: 22
Hibernate: drop sequence hibernate_sequence
Hibernate: create table FRIENDSHIP (CREATED_DATE timestamp not null, user_id_2 int8, user_id_1 int8, primary key (user_id_1, user_id_2))
апр 08, 2016 10:21:26 AM org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: HHH000389: Unsuccessful: create table USER (USER_ID int8 not null, BIRTHDAY varchar(255), NAME varchar(255), SOURNAME varchar(255), primary key (USER_ID))
Hibernate: create table USER (USER_ID int8 not null, BIRTHDAY varchar(255), NAME varchar(255), SOURNAME varchar(255), primary key (USER_ID))
апр 08, 2016 10:21:26 AM org.hibernate.tool.hbm2ddl.SchemaExport perform
Hibernate: alter table FRIENDSHIP add constraint FK_82a932pmyph72ritrnbumysli foreign key (user_id_2) references USER
ERROR:syntax error (approximate location: "USER")
Position: 14
апр 08, 2016 10:21:26 AM org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: HHH000389: Unsuccessful: alter table FRIENDSHIP add constraint FK_82a932pmyph72ritrnbumysli foreign key (user_id_2) references USER
апр 08, 2016 10:21:26 AM org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: syntax error (approximate location: "USER")
Position: 103
Hibernate: alter table FRIENDSHIP add constraint FK_nlu74mncjyeaokaaj0c5eomrp foreign key (user_id_1) references USER
апр 08, 2016 10:21:26 AM org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: HHH000389: Unsuccessful: alter table FRIENDSHIP add constraint FK_nlu74mncjyeaokaaj0c5eomrp foreign key (user_id_1) references USER
апр 08, 2016 10:21:26 AM org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: syntax error (approximate location: "USER")
Position: 103
Hibernate: create sequence hibernate_sequence
апр 08, 2016 10:21:26 AM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
I think the problem with this
#AssociationOverrides({
#AssociationOverride(name = "pk.user1", joinColumns = #JoinColumn(name = "user_id")),
#AssociationOverride(name = "pk.user2", joinColumns = #JoinColumn(name = "user_id")) })
You need to use different names for the foreign key columns user_id_1, user_id_2
#AssociationOverrides({
#AssociationOverride(name = "pk.user1", joinColumns = #JoinColumn(name = "user_id_1")),
#AssociationOverride(name = "pk.user2", joinColumns = #JoinColumn(name = "user_id_2")) })
Do not give names to tables like User. User is a reserved keyword in PostgreSQL. Please, use lower case plural names with prefix like xxx_users.
You can take a look on other useful prefixes and naming approaches: StrategyOptions, Hibernate5NamingStrategy.

EclipseLink and Hibernate integration

we currently work with an Eclipse-Link project (A) and a filled database (with a sequence table).
for my next project (B) I want/need to use Hibernate to access and write data from/to this database. working with an entity that exists in project B is perfectly fine, I can save and read it.
project A entities are needed for B, so I included them in the build path. although when I try to save an entity from project A I get several errors.
basic class Test in project A
#Entity
#Table(name = "test")
public class Test implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
public Test() {
}
public Test(String name) {
this.name = name;
}
// getter & setter
....
}
class Test is added to my sessionFactory
Configuration configuration = new Configuration();
configuration.configure().addAnnotatedClass(Test.class);
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
exceptions when I try to save a Test-object in project B
Hibernate: insert into test (name) values (?)
Nov 21, 2013 1:27:41 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1364, SQLState: HY000
Nov 21, 2013 1:27:41 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Field 'ID' doesn't have a default value
org.hibernate.exception.GenericJDBCException: could not execute statement
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:54)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:136)
at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:96)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:58)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2989)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3501)
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:81)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:393)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:227)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:207)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:191)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:321)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:286)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:192)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:206)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:191)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:764)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:756)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:752)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:352)
at com.sun.proxy.$Proxy12.save(Unknown Source)
at de.main.Dao.save(Dao.java:31)
at de.main.Main.main(Main.java:47)
Caused by: java.sql.SQLException: Field 'ID' doesn't have a default value
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4120)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4052)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2503)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2664)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2794)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2155)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2458)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2375)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2359)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:133)
... 29 more
GenerationType.AUTO lets the provider pick what it wants to use, and this is different in EclipseLink from Hibernate. EclipseLink will use a sequence table (http://wiki.eclipse.org/EclipseLink/Examples/JPA/PrimaryKey), while I believe in Hibernate it depends on the database - but in your case it seems to assume Identity is being used to assign it or the key would exist in the insert statement. Since your tables are not set up for sequencing or identity, you will need to specify the table generation that EclipseLink uses by default, something like:
#Id
#GeneratedValue(generator="testSequence")
#TableGenerator(name="testSequence", table="SEQUENCE",
pkColumnName="SEQ_NAME", valueColumnName="SEQ_COUNT",
pkColumnValue="TEST_GEN")
private int id;
You will have to verify that SEQUENCE table and column names and values being used.
you've to tell you database at table creation to take in concideration the creation of the ID.
in the case of MySql :
CREATE TABLE `test`
(
`ID` int(11) NOT NULL **AUTO_INCREMENT**,
`EMAIL` varchar(255) DEFAULT NULL,
PRIMARY KEY (`ID`)
)
the entity should looks like :
#Entity
#Table(name = "supplier")
public class supplier implements Serializable
{
private static final long serialVersionUID = 1L;
#Id
**#GeneratedValue(strategy = GenerationType.IDENTITY)**
#Column(name = "ID")

One to many map in Hibernate - error

can anyone tell me where is the error in this example
#Entity
#Table(name = "ITEM")
public class Item implements Serializable
{
#Id
#GeneratedValue
#Column(name = "ID")
private Long id;
#Column(name = "NAME")
private String name;
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name = "ID_ITEM",referencedColumnName="ID")
private List<ItemDetail> itemDetails;
second class
#Entity
#Table(name = "ITEM_DETAIL")
public class ItemDetail implements Serializable
{
#Id
#GeneratedValue
#Column(name = "ID")
private Long id;
#Column(name = "NAME")
private String name;
#Column(name = "ID_ITEM")
private Long itemId;
and the db
COMMIT;
CREATE TABLE item(
id serial PRIMARY KEY,
name VARCHAR(16)
);
CREATE TABLE item_detail(
ID serial PRIMARY KEY,
NAME VARCHAR(16),
ID_ITEM serial REFERENCES item (id)
);
COMMIT;
The error i got is
Hibernate: select nextval ('hibernate_sequence')
Hibernate: select nextval ('hibernate_sequence')
Hibernate: select nextval ('hibernate_sequence')
Hibernate: insert into ITEM (NAME, ID) values (?, ?)
Hibernate: insert into ITEM_DETAIL (ITEM_ID, NAME, ID) values (?, ?, ?)
Hibernate: insert into ITEM_DETAIL (ITEM_ID, NAME, ID) values (?, ?, ?)
Exception in thread "main" org.hibernate.exception.SQLGrammarException: Could not execute JDBC batch update
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:90)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:266)
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:1027)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:365)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:137)
at com.mkyong.common.App.main(App.java:51)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:115)
Caused by: java.sql.BatchUpdateException: Batch entry 0 insert into ITEM_DETAIL (ITEM_ID, NAME, ID) values (NULL, id1, 161) was aborted. Call getNextException to see the cause.
at org.postgresql.jdbc2.AbstractJdbc2Statement$BatchResultHandler.handleError(AbstractJdbc2Statement.java:2530)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1317)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:350)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeBatch(AbstractJdbc2Statement.java:2592)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
... 13 more
Process finished with exit code 1
It's obviously that item_id is null but why??
Thanks
Regards
#backebg: can you check your db script and let us know that you executed exactly same in Database. If yes then either correct your entities to use "ID_ITEM" or item_detail table to use 'ITEM_ID' instead 'ID_ITEM'. thanks
Having ITEM_ID mapped as a column in ItemDetail is a bit odd, and mapping it that way might might be the source of the problem. Nothing is telling the ItemDetail class that that field should be populated with a proper id for the parent Item, including that it shouldn't be null.
If the detail doesn't need to know about the parent, you might be able to just omit that field in the ItemDetail java code altogether. The field in the table should be populated as a consequence of the relation.
It's more common to map this sort of thing as a bidirectional association, so that you have a #OneToMany relation of Item to ItemDetail and a #ManyToOne relation of ItemDetail to Item, and the relations can be navigated in Java. If the ItemDetail does need to know about the parent item, you should do it this way.
This is described somewhere in the Hibernate Annotations Reference section on mapping associations.
Use nullable = false to tell Hibernate that the join column cannot be null:
#Entity
#Table(name = "ITEM")
public class Item implements Serializable {
// ...
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name = "ID_ITEM", referencedColumnName = "ID", nullable = false)
private List<ItemDetail> itemDetails;
// ...
}
and remove the itemId property from ItemDetail as it is already mapped by the #JoinColumn annotation. If you need the itemId, then use a bi-directional relationship (hold a reference to the entire Item object, not just the ID).

Categories