Spring Boot + JPA + Websecurity - How to save User + Profile?

Asked

Viewed 368 times

0

Hello, it’s been a few days that I’m breaking my head to be able to register a user and its role. The information should be recorded in different entities and I can’t make that relationship. I can only persist the user in the 'user' table. I cannot persist the profile information in the 'profile' entity. I’d like to understand how this relationship could work.

Hibernate Mappings

USER MODEL

@ManyToMany
@JoinTable(name="usuario_perfil", joinColumns = 
    @JoinColumn(name="usuario_id", referencedColumnName="id"), inverseJoinColumns = 
        @JoinColumn(name="perfil", referencedColumnName="rolePerfil"))
private List<Perfil> perfil2;

MODEL PROFILE

@Entity
public class Perfil implements GrantedAuthority{

    private static final long serialVersionUID = 1L;

    @Id
    @Enumerated
    private RolePerfil rolePerfil;

    @ManyToMany(mappedBy = "perfil2")
    private List<Usuario> usuarios;

    @Override
    public String getAuthority() {
        return rolePerfil.toString();
    }

    public List<Usuario> getUsuarios() {
        return usuarios;
    }

    public void setUsuarios(List<Usuario> usuarios) {
        this.usuarios = usuarios;
    }

    public RolePerfil getRolePerfil() {
        return rolePerfil;
    }

    public void setRolePerfil(RolePerfil rolePerfil) {
        this.rolePerfil = rolePerfil;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

}

Thymeleaf

<div class="form-group col-md-2">
    <label for="perfil2">Perfil</label>
    <select class="form-control" name="perfil2" id="perfil2">
        <option
            th:each="role : ${T(com.Test.model.RolePerfil).values()}"
            th:value="${role}" th:text="${role}">
        </option>
    </select>
</div>

Params

enter image description here

USERS CONTROLLER

@PostMapping(value = "/save")
public ModelAndView save(Usuario usuario, BindingResult bindingResult, RedirectAttributes redirectAttributes) {

    BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    String senha = passwordEncoder.encode(usuario.getSenha());
    String confirmaSenha = passwordEncoder.encode(usuario.getConfirmaSenha());
    usuario.setSenha(senha);
    usuario.setConfirmaSenha(confirmaSenha);

    System.out.println(usuario);

    usuarioRepository.save(usuario);
    redirectAttributes.addFlashAttribute("message", "Operação realizada com sucesso!");

    return edit(usuario.getId());
}

Console

    Usuario [nome=Bruno, login=bruno, senha=$2a$10..., confirmaSenha=$2a$10...,
email=test@test, dataRegistro=2020-02-13T02:50:23.790, status=true, perfil2=null]
    Hibernate: select next_val as id_val from hibernate_sequence for update
    Hibernate: update hibernate_sequence set next_val= ? where next_val=?
    Hibernate: insert into usuario (data_registro, email, login, nome, senha, status, id) values (?, ?, ?, ?, ?, ?, ?)

Hibernate

Hibernate: create table cliente (id bigint not null, bairro varchar(255), celular varchar(255), cep varchar(255), cidade varchar(255), cpf varchar(255), data_cadastro datetime, data_nascimento date, email varchar(255), endereco varchar(255), estado varchar(255), facebook varchar(255), instagram varchar(255), nome varchar(255), observacoes varchar(255), profissao varchar(255), sexo varchar(255), telefone varchar(255), tipo_pessoa varchar(255), twitter varchar(255), primary key (id)) engine=InnoDB
Hibernate: create table hibernate_sequence (next_val bigint) engine=InnoDB
Hibernate: insert into hibernate_sequence values ( 1 )
Hibernate: insert into hibernate_sequence values ( 1 )
Hibernate: insert into hibernate_sequence values ( 1 )
Hibernate: create table perfil (role_perfil integer not null, primary key (role_perfil)) engine=InnoDB
Hibernate: create table produto (id bigint not null, altura integer, categoria varchar(255), codigo_barra bigint, comissao decimal(19,2), comprimento integer, custo_operacional decimal(19,2), data_fabricacao datetime, data_validade datetime, descricao varchar(255), estoque integer, estoque_minimo integer, fabricante varchar(255), fornecedor varchar(255), icms decimal(19,2), largura integer, margem_lucro decimal(19,2), modelo varchar(255), nome varchar(255), origem varchar(255), peso integer, preco_promocional decimal(19,2), preco_unidade decimal(19,2), preco_venda decimal(19,2), referencia bigint, unidade varchar(255), primary key (id)) engine=InnoDB
Hibernate: create table usuario (id bigint not null, data_registro datetime, email varchar(255), login varchar(255), nome varchar(255), senha varchar(255), status bit, primary key (id)) engine=InnoDB
Hibernate: create table usuario_perfil (usuario_id bigint not null, perfil integer not null) engine=InnoDB
Hibernate: alter table usuario_perfil add constraint FKh5di2ijgv1c31x7q4k2xggiga foreign key (perfil) references perfil (role_perfil)
Hibernate: alter table usuario_perfil add constraint FKnrjqnbylalt4ykxbcef24f57w foreign key (usuario_id) references usuario (id)

From now on, thank you gentlemen.

  • Pq User is as @Id?

  • so I may be mistaken, but I believe I can leave the user as the primary key, since I will not make use of the identifier.

1 answer

1

Add the association between tables.

PROFILE CLASS

@Id
private Long id;

@ManyToOne(fetch = FetchType.EAGER)
@GeneratedValue(strategy = GenerationType.AUTO)
@JoinColumn(name = "usuario_id")
private Usuario usuario;

USER CLASS

@Id
private Long id;

@OneToMany(fetch = FetchType.EAGER, mappedBy = "usuario")
private List<Perfil> perfil = new ArrayList<>();
  • Even with these mappings nothing happens in the Profile table. it is necessary to persist the profileRepository.save(user) or something of the type?

  • I believe that if I correctly map the entities Hibernate makes this persistence automatically. but is tense. :(

  • Yes, it automatically persists when you save the user. Looking at your controller there, you do not set any profile for the user. Create a test profile and add it to your user profile list. Ai vc makes the user persistence. You have the code in git?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.