Hibernate doesn't create one entity - java

I'm trying to create tables using hibernate but all the entities seems to be mapped as tables except for one. Even the manytomany containing this table's id is created but not the table itself.
Service.java
#Entity
#Table(name="service")
public class Service {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="title")
private String title;
#Column(name="description")
private String desc;
#Column(name="price")
private int price;
#Column(name="limit")
private int limit;
#Column(name="status")
private boolean available;
#Column(name="tags")
private String tags;
#ManyToOne
#JoinColumn(name="provider_id")
private User provider;
#ManyToOne(cascade = {CascadeType.DETACH,CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH})
#JoinColumn(name="category_id")
private Category category;
#ManyToMany(cascade = {CascadeType.DETACH,CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH})
#JoinTable(
name="service_clients",
joinColumns = #JoinColumn(name="service_id"),
inverseJoinColumns = #JoinColumn(name="client_id")
)
private List<User> clients;
//GETTERS,SETTERS
}
I can update the post if you need more information.
PS: I don't get any error in my logs.

"limit" is reserved keyword for some databases. You can change the name of the property or you can create the table manualy.

On top of Buraks awnser, you could try encoding the column name:
#Column(name="\"limit\"")
Unfortunatly Hibernate isn't doing this by itself, for many vendors and keywords (like "order", "user") it's needed.

Related

How to make a query which searches by myClass_id and by either teacher_id or by replacingTeachers' ids (to contain an id) with Spring JPA?

I have an entity Subjects:
public class Subject {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
#OneToOne
private Teacher teacher;
#ManyToMany
private Set<Teacher> replacingTeachers;
#JsonIgnore
#ManyToOne
#JoinColumn(name = "class_id")
private Class myClass;
}
And I want to make a query which searches by myClass_id and by either teacher_id or by replacingTeachers' ids (to contain an id). How to do this with Spring JPA? I tried this:
Optional<Subject> findByTeacherIdAndMyClassIdOrReplacingTeachersContains(final Long teacherId, final Long classId);

type missmatch, java spring & hibernate, cannot convert data for mySQL database from Object to String

Im cant fix bug in my app, error is becouse Im trying to add element Object type in database table in row which requie String type,what shall I do? :S
[problem is in getProductSave, something with Stickers.
#RequestMapping(value = "product-save")
public String getProductSave(#ModelAttribute Product product) {
Category category = categoryService.getCategoryById(product.getCategory().getId());
List<Sticker> stickers = new ArrayList<Sticker>();
for(Sticker sticker : product.getStickers()) {
Sticker tempSticker = stickerService.getStickerById(sticker.getId());
stickers.add(tempSticker);
}
product.setCategory(category);
productDAO.saveProduct(product);
product.setStickers(stickers);
return "redirect: product-list";
}
Class Sticker has columns from table stickers in database
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column
private int id;
#Column
private String title;
#Column
private String color;
Class Product has field
#ManyToMany(cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.REFRESH })
#JoinTable(name = "products_stickers", joinColumns = #JoinColumn(name="products_id"), inverseJoinColumns = #JoinColumn(name="sticker_id"))
private List<Sticker> stickers;
Why you are not adding the stickers to the product before saving it? This could be the problem. Please check relation between your intermediate table "product_stickers" and "product" table. Ultimately you wanted to add stickers to your product but missing it.
Is there any possibility that problem could be in Sticker class, in constructor or some annotation?
#Entity
#Table(name = "stickers")
public class Sticker {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column
private int id;
#Column
private String title;
#Column
private String color;
public Sticker() {
}
public Sticker(String title, String color) {
this.title=title;
this.color=color;
}

Why spring data jpa-java.lang.IllegalStateException: Multiple representations of the same entity in OneToMany relationship?

I am working a very small application which contains 3 entity classes.
1.Category.
2.Products.
3.User
Relationships:-
a. OneToMany between User and Products.
b. OneToMany and ManyToOne between category and products i.e. a category can have multiple products and multiple products can belong to same category.
Entity Classes are shown below:-
User Entity:-
#Entity
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String username;
private String lastname;
private String email;
private String password;
#OneToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE},
fetch = FetchType.EAGER)
private Set<Products> products;
//getter and setter
}
Products Entity:-
#Entity
public class Products {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String productname;
private String cost;
#ManyToOne(cascade = {CascadeType.MERGE,CascadeType.PERSIST},
fetch = FetchType.LAZY)
private Category category;
//getter and setters
}
Category Entity:-
#Entity
public class Category {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
#OneToMany(mappedBy = "category",
cascade = {CascadeType.PERSIST, CascadeType.MERGE},
fetch = FetchType.EAGER)
private List<Products> products;
//getter and setters
}
Method to merge User with products in data base:-
#GetMapping("/cart")
public String Cart(Model model){
model.addAttribute("cart",productsSet);
System.out.println(productsSet);//At this stage in console I am able to see products added in set
User user = userRepository.findById(1);//hard coded for now.
user.setProducts(productsSet);
userService.saveUserProducts(user);//saveUserProducts() method in shown below.
productsSet.clear();
return "mycart";
}
saveUserProducts() :-
#Override
#Transactional
public void saveUserProducts(User user) {
entityManager.merge(user);
}
But when I am running the program I see the following exception in console:-
java.lang.IllegalStateException: Multiple representations of the same entity [com.demo.shopping.com.Entity.Products#2] are being merged. Detached: [Products{id=2, productname='p2', cost='200'}]; Detached: [Products{id=2, productname='p2', cost='200'}]
I found an article on stack-overflow but it was not fit in my situation.(java.lang.IllegalStateException: Multiple representations of the same entity with #ManyToMany 3 entities).Except this I don't get any relevant thing.
Please help me to let me know how to deal with this situation. Hope someone will help.
Thanks in advance.
Remove CascadeType.MERGE user class because in my program I am not adding new products also except this I am creating relation between existing user and products.

How to create a 1:n relationship with hibernate?

I am using hibernate to represent a database with the three major Entities User, Project and Comment. User and Project inherit from Base class. The Project also holds an unlimited amount of comments.
In the POJO i tried to represent the collection of comments associated by a project by with a List<Comment>.
My major problem is, when i i go and take a project which holds a number of comment references within the list java will throw an IllegalArgumentException saying, that it cant access the id field of comment, as it only gets an ArrayList.
Caused by: java.lang.IllegalArgumentException: Can not set int field com.project.objects.Comment.id to java.util.ArrayList
My classes are as followed - without Constructor/Setter/Getter as these are plain simple:
#MappedSuperclass
public abstract class Base {
#Id
#Column
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column
private String name;
#Column
private String longDesc;
#Column
private String briefDesc;
#Column
#ElementCollection(targetClass=String.class)
private List<String> goals;
#Column
private String picture;
#Column
private int cType;
#Entity(name = "Project")
#Table(name = "project")
public class Project extends Base {
#Column
private String start;
#Column
private String end;
#Column
private String manager;
#ElementCollection(targetClass=Comment.class)
#ManyToOne(targetEntity = Comment.class, fetch = FetchType.EAGER)
#JoinColumn(name = "comment_id")
private List<Comment> comments;
#Entity(name = "Comment")
#Table(name = "comment")
public class Comment {
#Id
#Column(name="comment_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column
private String comment;
#Column
private int rating;
#Column
private int pcuser;
#Column
private int cType;
Your 1:N association is wrong, as it is actually a N:1 right now. The correct would be:
Entity(name = "Project")
#Table(name = "project")
public class Project extends Base {
#Column
private String start;
#Column
private String end;
#Column
private String manager;
#OneToMany(mappedBy = "project", fetch = FetchType.EAGER)
private List<Comment> comments;
And in your Comment class:
#Entity(name = "Comment")
#Table(name = "comment")
public class Comment {
#Id
#Column(name="comment_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column
private String comment;
#Column
private int rating;
#Column
private int pcuser;
#Column
private int cType;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "id_project", nullable = false)
private Project project;
// THIS is the required and obrigatory mapping that you forgot.
// It's the foreing key itself
Disclaimer
I've never actually used Hibernate with inheritance before (usually, it's desnecessarily complex and also inefficient for a relational database) but check `https://www.baeldung.com/hibernate-inheritance` and `https://marcin-chwedczuk.github.io/mapping-inheritance-in-hibernate` for more information.
You're using a #ManyToOne annotation for comments but it should be #OneToMany.
In order to use #OneToMany you would have to have a column called something like project_id in the comment table, which you would reference from the #OneToMany field. Do you have that?
If not, how are you linking comments to projects in your database?
By the way, it's really easy to create poorly-performing systems with Hibernate, because it tends to obscure the cost of hitting the database. You've said that there can be any number of comments associated with a project. Do you really want to load them all every time the code loads a project? Let's say you just want a list of projects, for example to populate a selection list. Simply loading that list will also load every comment in the system, even though you don't actually need them.
Comment is an entity and should not be used with the #ElementCollection inside the Project entity.
Your relationship is a project to many comments. #OneToMany

Hibernate Relationship Mapping Issue

Hibernate novice here, running into issues trying to properly map the relationships between my Hibernate Entity classes.
I have a Ticket Entity and a User Entity. A user has many tickets, but a ticket only belongs to one unique user. What i've done is mapped the User - Tickets as a #OneToMany relationship and the Tickets - User as a #ManyToOne relationship. However, I am not getting any tickets returned.
The Query Hibernate is running is:
Hibernate: select tickets0_.user_user_id as user1_1_3_, tickets0_.tickets_ticket_id as tickets2_3_, ticketenti1_.ticket_id as ticket1_0_0_, ticketenti1_.assigned_to_user_id as assigned7_0_0_, ticketenti1_.belongs_to_user_id as belongs8_0_0_, ticketenti1_.date_created as date2_0_0_, ticketenti1_.description as descript3_0_0_, ticketenti1_.status_id as status4_0_0_, ticketenti1_.title as title0_0_, ticketenti1_.urgency_id as urgency6_0_0_, userentity2_.user_id as user1_1_1_, userentity2_.email as email1_1_, userentity2_.firstname as firstname1_1_, userentity2_.lastname as lastname1_1_, userentity2_.password as password1_1_, userentity2_.role_id as role6_1_1_, userentity2_.username as username1_1_, userentity2_.verified as verified1_1_, userentity3_.user_id as user1_1_2_, userentity3_.email as email1_2_, userentity3_.firstname as firstname1_2_, userentity3_.lastname as lastname1_2_, userentity3_.password as password1_2_, userentity3_.role_id as role6_1_2_, userentity3_.username as username1_2_, userentity3_.verified as verified1_2_ from user_ticket tickets0_ inner join ticket ticketenti1_ on tickets0_.tickets_ticket_id=ticketenti1_.ticket_id left outer join user userentity2_ on ticketenti1_.assigned_to_user_id=userentity2_.user_id left outer join user userentity3_ on ticketenti1_.belongs_to_user_id=userentity3_.user_id where tickets0_.user_user_id=?
The Entity Classes are:
TicketEntity.java
#Entity
#Table(name="ticket")
public class TicketEntity {
#Id
#Column(name="ticket_id")
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#Column(name="title")
private String title;
#Column(name="description")
private String description;
#Column(name="date_created")
#Temporal( TemporalType.TIMESTAMP )
private Date date_created;
#Column(name="status_id")
private int status_id;
//private TicketStatus status;
#Column(name="urgency_id")
private int urgency_id;
#ManyToOne
#JoinColumn(insertable=false, updatable=false)
private UserEntity belongs_to;
#ManyToOne
#JoinColumn(insertable=false, updatable=false)
private UserEntity assigned_to;
UserEntity.java
#Entity
#Table(name="user")
public class UserEntity {
#Id
#Column(name="user_id")
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#Column(name="firstname")
private String firstname;
#Column(name="lastname")
private String lastname;
#Column(name="username")
private String username;
#Column(name="email")
private String email;
#Column(name="password")
private String password;
#Transient
private String confirmpassword;
#Column(name="verified")
private boolean verified;
#Column(name="role_id")
private int role_id;
#OneToMany(fetch = FetchType.EAGER)
private List<TicketEntity> tickets;
Any help is appreciated,
Thanks!
In UserEntity.java, you need to add "mappedBy" for List<TicketEntity> tickets, like this:
#OneToMany(fetch = FetchType.EAGER, mappedBy="belongs_to")//why you have two UserEntity in TicketEntity.java?
private List<TicketEntity> tickets;
In TicketEntity.java, add (name = "user_id") to #JoinColumn for UserEntity belongs_to, like this:
#ManyToOne
#JoinColumn(name = "user_id", insertable=false, updatable=false)
private UserEntity belongs_to;
Same for private UserEntity assigned_to. You may need add another list for it in UserEntity.java if you want to query it too.

Categories