Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

423
Vistas
Spring JPA creates entity with null values

I have the following code:

groupModel.getUserFormGroups().clear();
for(MemberDTO member : group.getMembers()){
    User u = userRepository.findByEmail(member.getEmail());
    System.out.println(member.getEmail() + " " + groupModel.getName() + " " + member.getRole());
    if(u == null){
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }
    groupModel.getUserFormGroups().add(new UserFormGroup(u, groupModel, UserFormGroupRole.ADMIN));
}

try{
    groupRepository.save(groupModel);
    return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
} catch (DataIntegrityViolationException e){
    System.out.println(e.getMessage());
    System.out.println(e.getClass());
    return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).build();
}

When I run this, the new UserFormGroups have an id and all the other fields are null. Is there something wrong with fully updating a ManyToOne relationship?

On the group entity I have the following OneToMany relation:

@OneToMany(targetEntity=UserFormGroup.class, cascade = { CascadeType.PERSIST, CascadeType.REMOVE }, fetch = FetchType.EAGER, mappedBy = "formGroup", orphanRemoval=true)
private Set<UserFormGroup> userFormGroups = new HashSet<>();

And the UserFormGroup relation looks like this:

@Entity
@Table(uniqueConstraints={
        @UniqueConstraint(columnNames = {"user", "form_group"})
})
public class UserFormGroup implements Serializable{

    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private long id;

    @ManyToOne
    @JoinColumn(name = "user",referencedColumnName = "id")
    private User user;

    @ManyToOne
    @JoinColumn(name = "form_group", referencedColumnName = "id")
    private FormGroup formGroup;

    @Column(name = "role")
    private UserFormGroupRole role;

    public UserFormGroup() {
    }

    public UserFormGroup(User user, FormGroup group, UserFormGroupRole role) {
        this.user = user;
        this.formGroup = group;
        this.role = role;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public FormGroup getFormGroup() {
        return formGroup;
    }

    public void setFormGroup(FormGroup formGroup) {
        this.formGroup = formGroup;
    }

    public UserFormGroupRole getRole() {
        return role;
    }

    public void setRole(UserFormGroupRole role) {
        this.role = role;
    }
}
about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Not 100% but in my opinion, the problem might be following:

The CrudRepository's implementation of the save method checks whether the object you are saving is a new or existing entity. If it is already an existing entity, it performs a merge operation. This would be the scenario that's happening in your case as the groupModel is an existing entity.

Now on the @OneToMany dependency, you only have these cascade options:

cascade = { CascadeType.PERSIST, CascadeType.REMOVE }

If you add CascadeType.MERGE the operation should be propagated to the UserFromGroup entities and persist them (the default behavior of merge when the entities are new ones).

about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda