HIbernate - Spring boot / Null references FK when posting an User

Viewed 30

Controller

    @PostMapping
    public User newUser(@RequestBody User user) {
        return userService.save(user);
    }

ROL ENTITY

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "roles")
public class Role {
    @Id
    @GeneratedValue (strategy = GenerationType.IDENTITY)
    private Long role_id;
    @Column(name = "rol")
    @Enumerated(EnumType.STRING)
    private RoleType role;

    @Enumerated(EnumType.STRING)
    @ElementCollection(targetClass = Permission.class)
    @CollectionTable(
            name = "permisos",
            joinColumns=@JoinColumn(name = "role_id", referencedColumnName = "role_id")
    )
    private List<Permission> permissions;

Entity

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "usuarios")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String password;
    @JoinColumn(name = "role_id")
    @ManyToOne(targetEntity= com.ecommerce.model.Role.class)
    private Role role;

POST EXAMPLE

{
    "name" : "User",
    "password" : "1111",
    "role_id": 1
}

User have a relathionship with Roles, i have a Rol added to sql, but return NULL when i posted, this is what i expected! I cant find the solution Query example :

insert into usuarios (name,password,role_id) values ("Ignacio","1234",1);

EXPECTED OUTPUT
{
"id": 14,
"name": "User",
"password": "1111",
"role": {
"role_id": 1,
"role": "seller",
"permissions": [
"add_product"
     ]
  }
}
OUTPUT
{
"id": 15,
"name": "User2",
"password": "1111",
"role": null
}
1 Answers

This is the solution then with a DTO is more cleaner. Add one more property Long role_id and ignore property. When you do a post hibernate try to insert an id not a object. This way the db stay the same, but this new property is what hibernate use to catch the relationship. I hope this help.

Then with a DTO you can change the way that the info is showing in the get

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "usuarios")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String password;
    @JoinColumn(name = "role_id", referencedColumnName = "role_id",nullable = true,insertable=false, updatable=false)
    @ManyToOne(targetEntity= com.ecommerce.model.Role.class)
    private Role role;

    @JsonProperty("role_id")
    @JsonIgnoreProperties("role_id")
    @JsonBackReference
    private Long role_id;

POST EXAMPLE NOW

{
    "name" : "Federico",
    "password" : "tupassword",
    "role_id": 1
}

OUTPUT

{
"id": 14,
"name": "Federico",
"password": "tupassword",
"role": {
"role_id": 1,
"role": "seller",
"permissions": [
"add_product",
"edit_product",
"delete_product"
        ]
   }
}
Related