Search code examples
javaspring-data-jpapostmanspring-restcontrollercrud-repository

How to insert a json body with multiple data to multiple tables with relationship in springboot


I have two entities: UserEntity and LoginEntity and crudrepositories for each. The entities have a relationship of OneToOne where one user will have one login account. I also created a controller and I can get all the data from the database i.e when call getalluser I get all users with their relationship to login. and when I call getAllLogins I get all logins accounts. I also managed to insert the user and the login using API each individually and it's working fine but this will omit the foreign-key user_id.

Now since am knew am stack on how to insert the user and login each respectively with their relationships through one json body

@Entity@Table(name="user_table")public class UserEntity {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long uid;

private String fname;
private String lname;

@OneToOne( cascade = CascadeType.ALL, mappedBy = "userEntityFk")
private LoginEntity logins;

public UserEntity() {
    super();
}
public Long getUid() {
    return uid;
}
public void setUid(Long uid) {
    this.uid = uid;
}
public String getFname() {
    return fname;
}
public void setFname(String fname) {
    this.fname = fname;
}
public String getLname() {
    return lname;
}
public void setLname(String lname) {
    this.lname = lname;
}
public LoginEntity getLogins() {
    return logins;
}
public void setLogins(LoginEntity logins) {
    this.logins = logins;
}
public UserEntity(Long uid, String fname, String lname, LoginEntity logins) {
    super();
    this.uid = uid;
    this.fname = fname;
    this.lname = lname;
    this.logins = logins;
}

@Entity @Table(name="login_table") public class LoginEntity {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long lid;

private String username;
private String password;

@OneToOne(cascade = CascadeType.ALL )
private UserEntity userEntityFk;

public LoginEntity() {
    super();
}
public LoginEntity(Long lid, String username, String password, UserEntity userEntityFk) {
    super();
    this.lid = lid;
    this.username = username;
    this.password = password;
    this.userEntityFk = userEntityFk;
}
public Long getLid() {
    return lid;
}
public void setLid(Long lid) {
    this.lid = lid;
}
public String getUsername() {
    return username;
}
public void setUsername(String username) {
    this.username = username;
}
public String getPassword() {
    return password;
}
public void setPassword(String password) {
    this.password = password;
}
public UserEntity getUserEntityFk() {
    return userEntityFk;
}
public void setUserEntityFk(UserEntity userEntityFk) {
    this.userEntityFk = userEntityFk;
}   

}

@Repository 
public interface LoginRepo extends CrudRepository<LoginEntity, Integer> {

} 

@Repository 
public interface UserRepo extends CrudRepository<UserEntity, Integer> {

}

@RestController
@RequestMapping(path="/api")
public class MainController {

@Autowired 
private UserRepo userRepository;

@Autowired
private LoginRepo loginRepository;

//===this works fine i can get all the users after insert
@GetMapping(path="/user_acc")
  public @ResponseBody Iterable<UserEntity> getAllUsers() {
    // This returns a JSON or XML with the users
    return userRepository.findAll();
  }
//================this too works fine after insert
@GetMapping(path="/login_acc")
  public @ResponseBody Iterable<LoginEntity> getAlllogins() {
    // This returns a JSON or XML with the users
    return loginRepository.findAll();
  }
//===adding single user works fine. and it returns user_id
@PostMapping("/user_acc")
public Long addNewUser(@RequestBody UserEntity userz){
    UserEntity ue = userRepository.save(userz);
    return ue.getUid(); 
}

     //===this works but the foreign key not inserted and thats where my problem is
 @PostMapping("/login_acc")
    public LoginEntity addNewLogin(@RequestBody LoginEntity loginz){
        return loginRepository.save(loginz);
    }

}

class UserLogin{ 
   UserEntity myuser; 
   LoginEntity mylogin; 
   
   public UserEntity getMyuser() { 
       return myuser; 
    } 
 
   public void setMyuser(UserEntity myuser) { 
       this.myuser = myuser; 
   } 

   public LoginEntity getMylogin() { 
      return mylogin; 
   } 
    
   public void setMylogin(LoginEntity mylogin) { 
     this.mylogin = mylogin; 
    }

}

result on post http://localhost:8080/api/login_acc. account created but no foreign key
result on post http://localhost:8080/api/login_acc. account created but no foreign key
{
"lid": 1,
"username": "admin1",
"password": "11111",
"userEntityFk": null
}

result on geting all users on get method http://localhost:8080/api/user_acc
{
"uid": 1,
"fname": "hassan",
"lname": "zahor",
"logins": null
}

what i want to post is this body below to multiple tables
{
"fname":"hassan",
"lname":"zahor",
"username": "admin5",
"password": "55555"
}

Solution

  • This one should works better :

    {
    "fname":"hassan",
    "lname":"zahor",
    "userEntityFk" : {
       "username": "admin5",
       "password": "55555"
       }
    }
    

    However, you will get an error if your endpoint returns an object that contains a loop inclusion : spring will try to map it into json indefinitely.

    You can correct this issue to map your result into another object before returning it from your controller, or just remove the property "logins" from UserEntity.