I'm new with Hibernate and Criteria Query.
How can I implement it with Hibernate Criteria Object?
SELECT stateslocalization.StateId, stateslocalization.localization AS name
FROM processstate
Join states ON states.id = processstate.StateId
JOIN stateslocalization ON stateslocalization.StateId = states.id
WHERE processstate.ProcessId = 38 and processstate.StateId = states.id AND stateslocalization.StateId = states.id
Entities:
Process:
#Entity
#Table(name = "processes")
public class Process {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
#ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.PERSIST)
#JoinTable(
name = "processstate",
joinColumns = {#JoinColumn(name = "ProcessId")},
inverseJoinColumns = {#JoinColumn(name = "StateId")}
)
private Set<State> states;
//getters and setters.....
}
State:
#Entity
#Table(name = "states")
public class State {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private int id;
private String name;
#ManyToMany(mappedBy = "states", cascade = CascadeType.PERSIST, fetch = FetchType.EAGER)
private Set<Process> processes;
#OneToOne(mappedBy = "state")
private StateLocalization stateLocalization;
//getters and setters.....
}
StateLocalization:
#Entity
#Table(name = "stateslocalization")
public class StateLocalization {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "StateId", referencedColumnName = "id")
private State state;
private String localization;
//getters and setters.....
}
I did it with native query but I don't know how I can implement it to Hibernate Criteria, because I don't have entity processstate (it's only table).
Related
I created two simple entities for trying out the java persistence manytomany mapping. But whatever I try, the jointable won't be populated with a mapping and remains empty.
UserClass:
#Entity
#Table(name = "users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
#ManyToMany(targetEntity = Order.class ,fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinTable(
name = "users_orders",
joinColumns = #JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(name = "order_id", referencedColumnName = "id")
)
#JsonIgnoreProperties(value = "orderUsers")
private Set<Order> userOrders = new HashSet<>();
}
OrderClass:
#Entity
#Table(name = "orders")
public class Order {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
#ManyToMany(mappedBy = "userOrders", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JsonIgnoreProperties(value = "userOrders")
private Set<User> orderUsers = new HashSet<>();
}
I added Getter/Setter/Constructor via Lombok.
Create and save an user. Create an order, add the user and save it. But still the jointable remains empty.
Any ideas?
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;
I am facing a hibernate problem in updainting the join table in one to many mapping with hibernate. Below are my two entity class and join table entity class.
ArticleCategoryMap.java
#Entity
#Table(name = "ARTICLECATEGORYMAP")
public class ArticleCategoryMap {
private static final long serialVersionUID = -5653708523600543988L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
#Column ( name = "id")
Long id;
#ManyToOne(targetEntity = Article.class, fetch = FetchType.EAGER, optional = true, cascade = CascadeType.PERSIST)
#JoinColumn(name = "ARTICLE_ID", nullable = true, insertable = true, updatable = true)
private Article article;
#ManyToOne(targetEntity = Category.class, fetch = FetchType.EAGER, optional = true, cascade = CascadeType.PERSIST)
#JoinColumn(name = "CATEGORY_ID", nullable = true, insertable = true, updatable = true)
private Category category;
//setter and getter
}
Article.java
#Entity
#Table(name = "ARTICLE")
public class Article {
private long id;
private String title;
private String description;
private String keywords;
private String content;
#Id
#GeneratedValue
#Column(name = "ARTICLE_ID")
public long getId() {
return id;
}
//setter and getter
}
Category.java
#Entity
#Table(name = "CATEGORY")
public class Category {
private long id;
private String name;
#OneToMany(cascade = CascadeType.ALL, fetch=FetchType.EAGER)
#JoinTable(
name = "ARTICLECATEGORYMAP",
joinColumns = #JoinColumn(name = "CATEGORY_ID"),
inverseJoinColumns = #JoinColumn(name = "ARTICLE_ID")
)
#CollectionId(
columns = #Column(name="id"),
type=#Type(type="long"),
generator = "sequence"
)
private Collection<Article> articles;
#Id
#GeneratedValue
#Column(name = "CATEGORY_ID")
public long getId() {
return id;
}
#OneToMany(cascade = CascadeType.ALL, fetch=FetchType.EAGER)
#JoinTable(
name = "ARTICLECATEGORYMAP",
joinColumns = #JoinColumn(name = "CATEGORY_ID"),
inverseJoinColumns = #JoinColumn(name = "ARTICLE_ID")
)
#CollectionId(
columns = #Column(name="id"),
type=#Type(type="long"),
generator = "sequence"
)
// setter an getter
}
Now suppose first time I have 2 elements in article table which is mapping to one entry of the category table. so the join table will look something like
Now due to some reason, I want to update the entry where the article entry will map to a new category ID. So the final DB should look like
So My problem Is how can I update this join table.
If you want one to many relationship (1 category have many articles and 1 article to 1 category) you dont need a join table.
The entity classes should look like that:
Category Entity:
Contains a Set of articles:
#Entity
#Table(name = "CATEGORY")
public class Category {
private long id;
private String name;
#OneToMany(mappedBy="category")
private Set<Article> articles;
......
}
Article Entity:
#Entity
#Table(name = "ARTICLE")
public class Article {
#ManyToOne
#JoinColumn(name="id", nullable=false)
private Category category;
private long id;
private String title;
private String description;
private String keywords;
private String content;
.......
}
For more details take a look at hibernate-one-to-many. Hope this helps.
Also move annotation from methods to fields. This:
private long id;
#Id
#GeneratedValue
#Column(name = "CATEGORY_ID")
public long getId() {
return id;
}
Should be:
#Id
#GeneratedValue
#Column(name = "CATEGORY_ID")
private long id;
public long getId() {
return id;
}
Many to many relationship:
At your database you have 3 tables:
CATEGORY
ARTICLE
ARTICLECATEGORYMAP (join table)
For many to many relationship entities would be:
Category Entity:
#Entity
#Table(name = "CATEGORY")
public class Category {
#Id
#GeneratedValue
#Column(name = "CATEGORY_ID")
private long id;
private String name;
#ManyToMany(cascade = { CascadeType.ALL })
#JoinTable(
name = "ARTICLECATEGORYMAP",
joinColumns = { #JoinColumn(name = "CATEGORY_ID") },
inverseJoinColumns = { #JoinColumn(name = "ARTICLE_ID") }
)
Set<Article > articles = new HashSet<>();
.....
}
Article Entity:
#Entity
#Table(name = "ARTICLE")
public class Article {
#Id
#GeneratedValue
#Column(name = "ARTICLE_ID")
private long id;
private String title;
private String description;
private String keywords;
private String content;
#ManyToMany(mappedBy = "articles")
private Set<Category> categories = new HashSet<>();
.......
}
For more info take a look at many-to-many ralationship
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 :)
I am trying to add Staff object which has staff information, roles and subjects. The code below saves only Staff data not its associated collections data.
I have tried to debug it but didn't understand the issue. The staff object has roles and subjects before saving into database but they are not getting saved in the DB. Surprisingly, the similar code is working while saving Course table data; however, Course does also have collection of Subject class.
It seems to me that Subjects have Course object which may be creating problem, I am not sure why. Please advise how to fix it.
The complete project is available on GitHub(https://github.com/ravinain/practice/tree/master/Java/Spring/SchoolProject)
Staff.java
#Entity
#Table
public class Staff extends Person {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private double salary;
#OneToMany(mappedBy = "staff", fetch=FetchType.EAGER)
#Cascade({ CascadeType.ALL})
private Set<Role> roles = new HashSet<Role>();
#ManyToMany(mappedBy = "staffs", fetch=FetchType.EAGER)
#Cascade({CascadeType.ALL})
private Set<Subject> subjects = new HashSet<Subject>();
Role.java
#Entity
#Table
public class Role {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#NotNull
private int id;
private String name;
#ManyToOne
#JoinTable(name = "role_staff", joinColumns = #JoinColumn(name = "role_id", referencedColumnName = "id"), inverseJoinColumns = #JoinColumn(name = "staff_id", referencedColumnName = "id"))
#JsonIgnore
private Staff staff;
Subject.java
#Entity
#Table
public class Subject implements Comparable<Subject>{
#Id
#Column
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String description;
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(name = "subject_staff", joinColumns = #JoinColumn(name = "subject_id", referencedColumnName = "id"), inverseJoinColumns = #JoinColumn(name = "staff_id", referencedColumnName = "id"))
#JsonIgnore
private Set<Staff> staffs = new HashSet<Staff>();
#ManyToMany(mappedBy = "subjects", fetch = FetchType.EAGER)
#Cascade({ CascadeType.DELETE, CascadeType.SAVE_UPDATE })
#JsonIgnore
private Set<Course> courses = new HashSet<Course>();
#ManyToMany(mappedBy = "subjects", fetch = FetchType.EAGER)
#Cascade({ CascadeType.DELETE, CascadeType.SAVE_UPDATE })
#JsonIgnore
private Set<Student> students = new HashSet<Student>();
DAO Code:
public Staff addStaff(Staff staff) {
Session session = sessionFactory.getCurrentSession();
session.save(staff);
return staff;
}
POST Request:
{"name":"New Test","age":22,"gender":"Female","salary":12000,"roles":[{"id":3,"name":"Teacher"}],"subjects":[{"id":1,"description":"Math"},{"id":2,"description":"English"}]}