休眠多对多的双向存储

时间:2013-12-25 05:26:50

标签: java mysql sql hibernate

我跟随了mkyong

中的Mkyong(多对多示例 - 连接表+额外列)

当我运行应用程序时,我能够存储多对多的值

从库存中进行多对多的双向存储:

session.beginTransaction();

Category category1 = new Category("CONSUMER", "CONSUMER COMPANY");
//new category, need save to get the id first
session.save(category1);

Stock stock = new Stock();
stock.setStockCode("7052");
stock.setStockName("PADINI");

StockCategory stockCategory = new StockCategory();

stockCategory.setStock(stock);
stockCategory.setCategory(category1);
stockCategory.setCreatedDate(new Date());
stockCategory.setCreatedBy("system");

stock.getStockCategories().add(stockCategory);

session.save(stock);

session.getTransaction().commit();
  

它存储类别并将其ID用于Stock。它插入   三张桌子。很好..它生成sql如下

Hibernate: 
    insert 
    into
        hibernateLearning.category
        (`DESC`, NAME) 
    values
        (?, ?)

Hibernate: 
    insert 
    into
        hibernateLearning.stock
        (STOCK_CODE, STOCK_NAME) 
    values
        (?, ?)

Hibernate: 
    insert 
    into
        hibernateLearning.stock_category
        (CREATED_BY, CREATED_DATE, CATEGORY_ID, STOCK_ID) 
    values
        (?, ?, ?, ?)

许多从类别中存储的双向:

我修改了代码,并尝试按类别存储类别中的股票值:

session.beginTransaction();
// Saved the Stock first
Stock stock = new Stock();
stock.setStockCode("7052");
stock.setStockName("PADINI");
session.save(stock);

// Saving the Category with Stock
Category category1 = new Category("CONSUMER1", "CONSUMER COMPANY");
StockCategory stockCategory = new StockCategory();
stockCategory.setStock(stock);
stockCategory.setCategory(category1);
stockCategory.setCreatedDate(new Date());
stockCategory.setCreatedBy("system");

category1.getStockCategories().add(stockCategory);
session.save(category1);

session.getTransaction().commit();

此代码会生成以下查询:

Hibernate: 
    insert 
    into
        hibernateLearning.stock
        (STOCK_CODE, STOCK_NAME) 
    values
        (?, ?)


Hibernate: 
    insert 
    into
        hibernateLearning.category
        (`DESC`, NAME) 
    values
        (?, ?)

我首先保存库存并将其用于类别。此代码创建两个表并插入值。但缺少连接表(StockCategory)。 我想知道这段代码我错在哪里?

1 个答案:

答案 0 :(得分:0)

错误的是您只修改双向关联的一侧,而在第二个示例中,修改的一侧是反面(即具有mappedBy属性的一侧)。 Hibernate忽略了反面。对于Hibernate来说最重要的是业主方面。因此,正常并期望不保存关联。