Entity did not have primary key - java

#Entity
public class Product {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String productName;
private int year;
private Double price;
private String url;
public Product() { }
public Product(String productName, int year, Double price, String url) {
this.productName = productName;
this.year = year;
this.price = price;
this.url = url;
}
}
I have a problem with my Springboot. Even when I add #Id, the log tells me that Product didn't have any Id.

Make sure you add your entity class in repository interface
eg:
public interface Repository extends JpaRepository<Product,Long>{
}
and in entity
change private int year
to
private Integer year

Thanks, everyone help me with this. I had already fixed this. The problem was IJ auto complete wrong import. In this case I have to use javax.persistence but IJ auto complete it to a org.springframework.data.id

Related

Joining two entities in spring-boot

I have a category table that have its own unique id and name,
I have a product table that have its own unique id, name, price and categoryId.
Category.java
#Entity
public class Category {
#Id
#GeneratedValue
private long id;
private String name;
#OneToMany(fetch=FetchType.LAZY, mappedBy = "category")
private Set<Product> products;
//getters and setters
}
Product.java
#Entity
public class Product {
#Id
private long productId;
private String name;
private double price;
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="categoryId")
private Category category;
public Product() {
}
public Product(long productId, String name, double price) {
super();
this.productId = productId;
this.name = name;
this.price = price;
}
public long getProductId() {
return productId;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
}
When I try to create a new product by post method, I should be able to read or write it's categoryId, but I can't. What am I doing it wrong?
You should not be able to write its categoryId, but you need a getter and a setter for Product.category. To change the category of a product, you would do product.setCategory(newCategory). If you want to READ the category ID of a product, you also need to add a getter for Category.id; you would then do: product.getCategory().getId().

How to resolve IdClass Property not found issue when creating composite primary key using JPA

I am having issues creating composite primary key
I am getting org.hibernate.AnnotationException: Property of #IdClass not found this exception.
My serializable implementing class and model class is given below:
public class MakeCompositeKey implements Serializable {
private String codeName;
private int year;
public MakeCompositeKey() {
}
public MakeCompositeKey(String codeName, int year) {
this.codeName = codeName;
this.year = year;
}
#Override
public int hashCode() {
return super.hashCode();
}
#Override
public boolean equals(Object obj) {
return super.equals(obj);
}
}
and
#Entity
#IdClass(MakeCompositeKey.class)
public class Averages {
#Id
#Column(name = "code_name")
private String CodeName;
#Id
private int year;
#Column(name = "weighted_average_shs_out")
private double Weighted_Average_Shs_Out;
#Column(name = "weighted_average_shs_dil")
private double Weighted_Average_Shs_Out_Dil;
#Column(name = "average_receivables")
private double Average_Receivables;
#Column(name = "average_payables")
private double Average_Payables;
#Column(name = "average_inventory")
private double Average_Inventory;
//getters and setters
}
I don't understand what's going wrong. Please, help me resolve this issue.
Thank you!
You have a typo here which probably breaks everything up.
public class Averages {
#Id
#Column(name = "code_name")
private String CodeName; // <----this should be codeName instead of CodeName
//...class implementation
}
MakeCompositeKey should be annotated with #Embeddable
Look at this: How to map a composite key with JPA and Hibernate?

How to multiply two attributes in same model and get it into another attribute

I want to add two numbers in the same entity. Is this correct or how to do it.
#Data
#Entity
public class Product {
#Id
private Integer productId;
private String productName;
private Integer noOfUnits;
private Double cartonPrice;
#Transient
private Double unitPrice=cartonPrice-noOfUnits;
}
No this is not the right way to handle it! You should do all these in service classes based on in which controller this unitPrice field need to be calculated and save it in the database.
#Data
#Entity
public class Product {
#Id
#Column(name = "product_id")
private Integer productId;
#Column(name = "product_name")
private String productName;
#Column(name = "no_of_units")
private Double noOfUnits;
#Column(name = "carton_price")
private Double cartonPrice;
#Formula("carton_price + no_of_units")
private Double unitPrice;
}
Using this can do this calculation.

How to use relationships between tables in jpa

