I'm not big guru of JPA, but this behaviour looks strange to me, please comment!
I'm trying to persist nested Objects:
each Employee contains Set of Departments
if Department #Id is declared as #Generated int everything works fine. But it is inconvenient and I try to declare as #Id two fields (employee id + department id). But I get
EJBTransactionRolledbackException: A different object with the same identifier value was already associated with the session
on both merge and persist. Is it OK?
Some details:
Departments are declared this way
#OneToMany(fetch = FetchType.LAZY, orphanRemoval = true, cascade = CascadeType.ALL)
#JoinColumn(name = "snils")
private Set<DepartmentRecord> departments = new HashSet<>();
the relation is unidirectional and Persons are not declared in Departments
I populate departments this way:
record.getDepartments().add(new DepartmentRecord(snils, department));
Person is created this way:
Person record = em.find(Person.class, snils);
if (record == null)
record = new Person();
record.setSnils(snils);
record.setFullname(fullname);
record.resetLastActive();
on em.persist(record) or em.merge(record) I get an Exception.
Wrapping it to try catch block doesn't help
Transaction cannot proceed: STATUS_MARKED_ROLLBACK
What I need - is just update Person and Departments. Is it possible without boilerplate code (removing cascade, doing separate departments search et c )???
My environment: CentOS7, java8, Wildfly 10.2
Persons table is :
snils | character varying(255) | not null
blocked | integer | not null
fullname | character varying(255) |
lastactive | date |
Indexes:
"hr_workers_pkey" PRIMARY KEY, btree (snils)
Referenced by:
TABLE "hr_departments" CONSTRAINT "fk49rcpg7j54eq6fpf9x2nphnpu" FOREIGN KEY (snils) REFERENCES hr_workers(snils)
Department table is :
snils | character varying(255) | not null
department | character varying(255) | not null
lastactive | date |
Indexes:
"hr_departments_pkey" PRIMARY KEY, btree (snils, department)
Foreign-key constraints:
"fk49rcpg7j54eq6fpf9x2nphnpu" FOREIGN KEY (snils) REFERENCES hr_workers(snils)
Entity Person (actually SNILSRecord):
#Entity
#Table(name = "hr_workers")
public class SNILSRecord implements Serializable {
#Id
private String snils;
private String fullname;
#OneToMany(fetch = FetchType.LAZY, orphanRemoval = true, cascade = CascadeType.ALL)
#JoinColumn(name = "snils")
private Set<DepartmentRecord> departments = new HashSet<>();
#Temporal(TemporalType.DATE)
private Date lastActive;
private int blocked;
//getters and setters
}
Entity Department:
#Entity
#Table(name = "hr_departments")
public class DepartmentRecord implements Serializable {
#Id
private String snils;
#Id
private String department;
#Temporal(TemporalType.DATE)
private Date lastActive;
Related
Preamble An Oracle DB read-only(I don't have access) has the following two tables:
person
person table
| id | name | gender |
| -- | ------ | ------ |
| 2001 | Moses | M |
| 2002 | Luke | M |
| 2003 | Maryam | F |
PK(id)
reference
reference table
| sep | guid | table_name |
| --- | -------- | ---------- |
| 2001 | EA48-... | person |
| 2002 | 047F-... | person |
| 2003 | B23F-... | person |
| 2003 | 3E3H-... | address |
| 2001 | H2E0-... | address |
| 2001 | 92E4-... | report |
No PK, it is generated by some triggers
The person table is a straight forward table with a primary key. The reference table are generated via a trigger that stores the id(PK) in sep column of any table and the table name that is store in table_name column (Note: Since no primary key, the reference table stores duplicate values in the sep column but distinct value into guid.)
Requirement
I need to use JPA to get the record from the reference table and map to the person record (person.id and other table.id are stored in reference.sep column) using Jackson as follows
{
"id": 2001,
"name": "Moses",
"gender": "M",
"reference": {
"sep": 2001,
"guid": "EA48-...",
"tableName": "person"
}
}
Entity (Person)
#Entity
#Table(name="person")
public class Person implements Serializable {
#Id
private Long id;
private String name;
private String gender;
#OneToOne
#JoinColumn(name = "id", referencedColumnName = "sep", insertable = false, updatable = false)
private Reference reference;
// Getters & Setters
}
Entity (Reference)
#Entity
#Table(name="reference")
public class Reference implements Serializable {
private Long sep;
private String guid;
private String tableName;
//Getters & Setters
}
Problem 1
JPA throws error of no #Id annotation on Reference table.
Problem 2
If I add the #Id annotation on the sep field, JPA throws error of duplicate values for that column.
Problem 3
If I add the #Id annotation on the guid field (it is unique field), JPA throws error of mapping a Long to a String field (org.hibernate.TypeMismatchException: Provided id of the wrong type for class)
Question
How can I structure the entities (Person.java and Reference.java) in order to come up with the output below:
{
"id": 2001,
"name": "Moses",
"gender": "M",
"reference": {
"sep": 2001,
"guid": "EA48-...",
"tableName": "person"
}
}
Reference is the owner of the relationship and needs to be specified as such in either a unidirectional or bidirectional relationship
// Unidirection relationship
#Entity
public class Person implements Serializable {
#Id
private Long id;
private String name;
private String gender;
// Getters & Setters
}
#Entity
public class Reference implements Serializable {
#Id
private String guid;
private String tableName;
#OneToOne
#JoinColumn(name = "sep", insertable = false, updatable = false)
private Person person;
//Getters & Setters
}
// Bidirection relationship
#Entity
public class Person implements Serializable {
#Id
private Long id;
private String name;
private String gender;
#OneToOne(mappedBy = "person")
private Reference reference;
// Getters & Setters
}
#Entity
public class Reference implements Serializable {
#Id
private String guid;
private String tableName;
#OneToOne
#JoinColumn(name = "sep", insertable = false, updatable = false)
private Person person;
//Getters & Setters
}
Same example for read any kind records from table reference:
#Entity
#Table(name = "reference")
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(name = "table_name")
public abstract class AbstractReferenceEntity {
#Id
private UUID guid;
public UUID getGuid() {
return guid;
}
public void setGuid(UUID guid) {
this.guid = guid;
}
}
#Entity
#DiscriminatorValue("person")
public class PersonReferenceEntity extends AbstractReferenceEntity {
#OneToOne
#JoinColumn(name = "sep")
private Person person;
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
}
// Read all types of records.
AbstractReferenceEntity e = this.em.find(AbstractReferenceEntity.class, sameUuid));
// Read only person type of records.
AbstractReferenceEntity e = this.em.find(PersonReferenceEntity, sameUuid);
For the benefit of anyone looking to solve this kind of issue, I will be posting the solution that works for me following #XtremeBaumer suggestion in the comment.
Step 1: For the REFERENCE table, I made the JPA entity to have two ids (sep & table_name) by creating an extra composite Id class and using it in the Reference Entity.
public class RefId {
private Long sep;
private String tableName;
//All args constructor
//No args constructor
//Setters & Getters
//Override the equals() and hashCode() !very important
}
Step 2: Add the above class as a composite id to the Reference entity by using the #IdClass annotation. We must also declare and annotate the two fields with #Id in the Reference class.
#Entity
#Table(name="reference")
#IdClass(RefId.class) // Important if not using embeddable type
public class Reference implements Serializable {
#Id
private Long sep;
private String guid;
#Id
private String tableName;
//Getters & Setters
}
Step 3: In the Person entity, declare #OneToOne on the Reference entity and annotate it with #JoinColumnsOrFormulas as shown below:
#Entity
#Table(name="person")
public class Person implements Serializable {
#Id
private Long id;
private String name;
private String gender;
#OneToOne
#JoinColumnsOrFormulas(value = {
#JoinColumnOrFormula(column = #JoinColumn(name = "id", referencedColumnName = "sep", insertable = false, updatable = false)),
#JoinColumnOrFormula(formula = #JoinFormula(value = "'person'", referencedColumnName = "tableName"))
})
private Reference reference;
// Getters & Setters
}
This works fine in the scenario above. Note in the formula = #JoinFormula, it is like we are declaring the 'WHERE' clause i.e. WHERE table_name = 'person' (Don't miss the single quotes)
Lastly, by using the Jackson object mapper, I was able to get
{
"id": 2001,
"name": "Moses",
"gender": "M",
"reference": {
"sep": 2001,
"guid": "EA48-...",
"tableName": "person"
}
}
Thanks for your insight (#XtremeBaumer)
I am new to Hibernate and JPA and am trying to wire up a database of movies, raters, and ratings. I keep getting the error Caused by: org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: com.stephenalexander.projects.movierecommender.rating.Rating.movie in com.stephenalexander.projects.movierecommender.movie.Movie.ratings. Each Movie object and each Rater object has a OneToMany relationship with Rating. Here is how I've written things:
Rating:
package com.stephenalexander.projects.movierecommender.rating;
import com.stephenalexander.projects.movierecommender.movie.Movie;
import com.stephenalexander.projects.movierecommender.rater.Rater;
import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.Objects;
#Entity
#Table(name="rating")
public class Rating {
#Column(name = "rating_id")
private Long ratingId;
#Column(name = "rating")
private Double ratingValue;
private LocalDateTime time;
#ManyToOne
#JoinColumn(name = "rater_id", nullable = false)
private Rater rater;
#ManyToOne
#JoinColumn(name = "movie_id", nullable = false)
private Movie movie;
Movie:
package com.stephenalexander.projects.movierecommender.movie;
import com.stephenalexander.projects.movierecommender.rating.Rating;
import javax.persistence.*;
import java.util.List;
#Entity
#Table(name = "movie")
public class Movie {
#Id
#GeneratedValue(
strategy = GenerationType.AUTO
)
#Column(name = "movie_id")
private Integer movieId;
private String title;
private int year;
#Column(name = "posterurl")
private String posterUrl;
#Column(name = "runningtime")
private int runningTime;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "movie")
List<Rating> ratings;
Rater:
package com.stephenalexander.projects.movierecommender.rater;
import com.stephenalexander.projects.movierecommender.rating.Rating;
import javax.persistence.*;
import java.util.List;
import java.util.Objects;
#Entity
#Table(name = "rater")
public class Rater {
#Id
#GeneratedValue(
strategy = GenerationType.AUTO
)
#Column(name = "rater_id")
private Long raterId;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "rater")
private List<Rating> ratings;
I have looked at a number of other posts, and this error seems to most commonly be caused by the mappedBy annotation referencing something other than the name of the instance variable within the owner class. I believe I've done that correctly since the Rating class has a variable named rater and a variable named movie. I'm not sure what else could be causing the error. Thanks very much for reading!
EDIT: Adding my comment from an answer here to clarify how I've thought these annotations work:
As I understand it, List<Rating> ratings is mappedBy: "movie", so the movie object in Rating by its annotation will tell you what column the relationship is built on, which is the primary key of movie and foreign key of rating, movie_id. Same thing with rater_id. Is this not how the whole thing works?
EDIT 2: Another thought I have that might be a misunderstanding... are these notations not necessary if I've set up the relationships in my psql database already? Is this redundant? I thought the point of these was to essentially allow me to navigate the queries in java more easily. I was led to these notations defining relationships after I kept trying to write queries and ran into errors leading me to believe my code had no idea these tables were related. Here is how they're all set up in PostgreSQL:
-----------+-----------------------------+-----------+----------+-------------------------------------------
rating_id | integer | | not null | nextval('rating_rating_id_seq'::regclass)
rater_id | integer | | not null |
movie_id | integer | | not null |
rating | smallint | | |
time | timestamp without time zone | | |
Indexes:
"rating_pkey" PRIMARY KEY, btree (rating_id)
Foreign-key constraints:
"rating_movie_id_fkey" FOREIGN KEY (movie_id) REFERENCES movie(movie_id) ON UPDATE CASCADE
"rating_rater_id_fkey" FOREIGN KEY (rater_id) REFERENCES rater(rater_id) ON UPDATE CASCADE
Table "public.rater"
Column | Type | Collation | Nullable | Default
----------+---------+-----------+----------+---------
rater_id | integer | | not null |
Indexes:
"rater_pkey" PRIMARY KEY, btree (rater_id)
Referenced by:
TABLE "rating" CONSTRAINT "rating_rater_id_fkey" FOREIGN KEY (rater_id) REFERENCES rater(rater_id) ON UPDATE CASCADE
Table "public.movie"
Column | Type | Collation | Nullable | Default
-------------+------------------------+-----------+----------+---------
movie_id | integer | | not null |
title | character varying(100) | | not null |
year | smallint | | not null |
runningtime | smallint | | not null |
posterurl | character varying(350) | | |
Indexes:
"movie_pkey" PRIMARY KEY, btree (movie_id)
Referenced by:
TABLE "movies_genres" CONSTRAINT "fk_movie" FOREIGN KEY (movie_id) REFERENCES movie(movie_id)
TABLE "movies_directors" CONSTRAINT "fk_movie" FOREIGN KEY (movie_id) REFERENCES movie(movie_id)
TABLE "movies_countries" CONSTRAINT "fk_movie" FOREIGN KEY (movie_id) REFERENCES movie(movie_id)
TABLE "rating" CONSTRAINT "rating_movie_id_fkey" FOREIGN KEY (movie_id) REFERENCES movie(movie_id) ON UPDATE CASCADE
#Column(name = "movie_id")
private Integer movieId;
#ManyToOne
#JoinColumn(name = "movie_id", nullable = false)
private Movie movie;
U have a column with the same as movie_id in Rating and also in Movie. Hence there is a conflict.
Change either one of them.
What was missing was the targetEntity = Rating.class param to #OneToMany. So the functional annotations within the different classes are as follows:
Movie
#OneToMany(fetch = FetchType.LAZY, targetEntity = Rating.class, mappedBy = "movie")
private List<Rating> ratings
Rater
#OneToMany(fetch = FetchType.LAZY, targetEntity = Rating.class, mappedBy = "rater")
private List<Rating> ratings
Rating
#ManyToOne
#JoinColumn(name = "rater_id", nullable = false)
private Rater rater;
#ManyToOne
#JoinColumn(name = "movie_id", nullable = false)
private Movie movie;
Thanks to all who took a look at this!
I am facing a problem about how to manage mapping for a specific model.
This is a multitenant application, and we have made the choice of including the "tenant_id" in every entity, so we don't have to make a joint everytime we need to get an entity (in fact, this is the root of my problem...).
The model is as follow :
+--------------------+ +---------------+
| Book | | Author |
+--------------------+ +---------------+
| id (pk) | | id (pk) |
| tenant_id (pk)(fk) | | tenant_id (pk |
| author_id (fk) | | name |
| title | +---------------+
+--------------------+
As you can see, the tenant-id is in each entity, and part of the primary key. We use #IdClass to manage the composite key. Here is the code :
#Data
public class TenantAwareKey implements Serializable {
private UUID id;
private Integer tenantId;
}
#IdClass(TenantAwareKey.class)
#Entity
#Table(name = "BOOK")
#Data
public class Book {
#Id
#GeneratedValue
#Column(name = "ID")
private UUID id;
#Id
#Column(name = "TENANT_ID")
private Integer tenantId;
private String title;
#ManyToOne
#JoinColumns(
value = {
#JoinColumn(referencedColumnName = "id", name = "author_id"),
#JoinColumn(referencedColumnName = "tenant_id", name = "tenant_id", insertable = false, updatable = false)
})
private Author author;
}
#IdClass(TenantAwareKey.class)
#Entity
#Data
public class Author {
#Id
#GeneratedValue
#Column(name = TenantAwareConstant.ENTITY_ID_COLUMN_NAME)
private UUID id;
#Id
#Column(name = TenantAwareConstant.TENANT_ID_COLUMN_NAME)
private Integer tenantId;
private String name;
}
And then, when running my application I ended up with :
Caused by: org.hibernate.AnnotationException: Mixing insertable and non insertable columns in a property is not allowed:
com.pharmagest.durnal.tenant.entity.BookNoDuplicateColumn.author
at org.hibernate.cfg.Ejb3Column.checkPropertyConsistency(Ejb3Column.java:725)
at org.hibernate.cfg.AnnotationBinder.bindManyToOne(AnnotationBinder.java:3084)
(...)
I manage to make it work if I don't try to "mutualize" the tenant_id column, it can be acceptable when I have only one foreign key with this tenant_id, but less and less as the number of foreign key increase, resulting in adding a tenant_id column each time, duplicating information et spoiling memory...
After digging a bit, I found an open issue in Hibernate : https://hibernate.atlassian.net/browse/HHH-6221
It has not been fixed for years... So, my question is : Have you faced a mapping like this, and is there a solution to avoid duplicated columen when I have a foreign-key that share a field with the primary key?
As described here, you can bypass the validation by using #JoinColumnOrFormula for the column id_tenant.
You should map the author's association like this:
#JoinColumnsOrFormulas(
value = {
#JoinColumnOrFormula(column = #JoinColumn(referencedColumnName = "id", name = "author_id")),
#JoinColumnOrFormula(formula = #JoinFormula(referencedColumnName = "tenant_id", value = "tenant_id"))
})
I'm trying to set up a OneToOne relationship between two entities that share the same PK:
+----------------------------------+ +----------------+-----------------+
| Item | | Stats |
+----------------+-----------------+ +----------------+-----------------+
| reference (PK) | other data... | | reference (PK) | other data... |
+----------------+-----------------+ +----------------+-----------------+
| ABCD | ... | | ABCD | ... |
| XYZ | ... | | XYZ | ... |
+----------------+-----------------+ +----------------+-----------------+
where Stats.reference is a FK to Item.reference:
alter table Stats
add constraint FK_8du3dv2q88ptdvthk8gmsipsk
foreign key (reference)
references Item;
This structure is generated from the following annotaded classes:
#Entity
public class Item {
#Id
private String reference;
#OneToOne(mappedBy = "item", optional = false)
#Cascade({CascadeType.SAVE_UPDATE})
#Fetch(FetchMode.SELECT)
private Stats stats;
// ...
}
#Entity
public class Stats {
#Id
#OneToOne
#JoinColumn(name = "reference")
#Fetch(FetchMode.SELECT)
private Item item;
// ...
}
A new Item is creted as follows:
Item item = new Item();
item.setReference("ABC");
Stats stats = new Stats();
stats.setItem(item);
item.setStats(stats);
session.save(item);
My problem is when I do session.save(item) the INSERT statements order are wrong.
Hibernate first tries to insert into Stats table instead of Item, resulting in a FK constraint error.
How can I solve this issue? Thanks in advance.
Since your class Stats owns the association, try to do :
stats.setItem(item);
session.save(stats)
since you have one to one relationship between item and state and item has stats key as FK, and here you entity object should look like this
Item{
#OneToOne
#JoinColumn(name = "stat_id", nullable=false) //incase if you allow null
private stats stats
}
in stats entity no need to add relation annotation, since we defined in Item
while saving , you just save item entity, stats also get inserted
item.setStats(stats);
session.save(item);
in case if you want to save stats separately and items separately,
then you have define cascade type as DETACH for stats
Class Item{
#OneToOne(cascade=CascadeType.DETACH)
#JoinColumn(name = "stat_id", nullable=false) //incase if you allow null
private stats stats
}
The #JoinColumn annotation in Stats entity isn't complete, the attribute referencedColumnName must be specified.
public abstract java.lang.String referencedColumnName
(Optional) The name of the column referenced by this foreign key
column.
#Entity
public class Stats {
#Id
#OneToOne
#JoinColumn(name = "reference", referencedColumnName = "reference")
#Fetch(FetchMode.SELECT)
private Item item;
// ...
}
I have 3 models User, House, UserHouseMap. And I need to access a user's house through the map. Only problem is this is an old DB & I can't change the fact that I need to map User to UserHouseMap using user.name, which is a non primary key.
Hibernate keeps giving me errors saying I need to have it as the primary key or I get errors saying A JPA error occurred (Unable to build EntityManagerFactory): Unable to find column with logical name: name in org.hibernate.mapping.Table(users) and its related supertables and secondary tables
I have tried #Formula as a workaround, but that didnt work. I also tried #JoinColumnOrFormula but that didnt work either. Here is my solution with #Formula
#Expose
#ManyToOne(targetEntity = House.class)
#Formula("(select * from houses inner join user_house_map on houses.house_name = user_house_map.house_name where user_house_map.user_name=name)")
public House house;
Here was my attempt at a #JoinColumnOrFormula solution.
#Expose
#ManyToOne(targetEntity = House.class)
#JoinColumnsOrFormulas({
#JoinColumnOrFormula(formula=#JoinFormula(value="select name from users where users.id= id", referencedColumnName="name")),
#JoinColumnOrFormula(column = #JoinColumn(name= "house_name", referencedColumnName="house_name"))
})
public House house;
Here is my mapping
#Id
#GeneratedValue
#Expose
public Long id;
#Expose
#Required
#ManyToOne
#JoinTable(
name="user_house_map",
joinColumns=
#JoinColumn(unique=true,name="user_name", referencedColumnName="name"),
inverseJoinColumns=
#JoinColumn(name="house_name", referencedColumnName="house_name"))
private House house;
Here are the DB schemas
Users
Table "public.users"
Column | Type | Modifiers
-----------------------+-----------------------------+-----------------------------
name | character varying(255) |
id | integer | not null
Indexes:
"user_pkey" PRIMARY KEY, btree (id)
Foreign-key constraints:
"housing_fkey" FOREIGN KEY (name) REFERENCES user_house_map(user_name) DEFERRABLE INITIALLY DEFERRED
Houses
Table "public.houses"
Column | Type | Modifiers
---------------+------------------------+-----------
house_name | character varying(255) | not null
address | text |
city | text |
state | text |
zip | integer |
zip_ext | integer |
phone | text |
Indexes:
"house_pkey" PRIMARY KEY, btree (house_name)
Referenced by:
TABLE "user_house_map" CONSTRAINT "house_map_fkey" FOREIGN KEY (house_name) REFERENCES house(house_name) DEFERRABLE INITIALLY DEFERRED
UserHouseMap
Table "public.user_house_map"
Column | Type | Modifiers
-------------+------------------------+-----------
user_name | character varying(255) | not null
house_name | character varying(255) | not null
Indexes:
"user_house_map_pkey" PRIMARY KEY, btree (user_name)
"user_house_map_house_key" btree (house_name)
Foreign-key constraints:
"user_house_map_house_fkey" FOREIGN KEY (house_name) REFERENCES houses(house_name) DEFERRABLE INITIALLY DEFERRED
Referenced by:
TABLE "users" CONSTRAINT "housing_fkey" FOREIGN KEY (name) REFERENCES user_house_map(user_name) DEFERRABLE INITIALLY DEFERRED
This is how your mapping should look like:
#Entity
public class User {
#Id
private Long id;
private String name;
#OneToMany(mappedBy = "user")
private List<UserHouseMap> houses = new ArrayList<>();
}
#Entity
public class House {
#Id
#Column(name = "house_name", nullable = false, unique = true)
private String house_name;
private String address;
#OneToMany(mappedBy = "house")
private List<UserHouseMap> users = new ArrayList<>();
}
#Entity
public class UserHouseMap implements Serializable {
#Id #ManyToOne
#JoinColumn(name = "user_name", referencedColumnName = "name")
private User user;
#Id #ManyToOne
#JoinColumn(name = "house_name", referencedColumnName = "house_name")
private House house;
}
Both User and House have access to their associated UserHouseMap entities, matching the database schema.