Hibernate is not persisting nested relationship - java

I have 4 entities: Play, Actor, Play-representation and Category.
Each play belongs to a category and play-representation associates a play with a theater and a number of actors at a given time.
Here are the entities:
#Entity
#Table(name = "category")
public class Category {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#Column(name = "name")
private String name;
#OneToMany(mappedBy="category")
private List<Play> playList = new ArrayList<Play>();
#Entity
#Table(name = "actor")
public class Actor {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private long id;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "description")
private String description;
#Column(name = "profile_picture")
private String profilePicturePath;
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinTable(name = "play_representation_category",
joinColumns = {#JoinColumn(name = "actor_id")},
inverseJoinColumns = {#JoinColumn(name = "play_representation_id")})
private Set<PlayRepresentation> playRepresentations = new HashSet<>(0);
#Entity
#Table(name = "play")
public class Play {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#NotNull
#Column(name = "name")
private String name;
#NotNull
#Column(name = "description")
private String description;
#Column(name = "image_paths")
private String imagePaths;
#NotNull
#ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private Category category;
#Entity
#Table(name = "play_representation")
public class PlayRepresentation {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "play_id")
private Play play;
#OneToOne
#JoinColumn(name = "theater_id")
private Theater theater;
#Column(name = "date")
private Timestamp airingDate;
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinTable(name = "play_representation_category",
joinColumns = {#JoinColumn(name = "play_representation_id", nullable=false)},
inverseJoinColumns = {#JoinColumn(name = "actor_id", nullable=false)})
private Set<Actor> actors = new HashSet<>(0);
The issue I'm having is that hibernate is trying to find a relationship between play_representation and category! I've been trying to persist the relationship for the plays but it seems I got that wrong and can't figure out the best way to do it...It's a postgresql db by the way.
I am still learning, so if you have any other tips regarding the code I've shared, please let me know!
Edit: error is:
org.postgresql.util.PSQLException: ERROR: relation "play_representation_category" does not exist
Position: 281

I didn't need a mappedBy, it was actually a typo - I wrote play_representation_category instead of play_representation_actors. Pretty stupid, huh? At least I finally found it :)

Related

Is there a way to return user rating of a one book for that user?

I am working on a project, trying to create an AudioBook website. I am stuck on this part and i cant find answers on the internet.
The problem is when i get user, and list of favorite books, each book has list of user rating, from all of the users. And also there is a list of UserRatings that contains all of ratings from that user. I dont want neither.
Basically, is there a way to make it so when i do a search for list of books, every book object contains UserRating(One user rating) from a specific User that is logged in?
#Entity
#Table(name = "user_rating")
public class user_rating {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column
private Integer Id;
#Column
private String rating;
#ManyToOne
#JoinColumn(name = "user_id")
private users user;
#ManyToOne
#JoinColumn(name = "book_id")
private books book;
#Entity
#Table(name = "users")
public class users {
#Id
#Column
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column
private String name;
#Column(name = "last_name")
private String lastName;
#Column(name = "email")
private String email;
#Column(name = "date_of_creation")
private java.sql.Date dateOfCreation;
#Column
private String password;
#JsonManagedReference
#ManyToMany
#JoinTable(
name = "favourites",
joinColumns = #JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(name = "book_id", referencedColumnName = "id")
)
private Set<books> favourites = new HashSet<>();
#OneToMany(mappedBy ="user")
private List<user_rating> UserRating = new ArrayList<>();
#Entity
#Table(name = "books")
public class books {
#Id
#Column
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column
private String name;
#Column
private String description;
#Column(name = "date_of_creation")
private java.sql.Date date_of_creation;
#Column
private String text_file;
#JsonBackReference
#ManyToMany(mappedBy = "favourites")
private Set<users> users = new HashSet<>();
#JsonManagedReference
#ManyToMany()
#JoinTable(
name = "book_tags",
joinColumns = #JoinColumn(name = "book_id", referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(name = "tag_id", referencedColumnName = "id")
)
private List<tags> tags = new ArrayList<>();
#OneToOne
#PrimaryKeyJoinColumn
private audio_file audioFile;
#OneToMany(mappedBy = "book")
private List<user_rating> UserRatings = new ArrayList<>();

JPA exception : More than one row with the given identifier was found

I am developing application with Spring Boot, Vaadin and JPA.
I created 3 entity classes:
Author:
#Entity
#Table(name = "author")
public class Author {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="id")
private Long id;
#Column(name = "name")
private String name;
#Column(name = "surname")
private String surname;
#Column(name = "patronymic")
private String patronymic;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "author", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<Book> books;
Genre:
#Entity(name = "genre")
#Table(name = "genre")
public class Genre {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="id")
private Long id;
#Column(name = "name")
private String name;
#OneToOne(fetch = FetchType.LAZY, mappedBy = "genre", cascade = CascadeType.ALL, orphanRemoval = true)
private Book book;
The book is related to the author (many books - one author) and genre (one genre - one book)
Book:
#Entity
#Table(name = "book")
public class Book {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "name")
private String name;
#ManyToOne(fetch = FetchType.LAZY,cascade = CascadeType.ALL)
#JoinColumn(name = "author_id")
private Author author;
#OneToOne(fetch = FetchType.LAZY,cascade = CascadeType.ALL, orphanRemoval = true)
#JoinColumn(name = "genre_id")
private Genre genre;
#Column(name = "publisher")
private String publisher;
#Column(name = "year")
private int year;
#Column(name = "city")
private String city;
.. and when I run my spring boot application I get the error.
Caused by: org.hibernate.HibernateException: More than one row with the given identifier was found: 3, for class: com.app.entity.Book
Where did I go wrong?

How to handle duplicate data of child table that belongs to 1 of 2 parent table has many-to-many relationship

I have 2 tables called Product and Category with many-to-many relationship. And Product has a one-to-many relationship with Images table. I created a table Product_Category to link 2 table Product and Category together. My problem is when 1 product belongs to 1 category, it's just fine with 4 images of that product. But if 1 product belongs to 2 categories, i get 8 images instead of 4
This is image of problem
As you can see is's supposed to be _1 _2 _3 _4 instead _1 _1 _2 _2 ...
This is my entities class
ProductEntity
#Entity
#Table(name = "product")
public class ProductEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#Column(name = "name")
private String name;
#Column(name = "description")
private String description;
#Column(name = "price")
private double price;
#Column(name = "material")
private String material;
#ManyToOne
#JoinColumn(name="careId")
private ProductCareEntity productCare;
#OneToMany(mappedBy = "product", fetch = FetchType.EAGER)
private List<ImageEntity> images;
#OneToMany(mappedBy = "product", fetch = FetchType.EAGER)
private List<ProductCategoryEntity> productCategoryEntities;
#OneToMany(mappedBy = "product", fetch = FetchType.EAGER)
private List<OrderDetailEntity> orderDetailEntityList;
#OneToMany(mappedBy = "product", fetch = FetchType.EAGER,cascade=CascadeType.ALL)
private List<ProductSizeQuantityEntity> productSizeQuantities;
CategoryEntity
#Entity
#Table(name = "category")
public class CategoryEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#Column(name = "name")
private String name;
#OneToMany(mappedBy = "category", fetch = FetchType.EAGER)
private List<ProductCategoryEntity> productCategories;
ProductCategoryEntity
#Entity
#Table(name = "product_category")
public class ProductCategoryEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#ManyToOne
#JoinColumn(name = "categoryId")
private CategoryEntity category;
#ManyToOne
#JoinColumn(name = "productId")
private ProductEntity product;
How can i solve this problem?
I don't think you need ProductCategoryEntity at all. All you need to do is to make a List of Category type in product and List of Product type in Category. like this:
#Entity
#Table(name = "product")
public class ProductEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#Column(name = "name")
private String name;
#Column(name = "description")
private String description;
#Column(name = "price")
private double price;
#Column(name = "material")
private String material;
#ManyToOne
#JoinColumn(name="careId")
private ProductCareEntity productCare;
#OneToMany(mappedBy = "product", fetch = FetchType.EAGER)
private List<ImageEntity> images;
#ManyToMany(cascade = { CascadeType.ALL })
#JoinTable(name = "ProductCategory",
joinColumns = { #JoinColumn(name = "category_id") },
inverseJoinColumns = { #JoinColumn(name = "product_id"))
private List<Category> categories;
#OneToMany(mappedBy = "product", fetch = FetchType.EAGER)
private List<OrderDetailEntity> orderDetailEntityList;
#OneToMany(mappedBy = "product", fetch =
FetchType.EAGER,cascade=CascadeType.ALL)
private List<ProductSizeQuantityEntity> productSizeQuantities;
and
#Entity
#Table(name = "category")
public class CategoryEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#Column(name = "name")
private String name;
#ManyToMany(mappedBy = "projects")
#JoinTable(name = "ProductCategory")
private List<Product> products;

Cannot add restriction to oneToMany mapping in Hibernate

I have 2 entities linked together using oneToMany mapping. In the Dao layer when i apply restrictions on the linked entity it fetches all the results. It seems that the restrictions are not working on the linked entity. I want to apply restrictions on both entities.
DAO
Criteria criteria = createEntityCriteria()
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
.add(Restrictions.eq("status" , "APPROVED"))
.addOrder(Order.desc("approvedAt"))
.createAlias("purchaseDemandDetails" , "pds")
.add(Restrictions.ge("pds.approvedQuantity" , 1));
return criteria.list();
PurchaseDemand.java
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#ManyToOne
#JoinColumn(name = "created_by", referencedColumnName = "id")
private User createdBy;
#Column(name = "created_at")
private Date createdAt;
#ManyToOne
#JoinColumn(name = "updated_by" , referencedColumnName = "id")
private User updatedBy;
#Column(name = "updated_at")
private Date updatedAt;
#ManyToOne
#JoinColumn(name = "approved_by" , referencedColumnName = "id")
private User approvedBy;
#Column(name = "approved_at")
private Date approvedAt;
#Column(name = "status")
private String status;
#OneToMany(mappedBy = "purchaseDemand", cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
private Set<PurchaseDemandDetail> purchaseDemandDetails = new HashSet<PurchaseDemandDetail>();
public void setPurchaseDemandDetails(Set<PurchaseDemandDetail> purchaseDemandDetails)
{
this.purchaseDemandDetails.addAll(purchaseDemandDetails);
}
public Set<PurchaseDemandDetail> getPurchaseDemandDetails()
{
return this.purchaseDemandDetails;
}
PurchaseDemandDetail.java
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#ManyToOne
#JoinColumn(name = "purchase_demand_id",referencedColumnName = "id")
#JsonIgnore
private PurchaseDemand purchaseDemand;
#ManyToOne
#JoinColumn(name = "product_id",referencedColumnName = "id")
private Product product;
#Column(name = "requested_quantity", nullable = false)
#NotNull(message = "Quantity is required")
private int requestedQuantity;
#Column(name = "approved_quantity", nullable = false)
#NotNull(message = "Quantity is required")
private int approvedQuantity;
}

Hibernate ORA-02292: integrity constraint (ROOT.SYS_C007062) violated - child record found

I following have hibernate entities:
#Entity
#Table(name = "News")
public final class News implements Serializable, IEntity {
private static final long serialVersionUID = 3773281197317274020L;
#Id
#SequenceGenerator(name = "NEWS_SEQ_GEN", sequenceName = "NEWS_SEQ")
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "NEWS_SEQ_GEN")
#Column(name = "NEWS_ID", precision = 0)
private Long newsId; // Primary key
#Column(name = "TITLE")
private String title;
#Column(name = "SHORT_TEXT")
private String shortText;
#Column(name = "FULL_TEXT")
private String fullText;
#Temporal(TemporalType.DATE)
#Column(name = "CREATION_DATE")
private Date creationDate;
#Temporal(TemporalType.DATE)
#Column(name = "MODIFICATION_DATE")
private Date modificationDate;
#OneToMany(cascade = CascadeType.REMOVE, orphanRemoval = true)
#JoinColumn(name = "NEWS_ID", updatable = false, referencedColumnName = "NEWS_ID")
#OrderBy("creationDate ASC")
private List<Comment> commentsList;
#ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinTable(name = "NEWS_TAG", joinColumns = { #JoinColumn(name = "NEWS_ID") }, inverseJoinColumns = { #JoinColumn(name = "TAG_ID") })
private Set<Tag> tagSet;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinTable(name = "NEWS_AUTHOR", joinColumns = { #JoinColumn(name = "NEWS_ID") }, inverseJoinColumns = { #JoinColumn(name = "AUTHOR_ID") })
private Set<Author> author;
And the second:
#SequenceGenerator(name = "COMMENTS_SEQ", sequenceName = "COMMENTS_SEQ")
#Entity
#Table(name = "Comments")
public class Comment implements Serializable, IEntity {
private static final long serialVersionUID = 3431305873409011465L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "COMMENTS_SEQ")
#Column(name = "COMMENT_ID", precision = 0)
private Long commentId; // Primary key
#Column(name = "NEWS_ID")
private Long newsId;
#NotEmpty
#NotNull
#Column(name = "COMMENT_TEXT")
private String commentText;
#Temporal(TemporalType.DATE)
#Column(name = "CREATION_DATE")
private Date creationDate;
When I'm trying to remove entity News, I get the exception ORA-02292: integrity constraint (ROOT.SYS_C007062) violated - child record found. So, if I remove the property "updatable = false" it tries to set nullable fields into property Comment. What is my mistake? Please, help.
Thanks.
Because your news records have a one to one or one to many relation with comments. You most likely did not specifcy a CACASDE ON DELETE clause while defining your table. in order to delete entity NEWS you have to make sure that all of its related comments records are deleted or are referencing another NEWS record.
basicaly the definition of the ORA 02292 exception.

Categories

Resources