How can I use post method data in back end to save many to many relationship data with #JsonIgnore annotation.My joining table is not updating - json

How can I use the data send through post method, and save those data in a many to many relationship? I used #JsonIgnore annotation to stop the recursion.
I have implemented two entities.One is Employee and the other is Skills.In the Employee entity I used #JsonIgnore annotation to avoid the reccursion. But when I inserted the values Employee table got updated but the joining tabled is not updating.
This is my Employee entity class
#Entity
#Table(name = "Employee")
public class Employee implements Serializable{
private static final long serialVersionUID = -3009157732242241606L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long emp_id;
#Column(name = "emp_fname")
private String emp_fname;
#Column(name = "emp_lname")
private String emp_lname;
#Column(name = "emp_email")
private String emp_email;
#Column(name = "emp_dob")
private Date emp_dob;
#ManyToMany(cascade = CascadeType.MERGE)
#JoinTable(name = "emp_skills",
joinColumns = #JoinColumn(name = "emp_id", referencedColumnName = "emp_id"),
inverseJoinColumns = #JoinColumn(name = "s_id",referencedColumnName = "s_id"))
#JsonIgnore
private Set<Skills> skills;
}
This is my Skills class
#Entity
#Table(name = "Skills")
public class Skills implements Serializable {
private static final long serialVersionUID = -3009157732242241606L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long s_id;
#Column(name = "s_name")
private String s_name;
#ManyToMany(mappedBy = "skills")
private Set<Employee> employees;
And this is my controller class method to save data
#RequestMapping("/save")
#PostMapping("/save")
#CrossOrigin
public void createEmployee(#RequestBody Employee employee, BindingResult bindingResult){
Employee emp = new Employee(employee.getEmp_fname(),employee.getEmp_lname(),employee.getEmp_email(),employee.getEmp_dob());
emp.setSkills(employee.getSkills());
empRepository.save(emp);
//empRepository.save(new Employee(employee.getEmp_fname(),employee.getEmp_lname(),employee.getEmp_email(),employee.getEmp_dob()));
}
I want to update both Employee and emp_skills (the joining table) when the save method is triggered.

Related

Indexing for key which belongs to Primary key of other table

I have a two table as table as
#Entity
#Table(name = "product", uniqueConstraints=#UniqueConstraint(columnNames={"product_idn"}))
public class Product implements Serializable {
private static final long serialVersionUID = 21409635044L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String product_idn;
}
another table as
#Entity
#Table(name = "storage")
public class Storage implements Serializable {
private static final long serialVersionUID = -67165579239L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "product_id", nullable = false)
#JsonBackReference
private Product product;
}
Now I am fetching record from storage table. Should create a index (Non-Unique)on product_id of storage table? I have to fetch storages count per on product/ featching storages based on product.
Just add #Index annoation like below and it should work fine.
#Entity
#Table(name = "storage", indexes = #Index(columnList = "product_id",name = "storage_productId_index"))
public class Storage implements Serializable

Failed to convert from type [java.lang.Object[]] to type [#org.springframework.data.jpa.repository.Query

I have spring boot project using JPA/Hibernate, MySQL. I have three dao classes that have a many to many relationship.
The Poko classes look like this
Product
#Entity
#Table(name = "product")
public class Product {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", unique = true, nullable = false, columnDefinition = "integer")
private Integer id;
#Column(name = "name")
private String name;
#Column(name = "price")
private Double price;
#ManyToMany(cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
#JoinTable(
name = "product_extra",
joinColumns = #JoinColumn(name="product_id"),
inverseJoinColumns = #JoinColumn(name="extra_id")
)
private List<Extra> extras = new ArrayList<>();
//constructor getters and setters
}
ProductExtra
#Entity
#Table(name = "product_extra")
public class ProductExtra {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", unique = true, nullable = false, columnDefinition = "integer")
private Integer id;
#Column(name = "product_id")
private Integer productId;
#Column(name = "extra_id")
private Integer extraId;
//constructor getters and setter
}
Extra
#Entity
#Table(name = "extra")
public class Extra {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", unique = true, nullable = false, columnDefinition = "integer")
private Integer id;
#Column(name = "name")
private String name;
#Column(name = "price")
private Double price;
#ManyToMany(mappedBy = "extras")
private List<Product> products = new ArrayList<>();
//constructor getters and setters
}
The Extra repository with the query
public interface ExtraRepository extends JpaRepository<Extra, Integer> {
#Query("SELECT e.id, e.name, e.price FROM Extra e INNER JOIN ProductExtra pe ON e.id = pe.extraId WHERE pe.productId = ?1")
List<Extra> findExtraById(Integer productId);
}
The mapping in my controller
#GetMapping("/product/{productId}")
public List<Extra>getExtraById(#PathVariable("productId") final Integer productId){
return extraRepository.findExtraById(productId);
}
I am trying to make a many to many query to select The extras in each product, i am however getting this error Failed to convert from type [java.lang.Object[]] to type [#org.springframework.data.jpa.repository.Query the error message surprisingly also contains the results i want. Not sure what am doing wrong
Remove the SELECT clause:
#Query("FROM Extra join e.productExtra WHERE pe.productId = ?1")
Also keep in mind, that you not write an SQL Query, You work on Object, so for join you use the mapped property

path expected for join JPA Hibernate MySQL

I'm using composite PK in my app with 2 tables and one joining table.
I wrote this query for function:
#Repository
public interface HospitalDoctorDao extends JpaRepository<HospitalDoctor, Integer>{
#Query("select hd from HospitalDoctor hd join hospital on hd.hospital_id=hospital.id join doctor on hd.doctor_id = doctor.id where hospital_id = ?1 and doctor_id = ?1")
HospitalDoctor findByHospitalIdAndDoctorId(int hospital_id, int doctor_id);
}
and I am getting error Path expected for file! In MySQL everything is working. How Hibernate works in this case? How I should write this query? Here is my #Entity of join table:
#Entity
#Table(name = "hospital_doctor")
public class HospitalDoctor {
#Embeddable
static class HosdocPK implements Serializable {
private int hospitalId;
private int doctorId;
}
#EmbeddedId
#JsonBackReference
public HosdocPK hosdocPK;
#JsonManagedReference
#MapsId("DoctorId")
#ManyToOne(optional = false)
#JoinColumn(name = "doctorId", referencedColumnName = "id")
private Doctor doctor;
#JsonManagedReference
#MapsId("HospitalId")
#ManyToOne(optional = false)
#JoinColumn(name = "hospitalId", referencedColumnName = "id")
private Hospital hospital;
#Column(name = "Id")
private int id;
#Temporal(TemporalType.DATE)
private Date contract_start_date;
#Temporal(TemporalType.DATE)
private Date contract_end_date;
private String position;
private String supervisor;
private boolean part_time;
Getters and setters
}
Your query is incorrect.
Try:
select hd from HospitalDoctor hd where hd.hospital.id = ?1 and hd.doctor.id = ?2

Named query join select

I need to get GroupEntity objects which have assigned specific role in RoleGroupEntity Table.
I try to do this like that:
#NamedQuery(name = "GroupEntity.getGIDs", query = "SELECT o FROM RoleGroupEntity u JOIN FETCH u.GroupId o WHERE u.role_id LIKE :role_id")
but I got:
org.hibernate.QueryException: could not resolve property: role_id of: RoleGroupEntity
Entites sample:
#Entity
#Table(name = "group")
public class GroupEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "gid_number")
private Long gid_number;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "GroupId")
private List<RoleGroupEntity> GroupId;
RoleGroupEntity has Composite Key:
#Entity
#Table(name = "role_group")
public class RoleGroupEntity implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
private RoleGroupCompositeKey posRGKey;
#MapsId("role_id")
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "role_id")
private RoleEntity roles;
#MapsId("group_id")
#ManyToOne
#JoinColumn(name = "group_id")
private GroupEntity GroupId;
Do you know how to make my select query to work?
You can not use the joincolumn you have to use: u.roles.id LIKE :role_id")
#NamedQuery(name = "GroupEntity.getGIDs", query = "SELECT o FROM RoleGroupEntity u JOIN FETCH u.GroupId o WHERE u.roles.id LIKE :role_id")

Hibernate - Join query

I have two classes:
#Entity
public class Tick {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#ManyToOne(optional = false)
#JoinColumn(name = "elitesystem_id", referencedColumnName = "id")
private EliteSystem eliteSystem;
private Date createDate;
#ManyToOne(optional = true)
#JoinColumn(name = "commander_id", referencedColumnName = "id")
private Commander commander;
private String address;
and
#Entity
public class Note {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#ManyToOne(optional = true)
#JoinColumn(name = "tick_id", referencedColumnName = "id")
private Tick tick;
private String text;
private Date createDate;
I want to select all ticks and get notes if there are any:
Query query = session.createQuery("select t, n from Note n right join n.tick t where t.commander.name = '123'");
List<Object[]> list = query.list();
This returns only Tick objects. What is the correct approach to get the Note information as well in 1 single query?
I could put a reference to a Note into the Tick class, but this doesnt sound right, as there are only a few notes, so the column in the Tick table would mostly be empty.
Create a New class for example:
public class TickNote {
private Tick tick;
private Note note;
public TickNote(Tick tick,Note note){
this.tick=tick;
this.note=note;
Then your query is:
Query query = session.createQuery("select NEW TickNote(t, n) from Note n right join n.tick t where t.commander.name = '123'");
List<TickNote> list = query.list();