如何删除绑定表中的数据?

时间:2014-12-18 14:11:37

标签: java hibernate

我有三张桌子:A,B和AB。 A和B是典型的表,AB - 表绑定它们。例如:

A table
_____________________
int id | varchar data
1       hello


B table
_____________________
int id | varchar data
1       world


AB table
___________________
int a_id | int b_id
1         1

A和B有多对多的关系。有时我应该从A表中删除记录。那也可以从AB中删除绑定记录。但是我该怎么做呢?这是我的努力:

@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinTable(name = "ab", catalog = "mycatalog", joinColumns = { @JoinColumn(name = "a_id", nullable = false, updatable = false) }, inverseJoinColumns = { @JoinColumn(name = "b_id", nullable = false, updatable = false) })
    private Set<B> bs= new HashSet<B>(0);

删除方法:

@Override
    public int remove(int index) {
        Session session = null;
        session = this.sessionFactory.getCurrentSession();
        Query query = session
                .createSQLQuery("DELETE FROM mycatalog.A WHERE id=:id").setInteger(
                        "id", index);
        try {
            return query.executeUpdate();
        } catch (Exception e) {
            return 0;
        }

    }

1 个答案:

答案 0 :(得分:0)

取自:

hibernate-cascade-example-save-update-delete-and-delete-orphan

删除级联

cascade =“delete”在'stockDailyRecords'中声明,以启用删除级联效果。当您删除'Stock'时,其所有引用'stockDailyRecords'将被自动删除。

<!-- Stock.hbm.xml -->
<set name="stockDailyRecords" cascade="delete" table="stock_daily_record" ...>
      <key>
            <column name="STOCK_ID" not-null="true" />
      </key>
      <one-to-many class="com.mkyong.common.StockDailyRecord" />
</set>

代码:

Query q = session.createQuery("from Stock where stockCode = :stockCode ");
q.setParameter("stockCode", "4715");
Stock stock = (Stock)q.list().get(0);
session.delete(stock);

输出:

Hibernate: 
    delete from mkyong.stock_daily_record 
    where DAILY_RECORD_ID=?

Hibernate: 
    delete from mkyong.stock 
    where STOCK_ID=?