如何使用休眠模式

时间:2018-10-05 11:45:34

标签: postgresql hibernate

我是Hibernate的新手, 我想在一个表上执行删除操作,将当前表引用到另一个表上。

Ex:Client_Loan是我要对此进行删除的主表,另一个表是“ Loan_Details”。 loan_details表包含对client_loan ID的foreign_Key引用。

我想对client_loan表执行删除,如果我删除客户贷款表,则另一个表中的引用也想使用Hibernate一次删除,任何人都可以告诉我如何执行。 预先感谢。

2 个答案:

答案 0 :(得分:0)

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 

答案 1 :(得分:0)

首先从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();