Problems recovering data via altered JPA directly in the related entity

Asked

Viewed 62 times

0

I have the following entity

@Entity
@Table(name="matricula")
public class Matricula implements Serializable {

    private static final long serialVersionUID = 1L;

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

    @NotNull
    @ManyToOne(fetch=FetchType.EAGER)
    @JoinColumn(name = "usuario_id", nullable = false)
    private Usuario usuario;

    //...
}   

The Matricula entity belongs to a student (user) and only one student. But I have a problem. When I look for the registration after changing the given direction in the student, although in the database the information is already updated. routine still comes the old die.

User entity.

@Entity
@Table(name="usuario")
public class Usuario implements Serializable {

    private static final long serialVersionUID = 1L;

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

    @Enumerated(EnumType.STRING)
    @Column(name="tipo_do_cartao")
    private TipoDeCartao cartao;
    //---
}

Persistence of user change.

// Methodos.
public String confirma(){
    if(novoTipoDeCartao == null || novoTipoDeCartao.equals(usuario.getCartao()) ){
        FacesUtil.addErrorMessage("O novo tipo de cartão não pode ser nulo ou não pode ser igual ao atual");
        return "";
    }
    try{
        usuario.setCartao(novoTipoDeCartao);
        servicoUsuario.trocarTipoDeCartao(usuario);
        return "/Index.xhtml";
    } catch (NegocioException e){
        FacesUtil.addErrorMessage(e.getMessage());
        return "";
    }
}

@Transacao
    public void trocarTipoDeCartao(Usuario usuario) {
        Matricula matriculaAtiva = servicoMatricula.matriculaAtiva(usuario.getId());
        servicoDocumento.cancelaDocumentos(matriculaAtiva,EstadoDoDocumento.VENCIDO_TROCA);
        usuario = usuarioDao.salvar(usuario);
        matriculaAtiva = servicoMatricula.matriculaAtiva(usuario.getId());
    }

public Usuario salvar(Usuario usuario) {
        System.out.println("-- UsuarioDao salvar-----");
        try {
            usuario = entityManager.merge(usuario);
            //entityManager.flush();
            return usuario;
        }catch (PersistenceException e) {
            e.printStackTrace();
            //throw new NegocioException("Email já cadastrado");
            throw new NegocioException(TrataErro.buscaErro(e,"Não foi possivel salvar"));
        }catch (Exception e) {
            e.printStackTrace();
            //throw new NegocioException("Email já cadastrado");
            throw new NegocioException(TrataErro.buscaErro(e,"Não foi possivel salvar (E)"));
        }   
    }

Get the license plate

public Matricula matriculaAtiva(Long usuarioId) {
        return matriculaDao.buscarMatriculaAtiva(usuarioId);
    }

public Matricula buscarMatriculaAtiva(Long idUsuarioLogado) {
        try {
            CriteriaBuilder cb = entityManager.getCriteriaBuilder();
            CriteriaQuery<Matricula> cq = cb.createQuery(Matricula.class);
            Root<Matricula> m = cq.from(Matricula.class);
            cq.select(m);
            List<Predicate> criteria = new ArrayList<>();

            criteria.add(cb.equal(m.<Long>get("usuario").get("id"),idUsuarioLogado));
            criteria.add(cb.equal(m.<Boolean>get("status"),true));

            cq.where(criteria.toArray(new Predicate[0]));
            cq.orderBy(cb.asc(m.get("id")));
            TypedQuery<Matricula> tq = entityManager.createQuery(cq);

            Matricula mat = tq.getSingleResult();
            return mat;

        } catch (NoResultException e) {
            return null;
        }
    }
  • select occurs after commit? If you are saving the data and want to have the object updated, you should flush.

  • Yes. Select occurs after commit.

  • but in this case it is in the same request or another? use some kind of cache? how are your scopes in the view? I ask this because you can be with the object in Session and present yes an outdated object.

  • It’s another request. All my screens with viewscope. What is strange is that if on the screen that calls the registration I show the field in question (even with disable=false), shows updated and the registration screen is updated. Otherwise, the first time I enter is outdated. Closing and calling again is correct. It is very strange. I made the gambiarra to show the value on the previous screen, at least at the time this working, but I did not like this solution.

No answers

Browser other questions tagged

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