如何在EJB上获得隔离事务?

时间:2016-09-02 08:14:12

标签: java-ee ejb-3.0 jta

我有以下EJB会话bean:

@Stateless
public class FacadeBean implements FacadeBeanRemote {
    @PersistenceContext(unitName = "ejercicio7PU")
    private EntityManager em;

    @Override
    public void insertar(final long id) {
        Record r = new Record();
        r.setId(id);
        em.persist(r);
    }

    @Override
    public void insertarTres(final long id1, final long id2, final long id3) {
        Logger.getLogger(FacadeBean.class.getName()).log(Level.INFO, "Insertando registros");
        insertar(id1);
        insertar(id2);
        insertar(id3);
    }

}

Record实体如下:

@Entity
public class Record implements Serializable{

    private static final long serialVersionUID = 1L;

    @Id
    private Long id;

    public Long getId() {
        return id;
    }

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

    @Override
    public String toString() {
        return "Record{" + "id=" + id + '}';
    }

}

我在独立的java应用程序上调用远程方法来插入三个数字:

 ejb.insertarTres(1l, 2l, 3l);

现在,当我再次使用以下数字调用远程方法时,我希望这样:

ejb.insertarTres(4l, 5l, 3l);

即使数字3发生异常,也会保存数字4和5.

我尝试用

设置插入方法
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)

但它不适用于我的

1 个答案:

答案 0 :(得分:0)

您必须使用sessionContext.getBusinessObject (FacadeBeanLocal.class);
要获取bean的另一个实例以应用REQUIRE_NEW

@Stateless
public class FacadeBean implements FacadeBeanRemote {
    @PersistenceContext(unitName = "ejercicio7PU")
    private EntityManager em;
    @Resource
    private SessionContext sessionContext;

    private FacadeBeanLocal local;

    @PostConstruct
    void init() {
      local = sessionContext.getBusinessObject(FacadeBeanLocal.class);
     }

    @Override
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void insertar(final long id) {
        Record r = new Record();
        r.setId(id);
        em.persist(r);
    }

    @Override
    public void insertarTres(final long id1, final long id2, final long id3) {
        Logger.getLogger(FacadeBean.class.getName()).log(Level.INFO, "Insertando registros");
        local.insertar(id1);
        local.insertar(id2);
        local.insertar(id3);
    }

}