【问题标题】:How to delete a record from a table the table reference is in another table using hibernate如何使用hibernate从表中删除表引用在另一个表中的记录
【发布时间】:2019-03-10 22:07:02
【问题描述】:

我是 Hibernate 的新手, 我想对一个表执行删除,当前表引用到另一个表。

例如:Client_Loan 是我要删除的主表,另一个表是“Loan_Details”。 loan_details 表包含对 client_loan id 的 foreign_Key 引用。

我想对 client_loan 表执行删除,如果我删除 client_loan 表,另一个表中的引用也想使用 Hibernate 一次性删除,谁能告诉我如何执行。 提前致谢。

【问题讨论】:

    标签: postgresql hibernate


    【解决方案1】:

    首先从 Loan_Details 中删除,然后是 Client_loan

    First delete from Loan_Details then Client_loan
    
    int id = 2;
    Session session=getSession();  
    String hql = "delete from Loan_Details where client_loanid = :id"; 
    session.createQuery(hql).setString("id", new Integer(id)).executeUpdate();
    
    hql = "delete from Client_Loan where clientid = :id"; 
    session.createQuery(hql).setString("id", new Integer(id)).executeUpdate();

    【讨论】:

      【解决方案2】:
      You must be having classes like below
      
      @Entity
      @Table(name="Client_Loan")
      public class ClientLoan {
      
          @Id
          @GeneratedValue(strategy = GenerationType.AUTO)
          private Long id;
      
          private String name;
      
          @OneToMany(cascade = CascadeType.ALL, 
              mappedBy = "client", orphanRemoval = true)
          private List<Loan_Details> loans = new ArrayList<>();
      
          public void setName(String name) {
              this.name = name;
          }
      
          public List<Loan_Details> getComments() {
              return loans;
          }
      
          public void addComment(Loan_Details loan) {
              loans.add(loan);
          }
      
      }
      
      below for load details
      
      @Entity
      @Table(name="Loan_Details ")
      public class LoanDetails {
      
      
          @Id
          @GeneratedValue(strategy = GenerationType.AUTO)
          private Long id;
      
          @ManyToOne
          private Client_Loan client;
      
          public void setPost(Client_Loan post) {
              this.post = post;
          }
      
          public String getReview() {
              return review;
          }
      
          public void setReview(String review) {
              this.review = review;
          }
      }
      
      Now in ClientLoan in OnetoMany mapping cascade = CascadeType.ALL
      it means when you will delete CleintLoan all the LoanDetails will be deleted automatically 
      

      【讨论】:

        猜你喜欢
        • 2010-11-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-21
        • 1970-01-01
        相关资源
        最近更新 更多