简体   繁体   English

如何在 Spring JPA 中回滚 OnetoOne 关系

[英]How to Rollback OnetoOne Relationship in Spring JPA

I Have Three Entity Classes while I'm Inserting Data into Database If Any Exception is Thrown then All table Values are Should be Rollback当我将数据插入数据库时​​,我有三个实体类如果抛出任何异常,那么所有表值都应该回滚

Service Class:服务等级:

    @Service
    @Transactional
    public class CustomerService  {
    
        private final CustomerDetailsRepo cdRepo;
        
        @Autowired
        public CustomerService(CustomerDetailsRepo cdRepo) {
            
            this.cdRepo = cdRepo;
            
        }
        public void saveCustomer(CustomerDetails customerDetails) 
        {   
            cdRepo.save(customerDetails);       
        }   
}

The Above Service Class is One of my Three Service class以上服务类是我的三个服务类之一

Entity Class:实体类:

@Entity
@Table(name = "tbl_Customer")
public class CustomerDetails {

    @Id
    @GeneratedValue
    @Column(name="Customer_Id")
    private Long custid;

    @Column(name="Customer_Name")
    private String customerName;
    
    @Column(name="Email")
    private String email;
    
    @Column(name="Address")
    private String address;
    
    @Column(name="Phone")
    private String phoneno;
    
    public CustomerDetails() {
    }
      
    @OneToOne(mappedBy = "customerDetails", fetch = FetchType.LAZY,
            cascade = CascadeType.ALL)
    private Product product;

//getters and setters
}

Here I'm used OnetoOne Relationship这里我用的是 OnetoOne 关系

There are multiple ways you can achieve this.有多种方法可以实现这一目标。 Something like :就像是 :

public void saveCustomer(CustomerDetails customerDetails) {
  try {
    cdRepo.save(customerDetails);
  } catch (Exception e) {
    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
  }
}

Or you can mark your method with Transactional.或者您可以使用 Transactional 标记您的方法。 Eg:例如:

@Transactional(rollbackFor = SQLException.class)
public void saveCustomer(CustomerDetails customerDetails) throws SQLException{   
 cdRepo.save(customerDetails);
throw new SQLException("Some error when saving");       
} 

To learn more, you can refer here .要了解更多信息,您可以参考此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM