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

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.

Related

Why is Hibernate not creating many-to-many join tables?

I am trying to get Hibernate to create a many-to-many relationship join table. The entity tables are created just fine, but the join table won't show up. Some source create the join table by hand, others, like Youtube Tutorials explain how they are created automatically by Hibernate.
Here is my first Entity table:
package com.presents;
import javax.persistence.*;
import java.io.Serial;
import java.io.Serializable;
import java.util.Set;
#Entity
#Table(name = "articles")
public class Article implements Serializable {
#Serial
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private int id;
#Column(name = "name")
private String name;
#Column(name = "link")
private String url;
#Column(name = "likes")
private int likes;
#Column(name = "clicks")
private int clicks;
#ManyToMany(cascade = { CascadeType.ALL })
#JoinTable(
name = "category_article",
joinColumns = {
#JoinColumn(name = "article_id", referencedColumnName = "id")
},
inverseJoinColumns = {
#JoinColumn(name = "category_id", referencedColumnName = "id")
}
)
public Set<Categories> categories = new HashSet<>();;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public int getLikes() {
return likes;
}
public void setLikes(int likes) {
this.likes = likes;
}
public int getClicks() {
return clicks;
}
public void setClicks(int clicks) {
this.clicks = clicks;
}
public Set<Categories> getCategories() {
return cats;
}
public void setCategories(Set<Categories> categories) {
this.cats = categories;
}
}
This is my second Entity table:
package com.presents;
import javax.persistence.*;
import java.io.Serial;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
#Entity
#Table(name = "category")
public class Categories implements Serializable {
#Serial
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name = "id")
private int id;
#Column(name = "category")
private String category;
#ManyToMany(mappedBy = "categories")
public Set<Article> articles = new HashSet<>();
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public void setCategory(String category) {
this.category = category;
}
public String getCategory() {
return category;
}
public void setArticles(Set<Article> articles) {
this.articles = articles;
}
public Set<Article> getArticles() {
return articles;
}
}
The idea is that any article can be in many categories, but more than one category can apply to any article.
I am using a SQLite3 database, but I tried also with a MySQL database, both to no avail. Hibernate seems somehow to avoid the many-to-many annotation completely. It does not complain about it when I ran the code and seems to avoid it altogether. Again, the other to tables are created beautifully, without me fumbling around with any SQL commands.
Why is Hibernate refusing to create the join table, and how do I fix it?
Here is the output of Hibernate:
INFO: HHH000412: Hibernate ORM core version 5.6.2.Final
Dez. 18, 2021 8:41:14 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
Dez. 18, 2021 8:41:15 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Dez. 18, 2021 8:41:15 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [org.sqlite.JDBC] at URL [jdbc:sqlite:presents.db]
Dez. 18, 2021 8:41:15 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {}
Dez. 18, 2021 8:41:15 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Dez. 18, 2021 8:41:15 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Dez. 18, 2021 8:41:15 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.SQLiteDialect
Hibernate: drop table if exists articles
Hibernate: drop table if exists category
Hibernate: drop table if exists hibernate_sequence
Hibernate: create table articles (id integer not null, name varchar, link varchar, likes integer, clicks integer, primary key (id))
Hibernate: create table category (id integer not null, category varchar, primary key (id))
Hibernate: create table hibernate_sequence (next_val bigint)
Hibernate: insert into hibernate_sequence values ( 1 )
Dez. 18, 2021 8:41:16 AM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess#334ebcaa] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Dez. 18, 2021 8:41:16 AM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess#107bfcb2] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Dez. 18, 2021 8:41:16 AM org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator initiateService
INFO: HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
Hibernate: select next_val as id_val from hibernate_sequence
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
Hibernate: select next_val as id_val from hibernate_sequence
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
Hibernate: select next_val as id_val from hibernate_sequence
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
Hibernate: select next_val as id_val from hibernate_sequence
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
Hibernate: select next_val as id_val from hibernate_sequence
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
Hibernate: select next_val as id_val from hibernate_sequence
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
Hibernate: select next_val as id_val from hibernate_sequence
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
Hibernate: insert into articles (name, link, likes, clicks, id) values (?, ?, ?, ?, ?)
Hibernate: insert into articles (name, link, likes, clicks, id) values (?, ?, ?, ?, ?)
Hibernate: insert into articles (name, link, likes, clicks, id) values (?, ?, ?, ?, ?)
Hibernate: insert into articles (name, link, likes, clicks, id) values (?, ?, ?, ?, ?)
Hibernate: insert into category (category, id) values (?, ?)
Hibernate: insert into category (category, id) values (?, ?)
Hibernate: insert into category (category, id) values (?, ?)
Hibernate: select categories0_.id as id1_1_, categories0_.category as category2_1_ from category categories0_
You need to get an article, then add a category and save it. For example:
Categories category = categoryRepository.getById(100001);
article.getCategories().add(category);
articlesRepository.save(article);
productRepository.findAll();
This will add a new entry to the category_article table.
I found the mistake myself. I was using JPA annotations when I should have used Hibernate XML mapping. After removing every annotation and creating the necessary lines in the XML mapping files, the table appeared.

Hibernate many to one of the same entity. How to delete?

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.

JPA composite key (FKs + date) set date to auto_increment

I am working on a Java play project and trying to create a time tracker for users on projects. I have the following class for tracking time:
#Entity(name = "trackings")
public class Tracking extends Model {
#EmbeddedId
public TrackingPK id;
#ManyToOne
#MapsId("user")
#JoinColumn(name="user", referencedColumnName="id")
public User user;
#ManyToOne
#MapsId("project")
#JoinColumn(name="project", referencedColumnName="id")
public Project project;
#Required
#Enumerated(EnumType.STRING)
public ETrackingDuration duration;
#Embeddable
public class TrackingPK implements Serializable {
#ManyToOne
#JoinColumn(name = "user_id", referencedColumnName = "id", insertable = false, updatable = false)
private User user;
#ManyToOne
#JoinColumn(name = "project_id", referencedColumnName = "id", insertable = false, updatable = false)
private Project project;
#Column(name="date", columnDefinition="DATE NOT NULL")
#Temporal(TemporalType.DATE)
private Date date;
}
}
Unfortunately, JPA keeps making date as an auto_increment and I have no idea why.
Here are my logs:
09:14:16,939 ERROR ~ HHH000388: Unsuccessful: create table trackings (date datetime not null auto_increment, project_id bigint not null, user_id bigint not null, id bigint not null, duration varchar(255), primary key (date, project_id, user_id, id)) ENGINE=InnoDB DEFAULT CHARSET=utf8
09:14:16,939 ERROR ~ Incorrect column specifier for column 'date'
09:14:16,941 ERROR ~ HHH000388: Unsuccessful: alter table trackings add index FK_fjady3y2u9ej76atpce4djsu5 (project_id), add constraint FK_fjady3y2u9ej76atpce4djsu5 foreign key (project_id) references projects (id)
09:14:16,941 ERROR ~ Table 'trackings' doesn't exist
09:14:16,944 ERROR ~ HHH000388: Unsuccessful: alter table trackings add index FK_rdi49oyr8mro9t6vjj5towo0b (user_id), add constraint FK_rdi49oyr8mro9t6vjj5towo0b foreign key (user_id) references users (id)
Foreign keys are correct but not date...
There are a couple of issues with the mapping that I can see:
You need #MapsId("user") and #MapsId("project") on Tracking.user and Tracking.project, respectively
The #Column annotations on TrackingPK.user and TrackingPK.project are redundant with #MapsId in place (you may actually run into problems if you define the same column twice in JPA, without declaring it insertable=false, updatable=false in one of the definitions)
JPA allows java.util.Date as long as the temporal type is set to TemporalType.DATE (see: https://docs.oracle.com/javaee/7/tutorial/persistence-intro001.htm; your JPA provider might allow it, though, but you would need to check)
As regards the schema definition problem, if all else fails, try using columnDefinition="date not null" to override the default SQL for that column.
EDIT It turns out that play.db.jpa.Model defines an #Id column. Mixing #Id and #EmbeddedId is what causes the problem. You'll want to extend from play.db.jpa.GenericModel instead.

Hibernate Foreign Key Error

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.

Duplicate entry 'nn' for key '.... '

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.

Categories