Spring Jpa - Records deleted and re-inserted upon addition/deletion in join table - spring-boot

I have 3 entities user, role and user_roles.
User and Role entity have a one-to-many relationship with the UserRoles entity which is a join table. I have added user_roles as a entity because we plan to have additional properties in future as part of the join table.
User Entity
#Entity
#Table(name = "users")
public class User
{
#Id
#Column(name = "user_id")
#GeneratedValue(generator = RandomIdGenerator.GENERATOR_NAME)
#GenericGenerator(name = RandomIdGenerator.GENERATOR_NAME, strategy = "com.cs.util.RandomIdGenerator")
private Long id;
#Column(name = "email", nullable = false)
private String email;
#Column(name = "first_name", nullable = false)
private String firstName;
#Column(name = "last_name", nullable = false)
private String lastName;
#OneToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER,mappedBy = "user", orphanRemoval = true)
private List<UserRole> userRoles = new ArrayList<UserRole> ();
#JsonSerialize(using = ToStringSerializer.class)
public Long getId ()
{
return id;
}
public void setId (Long id)
{
this.id = id;
}
public String getEmail()
{
return email;
}
public void setEmail (String email)
{
this.email = email;
}
public String getFirstName()
{
return firstName;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public String getLastName()
{
return lastName;
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
#Transient
public Set<Role> getRoles()
{
Set<Role> roles = new HashSet<Role> ();
for (UserRole userRole : this.userRoles)
{
roles.add (userRole.getRole ());
}
return roles;
}
#JsonIgnore
public List<UserRole> getUserRoles()
{
return userRoles;
}
}
Role Entity
#Entity
#Table(name="roles")
public class Role {
#Id
#Column(name = "role_id")
#GeneratedValue(generator = RandomIdGenerator.GENERATOR_NAME)
#GenericGenerator(name = RandomIdGenerator.GENERATOR_NAME, strategy = "com.cs.util.RandomIdGenerator")
private Long id;
#Column(name="name", nullable = false)
private String name;
#Column(name="description", nullable = true)
private String description;
#Column(name = "suspend_flag")
private int suspendFlag;
#ManyToMany(fetch=FetchType.EAGER)
#JoinTable(name = "roles_permission",
joinColumns = #JoinColumn(name = "role_id"),
inverseJoinColumns = #JoinColumn(name = "permission_id"))
private Set<Permission> permissions= new HashSet<>();
#OneToMany(mappedBy = "role")
private List<UserRole> userRoles = new ArrayList<UserRole>();
#JsonSerialize(using=ToStringSerializer.class)
public Long getId ()
{
return id;
}
public void setId (Long id)
{
this.id = id;
}
public String getName ()
{
return name;
}
public void setName (String name)
{
this.name = name;
}
public String getDescription ()
{
return description;
}
public void setDescription (String description)
{
this.description = description;
}
public Set<Permission> getPermissions ()
{
return permissions;
}
public int getSuspendFlag ()
{
return suspendFlag;
}
public void setSuspendFlag (int suspendFlag)
{
this.suspendFlag = suspendFlag;
}
}
UserRole Entity
#Entity
#Table(name = "user_roles")
public class UserRole
{
public UserRole ()
{
}
public UserRole (User user, Role role)
{
this.user = user;
this.role = role;
}
#Id
#Column(name = "user_role_id")
#GeneratedValue(generator = RandomIdGenerator.GENERATOR_NAME)
#GenericGenerator(name = RandomIdGenerator.GENERATOR_NAME, strategy = "com.cs.util.RandomIdGenerator")
private Long id;
#ManyToOne
#JoinColumn(name = "user_id", referencedColumnName = "user_id")
private User user;
#ManyToOne
#JoinColumn(name = "role_id", referencedColumnName = "role_id")
private Role role;
public Long getId ()
{
return id;
}
public void setId (Long id)
{
this.id = id;
}
#JsonIgnore
public User getUser ()
{
return user;
}
public void setUser (User user)
{
this.user = user;
}
public Role getRole ()
{
return role;
}
public void setRole (Role role)
{
this.role = role;
}
}
With above code everything works fine but whenever I insert or delete a user_role all the records in the user_role table are deleted and re-inserted again.
For instance when I associate a new user_role to a user the existing user_role is deleted first and then it is re-associated again along with the new user role.
Hibernate: delete from user_roles where user_role_id=?
Hibernate: insert into user_roles (role_id, user_id, user_role_id) values (?, ?, ?)
Hibernate: insert into user_roles (role_id, user_id, user_role_id) values (?, ?, ?)
This is how I add a user role to the user entity.
UserRole userRole = new UserRole(user,role);
user.getUserRoles ().add (userRole);
m_userRepository.save (_user)
And then delete the user role from user like below
List<UserRole> uRolesTobeRemoved = new ArrayList<UserRole> ();
for(Role role : userRoles)
{
UserRole uRole = user.getUserRoles ().stream ().filter (userRole ->
userRole.getRole ().getId () == role.getId ()).collect (Collectors.toList ()).get (0);
uRolesTobeRemoved.add (uRole);
}
user.getUserRoles ().removeAll (uRolesTobeRemoved);
I'm not sure what is missing.

It looks like you see this behaviour due to so called "collection recreation".
Try to replace List<UserRole> userRoles to Set<UserRole> userRoles.
More detailed explanation you can find here.

Related

Insert users id to the patient in Spring Boot

I can't insert the id of the currently logged-in user while making the patient data.
I want the user to be able to add his own patients, but the problem is that when I add a new patient, the column id_user is null
I tried lots of ways but couldn't add id_user to the patient.
What do I miss?
This is my User Entity:
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int idUser;
private String firstName;
private String lastName;
private String username;
...
#ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.PERSIST)
#JoinTable(name = "users_roles",
joinColumns = #JoinColumn(name = "id_user"),
inverseJoinColumns = #JoinColumn(name = "id_role"))
#JsonManagedReference
private Set<Role> roles = new HashSet<>();
#OneToMany(cascade = CascadeType.ALL, mappedBy = "user")
private List<Patient> patients = new ArrayList<>();
public void add(Patient patient) {
if (patient != null) {
if (patients == null) {
patients = new ArrayList<>();
}
patients.add(patient);
patient.setUser(this);
}
}
Patient Entity:
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id_patient")
private int idPatient;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
...
#ManyToOne
#JoinColumn(name = "user_id", nullable = false)
private User user;
}
Controller
#RequestMapping("/addPatient")
public String addPatient(Model theModel, HttpServletRequest request) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
UserDetails userD = (UserDetails) auth.getPrincipal();
User u = userService.findByUsername(userD.getUsername());
request.getSession().setAttribute("id_user", u.getIdUser());
// int userId = user.getIdUser();
int userId = (int) request.getSession().getAttribute("id_user");
User user = new User();
user.setIdUser(userId);
Patient patient = new Patient();
patient.setUser(user);
theModel.addAttribute("patient", patient);
return "user/patients/add-patient-dashboard";
}
#PostMapping("savePatient")
public String savePatient(#ModelAttribute("patient") Patient thePatient, Model model) {
patientService.save(thePatient);
return "redirect:/user/allPatients";
}
I try editing the User service from:
#Override
public void save(User user) {
user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
userRepository.save(user);
}
to:
#Override
public void save(User user) {
List<Patient> patients = user.getPatients();
patients.forEach(patient -> user.add(patient));
user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
userRepository.save(user);
}
if someone can help me resolve this I would appreciate it since I'm struggling for a very long time with this
Thanks to M Denium I finally solve the issue. I have moved the whole code from addUser to saveUser method:
#RequestMapping("/addPatient")
public String addPatient(Model theModel) {
Patient patient = new Patient();
theModel.addAttribute("patient", patient);
return "user/patients/add-patient-dashboard";
}
#PostMapping("savePatient")
public String savePatient(#ModelAttribute("patient") Patient thePatient, Model model, HttpServletRequest request) {
patientService.save(thePatient);
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
UserDetails userD = (UserDetails) auth.getPrincipal();
User u = userService.findByUsername(userD.getUsername());
request.getSession().setAttribute("id_user", u.getIdUser());
int userId = (int) request.getSession().getAttribute("id_user");
User user = userService.findById(userId);
thePatient.setUser(user);
patientService.save(thePatient);
return "redirect:/user/allPatients";
}

