I have Type class as entity. The Type can have one parent type and many children types.
#Entity
#Table(name = "type")
public class Type extends EntityItem {
...
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "parent_type", referencedColumnName = "id")
private Type parentType;
#OneToMany(mappedBy = "parent_type")
private List<Type> childTypes = new ArrayList<>();
...
}
When I create parent type with children and save them, all is OK. But when I'm trying to delete the parent, I have the error below
2018-08-05 15:58:50,843 INFO [main] impl.TypeServiceImpl (TypeServiceImpl.java:53) - Type delete: Type [id=1000, parentType=null]
Hibernate:
delete
from
type
where
id=?
Aug 05, 2018 3:58:50 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 0, SQLState: 23503
Aug 05, 2018 3:58:50 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: ERROR: update or delete on table "type" violates foreign key constraint "fk_gbqg39jytwquch0bjm9j80gsf" on table "type"
Подробности: Key (id)=(1000) is still referenced from table "type".
Could you please explain what is wrong?
Thanks a lot.
Related
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")
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.
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.
I'm getting this error quite alot, and my hibernate is acting strange when I try to insert objects into my tables in my mySQL database.
okt. 06, 2015 9:57:28 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1062, SQLState: 23000
okt. 06, 2015 9:57:28 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Duplicate entry '77' for key 'UK_2gy9x2d1hqmk0d77o8ux44c6o'
okt. 06, 2015 9:57:28 PM org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl release
INFO: HHH000010: On release of batch it still contained JDBC statements
org.hibernate.exception.ConstraintViolationException: could not execute statement
When I look in MySQL WOrkbench I can see that whenever I persist or merge I get duplicate rows in my database tables.
I use these two methods for persist and merge:
public void persist(Object entity) {
session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
session.persist(entity);
session.flush();
session.getTransaction().commit();
}
public void merge(Object entity) {
session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
session.merge(entity);
session.flush();
session.getTransaction().commit();
}
I got my user class which has a ManyToMany with note class.
#ManyToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST } )
#JoinTable(
name = "user_note",
joinColumns = {#JoinColumn(name = "empId")},
inverseJoinColumns = {#JoinColumn(name = "note_id")})
private Set<Note> bookmarks = new HashSet<>();
note:
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private long projectId;
and a third class which has a OneToMany relation with note.
#OneToMany(fetch = FetchType.LAZY, cascade = { CascadeType.ALL })
#JoinTable(name = "organisation_note", joinColumns = { #JoinColumn(name = "OrganisationId") }, inverseJoinColumns = { #JoinColumn(name = "note_id") })
private Set<Note> bookmarks = new HashSet<>();
I've been looking around, and can't seem to find any topics on duplicated rows in the database. The first persist won't duplicate the row, but the second will, and the third will throw the exception. After that it's just exceptions after each time I try to persist. Which is not that reliable. Any input is appreciated.
I am trying to have unidirectional OneToOne relationship b/w two classes "Restaurant" and "Manager". "Manager" is child class which has one attribute called restaurantId.
here is my code and problem is explained below it:
Restaurant.java:
#Entity
public class Restaurant implements Serializable{
#Id
private long id;
//getters and setters}
RestaurantRepository.java
import java.util.List;
import org.springframework.data.repository.CrudRepository;
public interface RestaurantRepository extends CrudRepository<Restaurant, Long> {
List<Restaurant> findById(long id);
}
Manager.java:
#Entity
public class Manager implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private long id;
#OneToOne(fetch=FetchType.LAZY,optional=false,cascade = CascadeType.ALL)
#JoinColumn(name="restaurantId", referencedColumnName="id",nullable=false)
private Restaurant restaurantId;
//getters and setters}
I am trying to test add method for Manager.java in below test class:
public class ManagerTest {
private CrudRepository repository;
#Test
public void testAddManager() {
AbstractApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
CrudRepository restaurantRepository = context.getBean(RestaurantRepository.class);
Date date = new Date();
Restaurant restaurant = (Restaurant) restaurantRepository.findOne(1L);
repository = context.getBean(ManagerRepository.class);
createManager("x","xx","xxxxxxxx","x","x","x","India","null","null", date, "jimish#auberginesolutions.com", restaurant);
context.close();
}
private void createManager(String firstName, String lastName, String contactNo, String addrStreet,String addrCity, String addrState, String addrCountry, String addrLat, String addrLong, Date birthDate, String email, Restaurant restaurant){
Manager manager = new Manager(firstName, lastName, contactNo, addrStreet, addrCity, addrState, addrCountry, addrLat, addrLong, birthDate, email);
manager.setRestaurantId(restaurant);
repository.save(manager);
}
}
With above code I am expecting a new entry in Manager table, but It is trying to make entry in Restaurant Table.
here is console error in eclipse:
Hibernate: insert into Restaurant (addrCity, addrCountry, addrLat, addrLong, addrState, addrStreet, contactNo, maxCapacity, name, id) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Sep 16, 2014 2:24:20 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1062, SQLState: 23000
Sep 16, 2014 2:24:20 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Duplicate entry '1' for key 'PRIMARY'
Sep 16, 2014 2:24:20 PM org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl release
INFO: HHH000010: On release of batch it still contained JDBC statements
please help me out here. Any suggestion would be great.:)
You may be trying to add an entry with an already existing id
Either you forgot to AUTO_INCREMENT the id or you picked an invalid (already existing) id for your manager/restaurant.
You may find more details there
Error Code: 1062. Duplicate entry '1' for key 'PRIMARY'