使用有状态EJB在JPA生命周期中不起作用

问题描述

我尝试在Listenner中注入SFSB以获取用户,但是当尝试在Entity类中注入“ usuarioSessaoService” Bean时,未创建该Bean会生成NullPointer。在BaseEntityListenner中注入“ usuarioSessaoService” Bean时,将创建该Bean,但是getUsuarioSessao()返回null。

我在不同的Stateless类(例如ProjetoServiceImpl)中使用“ usuarioSessaoService” Bean进行了测试,并且工作正常。

@Log
@Stateful(name = "UsuarioSessaoService")
public class UsuarioSessaoServiceImpl implements UsuarioSessaoService,Serializable {
    private static final long serialVersionUID = 1L;
    
    private Usuario usuario;
            
    @Override
    public void defineUsuarioSessao(Usuario usuario) {
        this.usuario = usuario;
    }

    @Override
    public Usuario getUsuarioSessao() {
        return usuario;
    }    
}
@Stateless
@MappedSuperclass
@ToString @EqualsAndHashCode
@EntityListeners(BaseEntityListenner.class)
public class BaseEntity implements Serializable {
    private static final long serialVersionUID = 1L;
     
    @Transient
    @EJB(name = "UsuarioSessaoService")
    private UsuarioSessaoService usuarioSessaoService;
    
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    @Getter
    private Long id;
    
    @ManyToOne
    @JoinColumn(name = "USUARIO_ALteraCAO_ID")
    @Getter @Setter
    private Usuario usuarioAlteracao;
    
    @Column(name = "DATA_ALteraCAO")
    @Temporal(javax.persistence.TemporalType.TIMESTAMP)
    @Getter
    private Date dataAlteracao;
    
    @Column
    @LogColumn
    @Getter @Setter 
    private Boolean ativo = true;
    
    @PrePersist @PreUpdate
    private void setCamposDefault() throws UsuarioVazioException,NamingException {
        dataAlteracao =  new Date();
        usuarioAlteracao = usuarioSessaoService.getUsuarioSessao(); //usuarioSessaoService is null
    }
}
public class BaseEntityListenner implements Serializable {
    private static final long serialVersionUID = 1L;
    
    @EJB(name = "UsuarioSessaoService")
    private UsuarioSessaoService usuarioSessaoService;
    
    @PrePersist @PreUpdate
    private void setCamposDefault(BaseEntity entity) {
        entity.setUsuarioAlteracao(usuarioSessaoService.getUsuarioSessao()); //usuarioSessaoService.getUsuarioSessao() is null
    }
}
@Stateless(name = "ProjetoService")
public class ProjetoServiceImpl implements ProjetoService {
    ...
    
    @EJB(name = "UsuarioSessaoService")
    private UsuarioSessaoService usuarioSessaoService;

    @Transactional
    @Override
    public Projeto salvar(Projeto projeto,Usuario usuario) {
        usuarioSessaoService.defineUsuarioSessao(usuario);
        return projetoDAO.edit(projeto);
    }
...
}

谁可以在@PrePersist和@PreUpdate事件中获得“ usuario”的值?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)