I have a many to many relation between Permission and Role classes.
And there is a role_permission table to keep relation between role and permission
CREATE TABLE public.role_permissions
(
role_id bigint NOT NULL,
permission_id bigint NOT NULL,
CONSTRAINT role_permissions_pkey PRIMARY KEY (role_id, permission_id),
CONSTRAINT fkh0v7u4w7mttcu81o8wegayr8e FOREIGN KEY (permission_id)
REFERENCES public.permission (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT fklodb7xh4a2xjv39gc3lsop95n FOREIGN KEY (role_id)
REFERENCES public.role (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
WITH (
OIDS=FALSE
);
ALTER TABLE public.role_permissions
OWNER TO postgres;
When I want to delete Permission it throws following error
org.postgresql.util.PSQLException: ERROR: update or delete on table "permission" violates foreign key constraint "fkh0v7u4w7mttcu81o8wegayr8e" on table "role_permissions"
Detail: Key (id)=(6) is still referenced from table "role_permissions".
Here is my class implementations
package com.nova.stats.client.backend.auth.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.PreRemove;
import javax.persistence.Transient;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.HashSet;
import java.util.Set;
#Data
#AllArgsConstructor
#NoArgsConstructor
#Getter
#Setter
#EqualsAndHashCode(exclude = {"users", "roles"})
#ToString(exclude = {"users", "roles"})
#Entity
public class Permission implements GrantedAuthority {
#Transient
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotNull
#Size(min = 2, max=100, message = "Permission name must be between {min} and {max} characters long")
#Column(unique = true)
private String name;
#NotNull
#Size(min = 10, max=250, message = "Permission description must be between {min} and {max} characters long")
#Column
private String description;
#Getter(onMethod = #__(#Override))
#NotNull
#Size(min = 6, max=100, message = "Permission authority must be between {min} and {max} characters long")
#Column(unique = true)
private String authority;
#Getter(onMethod = #__(#JsonIgnore))
#ManyToMany(mappedBy = "permissions")
private Set<Role> roles;
#Getter(onMethod = #__(#JsonIgnore))
#ManyToMany(mappedBy = "permissions")
private Set<User> users;
public Permission(String name, String description, String authority) {
this.name = name;
this.description = description;
this.authority = authority;
}
}
package com.nova.stats.client.backend.auth.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.*;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.HashSet;
import java.util.Set;
#Data
#AllArgsConstructor
#NoArgsConstructor
#EqualsAndHashCode(exclude = {"users", "permissions"})
#ToString(exclude = {"users", "permissions"})
#Getter
#Setter
#Entity
public class Role implements GrantedAuthority {
#Transient
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotNull
#Size(min = 2, max=100, message = "Role name must be between {min} and {max} characters long")
#Column(unique = true)
private String name;
#NotNull
#Size(min = 10, max=250, message = "Role description must be between {min} and {max} characters long")
#Column
private String description;
#Getter(onMethod = #__(#Override))
#NotNull
#Size(min = 6, max=100, message = "Role authority must be between {min} and {max} characters long")
#Column(unique = true)
private String authority;
#Getter(onMethod = #__(#JsonIgnore))
#ManyToMany(mappedBy = "roles")
private Set<User> users = new HashSet<>(0);
#Getter(onMethod = #__(#JsonIgnore))
#Setter(onMethod = #__(#JsonProperty("permissions")))
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(name = "role_permissions", joinColumns = #JoinColumn(name = "role_id", referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(name = "permission_id", referencedColumnName = "id"))
private Set<Permission> permissions;
public Role(String name, String description, String authority, Set<Permission> permissions) {
this(name, description, authority);
this.permissions = permissions;
}
public Role(String name, String description, String authority) {
this.name = name;
this.description = description;
this.authority = authority;
}
}
Here is what I need; when I want to delete any permission then foreign key must be deleted in role_permission table but related role can't be delete. I mean when delete permission, just delete permission on table permission and relation on table role_permission
What should I do for that ?
The problem is that when try to delete a permission, it is still referenced on user. You need to delete the user first or remove it's permission before removing from permission table.
To delete in cascade you can try this:
#ManyToMany(cascade = CascadeType.ALL, mappedBy = "permissions")
private Set<User> users;
I added "#OnDelete(action = OnDeleteAction.CASCADE)" annotation on User and Permission in Role class
And also added Role and User in Permission class
And now, It works as I want
Here is an Example
package com.asd.asd;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.*;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.Set;
#Data
#AllArgsConstructor
#NoArgsConstructor
#Getter
#Setter
#EqualsAndHashCode(exclude = {"users", "roles"})
#ToString(exclude = {"users", "roles"})
#Entity
public class Permission implements GrantedAuthority {
#Transient
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotNull
#Size(min = 2, max=100, message = "Permission name must be between {min} and {max} characters long")
#Column(unique = true)
private String name;
#NotNull
#Size(min = 10, max=250, message = "Permission description must be between {min} and {max} characters long")
#Column
private String description;
#Getter(onMethod = #__(#Override))
#NotNull
#Size(min = 6, max=100, message = "Permission authority must be between {min} and {max} characters long")
#Column(unique = true)
private String authority;
#Getter(onMethod = #__(#JsonIgnore))
#ManyToMany(mappedBy = "permissions")
#OnDelete(action = OnDeleteAction.CASCADE)
private Set<Role> roles;
#Getter(onMethod = #__(#JsonIgnore))
#ManyToMany(mappedBy = "permissions")
#OnDelete(action = OnDeleteAction.CASCADE)
private Set<User> users;
public Permission(String name, String description, String authority) {
this.name = name;
this.description = description;
this.authority = authority;
}
}
Related
I have this POJO class:
package com.weather.weather.entity;
import jakarta.persistence.*;import lombok.Data;
import lombok.NoArgsConstructor;import org.hibernate.annotations.Proxy;import org.springframework.transaction.annotation.Transactional;
import java.util.List;import java.util.Set;
#Entity#Table(name = "users")#Data#NoArgsConstructor
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "username")
private String username;
#Column(name = "password")
private String password;
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(name = "collaborator",
joinColumns = #JoinColumn(name = "user_id"),
inverseJoinColumns = #JoinColumn(name = "role_id")
)
private Set<Role> roles;
}
Also Role class:
package com.weather.weather.entity;
import jakarta.persistence.*;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.Proxy;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Set;
#Entity
#Table(name = "roles")
#Data
#NoArgsConstructor
public class Role {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
// #OneToMany(mappedBy = "role")
// private List<User> users;
#ManyToMany(mappedBy = "roles")
private Set<User> users;
}
But always getRoles() are null.
I have tried changing data to #OneToOne, #ManyToOne, #OneToMany.But its always null.At some point, when i was doing #ManyToOne way, i have got this exception:
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.weather.weather.entity.Role.users: could not initialize proxy - no Session
And i found to ways to fix that. I`ve tried putting fetch property, #Proxy(lazy=false), and many many others. Nothing helped
Your annotation #ManyToMany imported from jakarta.persistence.
You should import from javax.persistence.* and you can remove proxy annotation and Lazy fetchType
I have two Entity classes User and UserProfile. The User table has a primary key for the User ID which is a long data type. This User ID is supposed to be the primary key in user_profile as well. User also has email as a column, which I want to be linked to the user_profile also. The issue I am having is that for some reason, a column named id is being inserted into my table when I already have the primary key user_id set in the user_profile table. Does anyone know what I am doing wrong?
User:
import javax.persistence.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
#Entity
#Table( name = "users",
uniqueConstraints = {
#UniqueConstraint(columnNames = "username"),
})
#SecondaryTable(name = "user_profile")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "username")
#NotBlank
#Size(max = 20)
private String username;
#Column(name = "email", table = "user_profile")
#NotBlank
#Size(max = 50)
#Email
private String email;
#NotBlank
#Size(max = 120)
private String password;
#ManyToMany(fetch = FetchType.LAZY)
#JoinTable( name = "user_roles",
joinColumns = #JoinColumn(name = "user_id"),
inverseJoinColumns = #JoinColumn(name = "role_id"))
private Set<Role> roles = new HashSet<>();
//getter methods
//setter methods
}
User_Profile:
import javax.persistence.*;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
#Entity
#Table(name = "user_profile")
public class UserProfile {
#Id
private Long id;
#OneToOne(fetch = FetchType.LAZY)
#MapsId
private User user;
// #JoinColumn(name = "email")
// #OneToOne(fetch = FetchType.LAZY)
// private User email;
#Column(name = "profile_img") //S3 image Link
private String profile_img;
#Column(name = "profile_banner") //S3 image Link
private String profile_banner;
//getter methods
//setter methods
}
User table:
User_Profile table:
You can avoid the usage of SecondaryTable and use just OneToOne and mappedBy and #PrimaryKeyJoinColumn :
#Entity
#Table(#Table( name = "users",
uniqueConstraints = { #UniqueConstraint(columnNames = "username") }))
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "user_id")
Long userId;
#OneToOne(mappedBy = "user")
UserProfile userProfile;
// Other fields
// getters and setters
}
#Entity
#Table(name = "user_profile")
public class UserProfile {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "user_id")
Long userId;
#OneToOne
#PrimaryKeyJoinColumn(name = "user_id")
User user;
// other fields
// getters and setters
}
more details here https://www.baeldung.com/jpa-mapping-single-entity-to-multiple-tables
I was not aware of #MapsId, learned something new.
A simple search and found following
can someone please explain me #MapsId in hibernate?
I tried with dummy code. It looks like we are mixing #SecondaryTable and #MapsId together.
The duplicate column is from SecondaryTable annotation.
i don't have full context of requirement here, mostly https://www.baeldung.com/jpa-mapping-single-entity-to-multiple-tables should solve the need. #Oussama ZAGHDOUD also mentioned this in his response.
In summary, use #MapsId when you want to keep two separate entity class for 2 tables and #SecondaryTable combines 2 tables into one entity class. Both acts same way, primary key of one table works as primary key and foreign key of 2nd table.
With #MapsId only I was getting following sql
Hibernate: create table user_profile (profile_banner varchar(255), profile_img varchar(255), user_user_id bigint not null, primary key (user_user_id))
Hibernate: create table users (user_id bigint generated by default as identity, email varchar(50), password varchar(120), username varchar(20), primary key (user_id))
Hibernate: alter table users add constraint UKr43af9ap4edm43mmtq01oddj6 unique (username)
Hibernate: alter table user_profile add constraint FKqkgvrni6161p23yj2lbp9xxlk foreign key (user_user_id) references users
With #SecondaryTable
Hibernate: create table user_profile (email varchar(50), profile_banner varchar(255), profile_img varchar(255), user_id bigint not null, primary key (user_id))
Hibernate: create table users (user_id bigint generated by default as identity, password varchar(120), username varchar(20), primary key (user_id))
Hibernate: alter table users add constraint UKr43af9ap4edm43mmtq01oddj6 unique (username)
Hibernate: alter table user_profile add constraint FKuganfwvnbll4kn2a3jeyxtyi foreign key (user_id) references users
Entity class will look like below
package com.example.demo.entity;
import javax.persistence.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
#Entity
#Table( name = "users",
uniqueConstraints = {
#UniqueConstraint(columnNames = "username")
})
#SecondaryTable(name = "user_profile", pkJoinColumns = #PrimaryKeyJoinColumn(name = "user_id"))
public class User implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="user_id")
private Long userId;
#Column(name = "username")
#NotBlank
#Size(max = 20)
private String username;
#Column(name = "email", table = "user_profile")
#NotBlank
#Size(max = 50)
#Email
private String email;
#Column(name = "profile_img", table = "user_profile") //S3 image Link
private String profile_img;
#Column(name = "profile_banner", table = "user_profile") //S3 image Link
private String profile_banner;
#NotBlank
#Size(max = 120)
private String password;
//getter methods
//setter methods
}
These are my model classes and when I add the json data you see below, the data is successfully placed in my database tables.
{
"RequestIdentifier": "01asdasdk12k1j21kj21k",
"Status": {
"Name": "Successful",
"Code": 0,
"Message": "null"
},
"Response": {
"Name": "PersonName",
"Surname": "PersonSurname",
"Patronymic": "PersonPatronymic",
"BirthDate": "PersonBirthdate",
"Allowance": [], //it's normal for it to be empty
"Pension": [ //Here is the part where I can't get the data. It returns empty just like Allowance.
{
"Type": {
"Label": "LabelName",
"Id": 0,
"Description": "description"
},
"StartDate": "05.12.2021",
"EndDate": "null",
"Group": null,
"Amount": 5154540
}
]
}
}
package com.example.sifirdanapi.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.*;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.format.annotation.DateTimeFormat;
import javax.persistence.*;
import java.util.Date;
import java.util.List;
import java.util.Set;
#Entity
#Setter
#Getter
#AllArgsConstructor
#NoArgsConstructor
#ToString
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler", "allowance", "pension"})
public class PensionInfoResult {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "id_Sequence")
#SequenceGenerator(name = "id_Sequence", sequenceName = "ID_SEQ")
private Long id;
private String RequestIdentifier;
private String name;
private String surname;
private String patronymic;
private String birthDate;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
#LazyCollection(LazyCollectionOption.FALSE)
#Fetch(value = FetchMode.SUBSELECT)
private Set<PensionInfoAllowance> allowance;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
#LazyCollection(LazyCollectionOption.FALSE)
#Fetch(value = FetchMode.SUBSELECT)
private Set<PensionInfoPension> pension;
//--------------------------------------------
private String pin;
private String branchCode;
private String username;
#Column(name = "CREATED_DATE")
#Temporal(TemporalType.TIMESTAMP)
#CreatedDate
#DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS")
private Date createdDate;
#Lob
#Column
private String request;
private String statusCode;
private String statusMessage;
private String statusName;
#Lob
#Column
private String response;
#PrePersist
public void persist() {
setCreatedDate(new Date());
}
}
package com.example.sifirdanapi.model;
import lombok.*;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.format.annotation.DateTimeFormat;
import javax.persistence.*;
import java.math.BigDecimal;
import java.util.Date;
#Entity
#Setter
#Getter
#AllArgsConstructor
#NoArgsConstructor
#ToString
public class PensionInfoPension {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "id_Sequence")
#SequenceGenerator(name = "id_Sequence", sequenceName = "ID_SEQ")
private Long id;
private String startDate;
private String endDate;
private BigDecimal amount;
private Integer typeId;
private String typeDesc;
private String typeLabel;
private Integer groupId;
private String groupdesc;
#ManyToOne(fetch = FetchType.EAGER)
private PensionInfoResult pensionInfoResult;
#Column(name = "CREATED_DATE")
#Temporal(TemporalType.TIMESTAMP)
#CreatedDate
#DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS")
private Date createdDate;
#PrePersist
public void persist() {
setCreatedDate(new Date());
}
}
package com.example.sifirdanapi.model;
import lombok.*;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.format.annotation.DateTimeFormat;
import javax.persistence.*;
import java.math.BigDecimal;
import java.util.Date;
#Entity
#Setter
#Getter
#AllArgsConstructor
#NoArgsConstructor
#ToString
public class PensionInfoAllowance {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "id_Sequence")
#SequenceGenerator(name = "id_Sequence", sequenceName = "ID_SEQ")
private Long id;
private String beginDate;
private String endDate;
private BigDecimal amount;
private Integer groupId;
private String groupDesc;
private Integer typeId;
private String typeDesc;
#ManyToOne(fetch = FetchType.EAGER)
private PensionInfoResult pensionInfoResult;
#Column(name = "CREATED_DATE")
#Temporal(TemporalType.TIMESTAMP)
#CreatedDate
#DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS")
private Date createdDate;
public Date getCreatedDate() {
return createdDate;
}
}
So I don't have any problems in the relationship part. I just couldn't figure out how to write the query I have shown below in spring boot data jpa. When I run the following query in sql, it successfully returns the data I want, but I cannot export it to java.
SELECT
*
FROM
pension_info_result AS pir
JOIN
pension_info_pension AS pip ON pir.id = pip.pension_info_result_id
JOIN
pension_info_allowance as pia ON pir.id = pia.pension_info_result_id
where pir.id=?
#Query(value =
"""
select pif from PensionInfoResult pif
join PensionInfoPension pip on if.id=pip.pensionInfoResult.id
join PensionInfoAllowance pia on pif.id=pia.pensionInfoResult.id
where pif.id=?1
"""
, nativeQuery = true)
PensionInfoResult findById(Long id);
When I run the program it gives me the following error.
java.sql.SQLSyntaxErrorException: Table 'api.pensioninforesult' doesn't exist
How can I write the query I showed above more accurately?
I have a users table which contains the user details. i also have a authorities table which has the role of a user. The user and authorities table has one to many mapping. When i try to save the details using Jpa the foreign key column is blank no data is inserted in that field. i have a form in which i am specifying the role of the user along with other details.
package com.example.StarsProject.Model;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
#Entity
#Table
#Getter
#Setter
public class Authorities {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String role;
#ManyToOne(cascade = CascadeType.PERSIST,fetch=FetchType.EAGER)
#JoinColumn(name = "users_id", referencedColumnName = "id")
private Users users;
public Authorities(String role){
this.role = role;
}
}
package com.example.StarsProject.Model;
import com.example.StarsProject.DTO.UserDTO;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
#Entity
#Table
#Getter
#Setter
public class Users {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column(name = "first_name")
private String firstname;
#Column(name = "last_name")
private String lastname;
#Column(unique = true)
private String email;
private String password;
#OneToMany(fetch = FetchType.EAGER,targetEntity = Authorities.class,mappedBy = "users", cascade = CascadeType.PERSIST)
private Set<Authorities> authorities;
public Users(UserDTO userDTO) {
this.email = userDTO.getEmail();
this.firstname = userDTO.getFirstname();
this.lastname = userDTO.getLastname();
this.password = userDTO.getPassword();
// Authorities authorities = new Authorities();
// authorities.setRole(userDTO.getRole());
// Set<Authorities> set = new HashSet<>();
// set.add(authorities);
this.authorities = new HashSet<Authorities>(Arrays.asList(new Authorities(userDTO.getRole())));
}
}
package com.example.StarsProject.Service;
import com.example.StarsProject.DTO.UserDTO;
import com.example.StarsProject.Model.Users;
import com.example.StarsProject.Repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
public class UserDetailsServiceImpl implements UserDetailsServiceInterface{
#Autowired
UserRepository userRepository;
#Override
public void storeUserDetails(UserDTO userDTO) {
Users users = new Users(userDTO);
userRepository.save(users);
}
}
When i try to save the user details it doesn't insert any value in the foreign key column. Can someone tell me what i am doing wrong.
You need to setusers field in Authorities manually. Hibernate won't fill it for you.
I've a Java REST API with JPA. Whenever I create an entity, I also want to create another entity with a forgein key. Or maybe someone can advise me otherwise, I would really appreciate it and learn from it =)
When i successfully create a company it will make a file entity in the database as well, so that works fine. but,
Whenever I execute a findAll method in the JPA repository it will give me a loop of the one company that i've created.
like this:
If you need any more information, please let me know!
Company.class
package nl.hulpvriend.dehulpvriend.company;
import javax.validation.constraints.NotNull;
import lombok.*;
import nl.hulpvriend.dehulpvriend.file.File;
import javax.persistence.*;
import javax.validation.constraints.Size;
#Entity
#Data
#NoArgsConstructor
#AllArgsConstructor
#Setter
#Getter
public class Company {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#NotNull
private String email;
#Column(unique = true)
#NotNull(message = "The company name cannot be empty")
#Size(max = 30, message = "Company name cannot be longer than 30 characters")
private String name;
#NotNull(message = "Company must contain a service type")
#Enumerated(EnumType.STRING)
private ServiceType serviceType;
private double stars;
private Integer pricePerHour;
private String description;
private String kvk;
#OneToOne(mappedBy="company", cascade = CascadeType.ALL)
private File file;
}
File.class
package nl.hulpvriend.dehulpvriend.file;
import lombok.*;
import nl.hulpvriend.dehulpvriend.company.Company;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
#AllArgsConstructor
#Getter
#Setter
#NoArgsConstructor
#Entity
#Data
public class File {
#Id
private Integer id;
private String fileId;
#OneToOne(fetch = FetchType.EAGER)
#MapsId
private Company company;
#NotNull(message = "Must contain a data")
#Lob
private byte[] data;
private String downloadUrl;
private String fileName;
private String fileType;
public File(String fileName, String fileType, byte[] data) {
this.fileName = fileName;
this.fileType = fileType;
this.data = data;
}
}
Add JsonIgnore to one of the references to break the loop:
For example in the File class:
#JsonIgnore
#OneToOne(fetch = FetchType.EAGER)
#MapsId
private Company company;