I am learning jpa on my own by using online tutorials & trying out possible examples but now i am little confused about how to use relationships between tables. I have 3 classes having #Entity annotation which means jpa will create table based on these classes.i have id field in Student, Course, Booking classes and they will be primary key for respective tables.
The help i need is, in Booking class there is sid & cid fields and i want them to be referenced such as sid(Student.java)=sid(Booking.java) & cid(Course.java)=cid(Booking.java) and the scenario is each student can one or multiple bookings of one or multiple course. can someone tell me how & where should i use #OnetoOne, #OnetoMany, #ManytoMany, #ManytoOne in my code.
Student.java
package com.testapp;
import java.util.List;
import javax.persistence.*;
#Entity
public class Student{
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int sid;
private String name;
private int salary;
//Getters and Setters....
..
public Student() {
super();
}
public Student(int sid, String name, float salary) {
super();
this.sid = sid;
this.name = name;
this.salary = salary;
}
public Student(String name, float salary) {
super();
this.name = name;
this.salary = salary;
}
}
Course.java
package com.testapp;
import java.util.List;
import javax.persistence.*;
#Entity
public class Course {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int cid;
private String cname;
private int price;
//Getters and Setters....
..
public Course() {
super();
}
public Course(int cid, String cname, int price) {
super();
this.cid = cid;
this.cname = cname;
this.price = price;
}
public Course(String cname, int price) {
super();
this.cname = cname;
this.price = price;
}
}
Booking.java
package com.testapp;
import java.util.Set;
import javax.persistence.*;
#Entity
public class Booking {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int bid;
private String date;
private int sid;
private int cid;
//Getters and Setters....
..
public Booking() {
super();
}
public Booking(int bid, String date, int sid, int cid) {
super();
this.bid = bid;
this.date= date;
this.sid = sid;
this.cid = cid;
}
public Booking(String date, int sid, int cid) {
super();
this.date = date;
this.sid = sid;
this.cid = cid;
}
}
Thank You..
Just define object in you class, as an example student involving many Cource , then you can define property on student class like below
public class Student{
private List<Cource> cources;
}
then orm detects the relationship, but also you have annotations like #OneToMant #ManyToMany in JPA
The best way to define this relationship in your case will be Student and Course will have OneToMany relation with Booking. And Booking will have ManyToOne relation with Student and Course
Student.java
#OneToMany(mappedBy = "student", cascade = CascadeType.ALL, orphanRemoval = true)
public Set< Booking > getBookings() {
return bookings;
}
Course.java
#OneToMany(mappedBy = "course", cascade = CascadeType.ALL, orphanRemoval = true)
public Set<Booking> getBookings() {
return bookings;
}
Booking.java
#Entity
public class Booking {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int bid;
private String date;
private Student student;
private Course course;
#Id
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "sid")
public Student getStudent() {
return student;
}
#Id
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "cid")
public Course getCourse() {
return course;
}
//Getters and Setters....
..
public Booking() {
super();
}
}
You should not use primary keys of other entities in JPA!
Use #ManyToOne and Student as well as Cource instead of sid and cid.

How to filter an entity in hibernate with hibernate filters

I need to filter an entity in a list of objects, for example:
public class Student {
private int id;
private List<Course> courses;
}
public class Course {
private int id;
private String name;
private float note;
private Classroom classroom;
}
public class Classroom {
private int id;
private String classroom;
}
How to obtain a student object with a list of courses with only notes greater than 70, and located in classroom 23 (for example)?
Is there a way to use the name of the entity instead of the one of the column of the database?
Or how do I associate with sql the alias generated by hibernate for the entity?
I attach a link from the hibernate filters:
https://docs.jboss.org/hibernate/orm/5.0/manual/en-US/html/ch19.html
Ok it think this should do the trick:
Entities
public class Student {
private int id;
#OneToMany(mappedBy = "student")
#Filter(name = "defaultCoursesFilter")
private List<Course> courses;
}
#FilterDef(name = "defaultCoursesFilter"
, defaultCondition=" notes > 70")
public class Course {
private int id;
private String name;
private float note;
#ManyToOne
#Filter(name = "defaultClassromFilter")
private Classroom classroom;
}
#FilterDef(name = "defaultClassromFilter"
, defaultCondition=" id = 23")
public class Classroom {
private int id;
private String classroom;
}
Before query
Session session = sessionFactory.getCurrentSession();
session.enableFilter("defaultCoursesFilter");
session.enableFilter("defaultClassromFilter");
// query

Categories