Not null reference a null or transient value

So i am trying to achieve oneToone relationship between two entity classes.First class is a customer entity class which have two foreign keys buyer_id and seller_id.So what i want initially is that when the user fills the initial credentials in the website the buyer_id and seller_id field should be null and after the user fills the required information for the buyer or seller i will update the row of the corresponding customer and add the buyer_id and seller_id.But when i try to create a customer entry i am getting this error that buyer_id cannot be null?
This is my customer table
#Entity
#Table(name = "Customer")
public class Customer {
public enum Status{
ACTIVE,
IN_ACTIVE
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private long id;
#OneToOne(fetch = FetchType.LAZY,optional = true,cascade=CascadeType.ALL)
#JoinColumn(name = "seller_id",nullable = true,referencedColumnName = "id",updatable = true)
#Basic(optional = true)
private Seller seller_id;
#OneToOne(fetch=FetchType.LAZY,optional = true,cascade=CascadeType.ALL)
#JoinColumn(name = "buyer_id", nullable = true,referencedColumnName="id",updatable = true)
#Basic(optional = true)
private Buyer buyer_id;
#OneToOne(fetch=FetchType.LAZY,optional = false,cascade = CascadeType.ALL)
#JoinColumn(name = "user_id",nullable = false,unique = true,referencedColumnName = "id")
private User user_id;
public Buyer getBuyer_id() {
return buyer_id;
}
public void setBuyer_id(Buyer buyer_id) {
this.buyer_id = buyer_id;
}
#Column(name = "Name")
String name;
#Enumerated(EnumType.STRING)
#Column(name = "Status")
private Status status;
public Customer(String name,Status status){
this.name=name;
this.status = status;
}
public Customer(){
}
public Seller getSeller_id() {
return seller_id;
}
public void setSeller_id(Seller seller_id) {
this.seller_id = seller_id;
}
public User getUser_id() {
return user_id;
}
public void setUser_id(User user_id) {
this.user_id = user_id;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public User getUser() {
return user_id;
}
public void setUser(User user) {
this.user_id = user;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
}
This is my buyer table
#Entity
#Table(name="Buyer")
public class Buyer {
#Id
#Column(name = "id") private long id;
#Column(name = "GSTIN")
String GSTIN;
#Column(name = "Legal_Document")
#Lob
private byte[] legalDocument;
#OneToOne(fetch=FetchType.LAZY,
cascade = CascadeType.ALL,
mappedBy = "buyer_id")
#JsonIgnore
private Customer customer;
#Column(name = "Authorized_person_name")
String authorized_person_name;
#Column(name = "Authorized_person_email")
String authorized_person_email;
}
This is my seller table
#Entity
#Table(name = "Seller")
public class Seller {
#Id
#Nullable
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private long id;
#Column(name = "GSTIN")
private String GSTIN;
#Column(name = "GST_Document")
#Lob
private byte[] gst_document;
#OneToOne(fetch=FetchType.LAZY,
cascade = CascadeType.ALL,
mappedBy = "seller_id")
#JsonIgnore
private Customer customer;
// #OneToOne(fetch = FetchType.LAZY,
// cascade = CascadeType.ALL,
// mappedBy = "sellerId")
// #JsonIgnore
// private PickupAddress pickupAddress;
#Column(name = "name")
private String name;
#Column(name = "email")
private String email;
public String getGSTIN() {
return GSTIN;
}
public void setGSTIN(String GSTIN) {
this.GSTIN = GSTIN;
}
public byte[] getGst_document() {
return gst_document;
}
public void setGst_document(byte[] gst_document) {
this.gst_document = gst_document;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}

Roles not getting fetched from database along with the user object

I am creating a user registration flow with spring boot (2.1.3.RELEASE) . With the help of few articles I am able to successfully add a user along with its roles and user is able to login into the system. The problem is when user is successfully loged-in, the authentication obect has empty role even when I can see th correct role mapping in mysql database (honestly I am not able to get exactly how roles are fetched from database when findByUserName method is called.
Below is my code:
Entity objects
1. User.java
public class User implements UserDetails {
private static final long serialVersionUID = 1L;
public User() {
//Verification flow 2. set enabled = false
this.enabled = false;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "user_unique_number")
private long id;
#UniqueUser(groups = UniqueUserOrder.class)
#Column(name = "username", length = 60,nullable = false, unique = true)
private String username;
#Column(name = "email", nullable = false, unique = true)
private String email;
#Column(name = "password", nullable = false)
private String password;
#OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Set<UserRole> userRoles = new HashSet<>();
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
Set<GrantedAuthority> authorities = new HashSet<>();
userRoles.forEach(ur -> authorities.add(new Authority(ur.getRole().getName())));
return authorities;
}
public Set<UserRole> getUserRoles() {
return userRoles;
}
public void setUserRoles(Set<UserRole> userRoles) {
this.userRoles = userRoles;
}
...//OTHER GETTERS AND SETTERS
}
Roles.java
public class Role
{#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
private String name;
#OneToMany(mappedBy = "role", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Set<UserRole> userRoles = new HashSet<>();
public Role() {
}
public Role(RolesEnum rolesEnum) {
this.id = rolesEnum.getId();
this.name = rolesEnum.getRoleName();
}
public Set<UserRole> getUserRoles() {
return userRoles;
}
public void setUserRoles(Set<UserRole> userRoles) {
this.userRoles = userRoles;
}
...//OTHER GETTERS AND SETTERS }
UserRole.java
public class UserRole {
public UserRole() {}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private long id;
public UserRole(User user, Role role) {
this.user = user;
this.role = role;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "user_id")
private User user;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "role_id")
private Role role;
...//OTHER GETTERS AND SETTERS
}
4.RolesEnum.java
public enum RolesEnum {
ADMIN(1, "ROLE_ADMIN"),
BASIC(2, "ROLE_BASIC");
private final int id;
private final String roleName;
...//OTHER GETTERS AND SETTERS
}
New user is getting created as below:
...
...
String encryptedPassword = passwordEncoder.encode(adminPassword);
user.setPassword(encryptedPassword);
user.setUsername(adminUsername);
user.setEmail(adminEmail);
user.setUserCreateTime(LocalDateTime.now());
Set<UserRole> userRoles = new HashSet<>();
UserRole userRole = new UserRole();
userRole.setUser(user);
userRole.setRole(new Role(RolesEnum.ADMIN));
userRoles.add(userRole);
user.getUserRoles().addAll(userRoles);
user.setAccountNonLocked(true);
user.setEnabled(true);
user.setAccountNonExpired(true);
user.setCredentialsNonExpired(true);
user = userRepository.save(user);
...
...
At this point user is added successfully along with the roles in database
User is also able to successfully log-in but the problem is after logging, authentication object has an empty list of roles
Below is the code which is failing
public class SecurityConfig extends WebSecurityConfigurerAdapter {
......
......
private AuthenticationSuccessHandler loginSuccessHandler() {
return (request, response, **authentication**) -> {
Collection<? extends GrantedAuthority> authorities
= authentication.getAuthorities();
for (GrantedAuthority grantedAuthority : authorities) {
if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) {
isAdmin = true;
break;
} else if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) {
isBasic = true;
break;
}
}
if (isAdmin) { return "/admin/"; } else if (isBasic) { return
"/profile.html"; } else { throw new IllegalStateException(); }
response.sendRedirect("/");
};
}
......
......
When i inspect authentication object using eclipse the roles are not getting fetched from database
Here is the code for fetching user#Override
public User findByUserName(String username) {
return userRepository.findByUsername(username);
}
Do I need to add some additional logic to fetch roles along with user or Spring handles it behind the scene? Please let me know what I am doing wrong here... Thanks

#Id Not Mapped For Specific Entity In A Spring-Boot Controller

I have two entities Employee and Department and each have a Spring Web #RestController annotated class with update methods i.e. Http PUT.
For some strange reason (and likely a blindingly obvious solution) whenever the PUT is called for the Employee class, the ID in the JSON payload is NOT mapped to the id class of the Employee entity but it works perfectly for the Department entity.
Employee class:
Entity
#Table(name = "EMPLOYEE")
public class Employee implements Serializable, Identity<Long>, Deleted
{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "NAME")
private String name;
#ManyToOne
#Where(clause = "is_deleted = false")
private Department department;
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(name = "EMP_QUAL", joinColumns = #JoinColumn(name = "EMPLOYEE_ID"), inverseJoinColumns = #JoinColumn(name = "QUALIFICATION_ID"))
#WhereJoinTable(clause = "IS_DELETED = false")
#SQLDelete(sql = "UPDATE `EMP_QUAL` SET IS_DELETED = true where EMPLOYEE_ID = ? and QUALIFICATION_ID = ? and IS_DELETED = False")
private Set<Qualification> qualifications;
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(name = "EMP_PROJ", joinColumns = #JoinColumn(name = "emp_id"), inverseJoinColumns = #JoinColumn(name = "proj_id"))
#Where(clause = "is_deleted = false")
private Set<Project> projects;
#JsonIgnore
#Column(name = "is_deleted", nullable = false)
private Boolean isDeleted = false;
#Override
public Long getId()
{
return this.id;
}
#Override
public void setId(final Long id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(final String name)
{
this.name = name;
}
public Set<Project> getProjects()
{
return projects;
}
public void setProjects(final Set<Project> projects)
{
this.projects = projects;
}
public Department getDepartment()
{
return department;
}
public void setDepartment(final Department department)
{
this.department = department;
}
public Set<Qualification> getQualifications()
{
return qualifications;
}
public void setQualifications(final Set<Qualification> qualifications)
{
this.qualifications = qualifications;
}
public Boolean isDeleted()
{
return isDeleted;
}
public void setDeleted(final Boolean deleted)
{
isDeleted = deleted;
}
}
Department class:
#Entity
#Table(name = "DEPARTMENT")
public class Department implements Serializable, Identity<Long>, Deleted
{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "name")
private String name;
#OneToMany(fetch = FetchType.EAGER)
#WhereJoinTable(clause = "is_deleted = false")
#JoinTable(name = "DEPARTMENT_EMPLOYEE", joinColumns = {#JoinColumn(name = "department_id")},
inverseJoinColumns = {#JoinColumn(name = "employee_id")})
#SQLDelete(sql = "UPDATE DEPARTMENT_EMPLOYEE SET is_deleted = true where department_id = ? and employee_id = ? and is_deleted = false")
private Set<Employee> departmentMembers;
#Column(name = "is_deleted", nullable = false)
private Boolean isDeleted;
#Override
public Long getId()
{
return this.id;
}
#Override
public void setId(final Long id)
{
this.id = id;
}
#Override
public Boolean isDeleted()
{
return this.isDeleted;
}
#Override
public void setDeleted(final Boolean isDeleted)
{
this.isDeleted = isDeleted;
}
public String getName()
{
return name;
}
public void setName(final String name)
{
this.name = name;
}
public Set<Employee> getDepartmentMembers()
{
return departmentMembers;
}
public void setDepartmentMembers(final Set<Employee> departmentMembers)
{
this.departmentMembers = departmentMembers;
}
}
When call PUT /employees/{id}:
Calling PUT /departments/{id}:
As you can see in the screenshots of the debugger the id field of Department is populated while it is null in Employee. I'm testing this with Swagger and I am setting the ID in the payload. I don't have any specific Jackson configuration set I just use Spring boot's default but I cannot work out why only in Employee the id field is never mapped.
Employee body:
{
"id":1,
"name": "New Name"
}
Department body:
{
"id":2,
"name": "chemistry",
"deleted":false
}
The issue was due to a Jackson annotation #JsonIdentityInfo on another entity Project which is has a relationship with Employee:
#Entity
#Table(name = "PROJECT")
public class Project implements Serializable, Identity<Long>, Deleted
{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "name")
private String name;
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(name = "EMP_PROJ", joinColumns = #JoinColumn(name = "proj_id"), inverseJoinColumns = #JoinColumn(name = "emp_id"))
#JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "id")
#Where(clause = "is_deleted = false")
private Set<Employee> employees;

JsonIgnore dynamically If it is nested?

I have hibernate models like following:
Ticket Model:
#Entity
#Table(name = "ticket")
public class TicketModel {
private BigInteger id;
private UserModel user;
#Id
#Column(name = "id", nullable = false)
#SequenceGenerator(name = "seqTicket", sequenceName = "ticket_id_seq", allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seqTicket")
public BigInteger getId() {
return id;
}
public void setId(BigInteger id) {
this.id = id;
}
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "user_id", referencedColumnName = "id")
public UserModel getUser() {
return user;
}
public void setUser(UserModel user) {
this.user = user;
}
}
User Model:
#Entity
#Table(name = "user")
public class UserModel {
private BigInteger id;
private String name;
private CompanyModel company;
#Id
#Column(name = "id", nullable = false)
#SequenceGenerator(name = "seqUser", sequenceName = "user_id_seq", allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seqUser")
public BigInteger getId() {
return id;
}
public void setId(BigInteger id) {
this.id = id;
}
#Basic
#Column(name = "name", nullable = false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "company_id", referencedColumnName = "id")
public CompanyModel getUser() {
return company;
}
public void setUser(CompanyModel company) {
this.company = company;
}
}
Company Model:
#Entity
#Table(name = "company")
public class UserModel {
private BigInteger id;
private String name;
#Id
#Column(name = "id", nullable = false)
#SequenceGenerator(name = "seqCompany", sequenceName = "company_id_seq", allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seqCompany")
public BigInteger getId() {
return id;
}
public void setId(BigInteger id) {
this.id = id;
}
#Basic
#Column(name = "name", nullable = false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Now, what i want to do is json ignoring user's company in my rest controller if I am returning ticket object. But if I am returning User object I dont want to ignore company relation.
For example:
in ticket controller's return it should be a json like :
{
"id":1,
"user":{
"id":3,
"name":"something"
}
}
but in user controller's return it should be like:
{
"id":3,
"name":"something",
"company":{
"id":5,
"name":"something else"
}
}
So shortly, I want to ignore relations if it is in second dimension.
Is that possible?

Resources