How to delete entity with many to many relation? JPA - java

i don't know how to delete this. Only one thing i noticed that the OrderToProvider will be deleted after deleting all entities in a table named "OrderToProvider-Goods".
Code:
OrderToProvider
public class OrderToProvider {
#GeneratedValue (strategy = GenerationType.IDENTITY)
#Id
private int id;
#Basic
private int price;
#Basic
private Date dataOfOrder;
#Basic
private Date dateOfProcessing;
#ManyToOne(optional = false)
private main.data.Provider provider;
#ManyToMany (cascade = CascadeType.ALL)
private Collection<Good> goods;
Good
public class Good implements Comparable<Good>{
#GeneratedValue (strategy = GenerationType.IDENTITY)
#Id
private int id;
#Basic
private String name;
#Basic
private String model;
#Basic
private int price;
#Basic
private String type;
#Basic
private int amount;
#ManyToOne(optional = false)
private Provider provider;

To delete the OrderToProvider from your DB, first you retrieve it from your DB, then setGoods(null) and setProvider(null), then delete it afterwards. This should work with conditions that you have a properly implemented setters.
I hope this is helpful.

Related

Spring JPA Join two tables without third class

Is there a way to join two tables in Spring JPA without using association class.
I have two MySQL DB tables :
employees(id,.....,department_id)
departments(id,.....)
And I'm searching for a way to join these tables using only my employee and department classes.
Currently, I managed to join two tables but with the third association class.
My current implementation is:
Employee class:
#Entity(name = "Employee")
#Table(name = "employees")
#JsonInclude(Include.NON_NULL)
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#JsonIgnore
#Column(name = "employee_id")
private Long employeeId;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "phone_number")
private String phoneNumber;
#Column(name = "hire_date")
private Double hireDate;
#Column(name = "job_id")
private Long jobId;
#Column(name = "salary")
private Double salary;
#Column(name = "commission_pct")
private Double commissionPct;
#Column(name = "employees")
private Long employees;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "id", insertable = false, updatable = false)
#Fetch(FetchMode.JOIN)
private Department department;
}
Department class:
#Entity(name = "Department")
#Table(name = "departments")
#JsonInclude(Include.NON_NULL)
public class Department implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "department_name")
private String departmentName;
#Column(name = "department_id")
private long departmentId;
#Column(name = "manager_id")
private Double managerId;
#Column(name = "location_id")
private Double locationId;
}
Association class:
public class DeptEmpDto {
private long departmentId;
private String departmentName;
private Double managerId;
private Double locationId;
private long employeeId;
private String firstName;
private String lastName;
private String phoneNumber;
private Double hireDate;
private Long jobId;
private Double salary;
private Double commissionPct;
}
Repository:
public interface IEmployeeRepository extends JpaRepository<Employee, Long> {
#Query("SELECT new com.concretepage.entity.DeptEmpDto(d.departmentId,d.departmentName,d.managerId,d.locationId,e.employeeId,e.firstName,e.lastName,e.phoneNumber,e.hireDate,e.jobId,e.salary,e.commissionPct FROM Employee e INNER JOIN Department d ON d.id = e.jobId")
List<DeptEmpDto> fetchEmpDeptDataInnerJoin();
You can use it in Employee class
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(
name = "DeptEmp",
joinColumns = #JoinColumn(name = "emp_id",referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(name = "dep_id",referencedColumnName = "id")
)
private Set<Departments> departments = new HashSet<>();
Look at this about JPA
Logically an employee can't work in two departements so your relationship is correct
But you can do that with a #ManyToMany annotation.

How to check if same object exists before inserting another one into database in hibernate?

Team.java
#Entity
#Table(name = "team")
public class Team {
#Id
#Column(name = "team_id")
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#NotNull
#NotEmpty
#Size(max = 30)
private String leadName;
#NotNull
#NotEmpty
#Email(message = "email must be valid")
private String leadEmail;
#NotNull
#NotEmpty
#Size(max = 30)
private String teamName;
#ManyToOne
#JoinColumn(name = "city_id")
private City city;
#OneToMany( cascade = CascadeType.ALL)
#JoinColumn(name = "team_id")
private List<Idea> ideas;
#NotNull
#NotEmpty
private String organization;
...
}
This is JAVA Hibernate class (Spring Boot) and class TeamRepository exists. Before insertion I want to check if the same entry exists in JPA repository (TeamRepository). How it can be done with hibernate annotations? Is it possible at all?

How create a constraint with Hibernate?

How can I create a constraint with Hibernate? I'm mapping two classes, "Team" and "Match", but I want that a match JUST can happens if the teams are from the same League. The way that I'm doing right now I can create a match with teams from differents leagues (which isn't interesting in this case).
Is there some annotation that "wraps" my teams, home and away, just being from one league? Or I have to do this in my system?
Thanks.
#Table(name = "match")
#Entity
public class Match implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#ManyToOne
#JoinColumn(name = "id_league")
private League league;
#ManyToOne
#JoinColumn(name = "id_home", referencedColumnName="id")
private Team home;
#ManyToOne
#JoinColumn(name = "id_away", referencedColumnName="id")
private Team away;
#Column
private Integer goalsHome;
#Column
private Integer goalsAway;
#Temporal(value = TemporalType.DATE)
private Date matchDate;
and
#Table(name="team")
#Entity
public class Team implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#Column(length = 55)
private String name;
#ManyToOne
#JoinColumn(name = "id_league")
private League league;
#OneToMany
private List<Match> match;

using #JsonIdentityInfo or #JsonManagedReference, #JsonBackReference causes my property in a class to be ignored when parsing into it

i have been having hibernate circular dependency issues this are the class below:
#Entity
#JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="id")
public class Task extends DefaultEntity{
#ManyToOne
#JoinColumn(name = "cloth_model_id")
//#JsonIgnore
private ClothModel clothModel;
private String details;
private boolean completed;
#ManyToOne
#JoinColumn(name = "employee_id")
private Employee employee;
}
#Entity
#JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="id")
public class ClothModel extends DefaultEntity {
private ClothingType clothingType;
private int quantity;
private double amount;
#Transient
private String modelStructure;
private String savedUrl;
#Transient
//#JsonManagedReference
private List<Task> tasks = new ArrayList<>();
}
#MappedSuperclass
public class DefaultEntity implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(columnDefinition = "serial")
private long id;
#Column(name = "Time",columnDefinition= "TIMESTAMP WITH TIME ZONE")
#Temporal(TemporalType.TIMESTAMP)
private Date dateCreated;
i removed the getters and setters, so the code wouldn't be too much
When i apply the #JsonIdentityInfo or #JsonManagedReference, #JsonBackReference to both the ClothModel.class and Task.class, i notice that in the clothModel property in the Task.class will be ignored when i try writing a JSON to it, it acts like i am using a #Jsonignore annotation. Why is this and why isn't there a proper 100% working fix for Hibernate circular recursion.

JPA mapping sports game with two #OneToOne relations

I have the following hierarchy for a football match.
#Entity
public class Match {
#Id
#GeneratedValue
protected Integer id;
#Column(name = "home_team_id")
private int homeTeamId;
#Column(name = "away_team_id")
private int awayTeamId;
private TeamScore homeScore;
private TeamScore awayScore;
}
#Entity(name = "team_score")
public class TeamScore {
#EmbeddedId
protected TeamScoreId id;
private List<Goal> goals;
}
#Embeddable
public class TeamScoreId {
#Column(name = "match_id")
private Integer matchId;
#Column(name = "team_id")
private int teamId;
}
And I have a problem with mapping homeScore and awayScore in Match with TeamScore entity.
The first concern is whether two #OneToOne relations should be here. And how should they be configured?
The second one relates to matchId in TeamScoreId. How this mapping can be performed?

Categories

Resources