使用JPA详细说明异常时回滚事务

时间:2015-10-08 17:28:55

标签: jpa cascade persist

我正在使用JPA和Hibernate 4.1 2.0我需要拥有两个主/详细信息表。我的问题是,细节中是否存在未在表中存储任何数据的异常。

下面显示了我的代码。

@Entity
@Table(name = "tblmaster")
public class Master implements Serializable {

    private static final long serialVersionUID = 1L;
    private Long id;
    private String mail;
    private List<Detail> listDetail = new ArrayList<Detail>();

    @Id
    @Column(name = "secmaster", nullable = false, unique = true)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public Long getId() {
        return id;
    }

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

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @OneToMany(mappedBy = "master", cascade = CascadeType.ALL, targetEntity = Detail.class,fetch = FetchType.EAGER)
    public List<Detail> getListDetail() {
        return listDetail;
    }

    public void setListDetail(List<Detail> listaProgramaEducativo) {
        this.listDetail = listDetail;
    }

    public void addDetail(Detail detail) {
        listDetail.add(detail);
        detail.setDetail(this);
    }



@Entity
@Table(name = "tbldetail")
public class Detail implements Serializable {

    private static final long serialVersionUID = 1L;
    private Long id;    
    private Master master;

    @Id
    @Column(name = "secdetail", nullable= false, unique = true)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public Long getId() {
        return id;
    }

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

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "secmaster")
    public Master getMaster() {
        return master;
    }

    public void setMaster(Master master) {
        this.master = master;
    }   

Master master = new Master();

master.setMail(&#34; jj@gmail.com");

Detail detail1 = new Detail();
Detail detail2 = new Detail();

master.addDetail(detail1);
master.addDetail(detail2);
session.persist(master);
master.addDetail();

在示例中,我根据字段的大小详细说明了一个例外。我需要的是,如果我详细创建一个异常,不要留在主人。

1 个答案:

答案 0 :(得分:0)

处理事务取决于您在代码中创建事务的方式。

如果您在代码中强制开始并提交事务,则应将整个事务放在try..catch块中,如Hibernate Javadoc中所述:

 Session sess = factory.openSession();
 Transaction tx;
 try {
     tx = sess.beginTransaction();
     //do some work
     ...
     tx.commit();
 }
 catch (Exception e) {
     if (tx!=null) tx.rollback();
     throw e;
 }
 finally {
     sess.close();
 }

如果您使用事务bean(使用@Transactional注释或EJB标记),则任何RuntimeException和某些类型的PersistenceException都将导致事务自动回滚