2015-04-03 119 views
1

我想使用Hibernate在product表中插入一些產品。休眠外鍵插入不起作用

CREATE TABLE `product` (
    `id` int(10) unsigned NOT NULL AUTO_INCREMENT, 
    `name` varchar(60) NOT NULL, 
    `brand_id` int(10) unsigned NOT NULL, 
    `category_id` int(10) unsigned NOT NULL, 
    `info` varchar(100) NOT NULL, 
    `fullname` varchar(100) NOT NULL, 
    PRIMARY KEY (`id`), 
    KEY `FK_product_2_idx` (`category_id`), 
    KEY `FK_product_1_idx` (`brand_id`), 
    CONSTRAINT `FK_product_1` FOREIGN KEY (`brand_id`) REFERENCES `brand` (`id`), 
    CONSTRAINT `FK_product_2` FOREIGN KEY (`category_id`) REFERENCES `category` (`id`) ON DELETE CASCADE ON UPDATE CASCADE 
) ENGINE=InnoDB AUTO_INCREMENT=1315 DEFAULT CHARSET=latin1 

以上是我的產品表。爲brandcategory這樣我第一次查詢:

public Brand getMyBrand(){ 
    Session session = factory.openSession(); 
    Transaction tx = null; 
    Brand result = null; 
    try { 
     tx = session.beginTransaction(); 
     Query hql = session.createQuery 
       ("FROM Brand B WHERE B.name= :name"); 
     hql.setParameter("name", "unknown"); 
     result = (Brand) hql.uniqueResult(); 
     tx.commit(); 
    } catch (HibernateException e) { 
     if (tx != null) tx.rollback(); 
     e.printStackTrace(); 
    } finally { 
     session.close(); 
     return result; 
    } 
} 

然後我用這段代碼保存產品:

public int testInsert(){ 
    Product product = new Product(getUnknownCategory(),getUnknownBrand() 
      ,"test1","test1","test1"); 
    return insertSingleProduct(product); 
} 

public int insertSingleProduct(Product product){ 
    Session session = factory.openSession(); 
    Transaction tx = null; 
    int result = -1; 
    try { 
     tx = session.beginTransaction(); 
     result = (Integer) session.save(product); 
     tx.commit(); 
    } catch (HibernateException e) { 
     if (tx != null) tx.rollback(); 
     e.printStackTrace(); 
    } finally { 
     session.close(); 
     return result; 
    } 
} 

但我結束了以下錯誤:

Caused by: java.sql.SQLException: Field 'brand_id' doesn't have a default value 

這意味着它無法在品牌表中找到品牌!

回答

2

我想我已經明白了原因,因爲我曾經遇到過這個。
錯誤告訴你一切。您的品牌brand_id沒有默認值。
所以插入過程中DB不能夠計算插入的.. 現在,你有三種選擇:
1.添加一個默認值列brand_id使用 -

ALTER TABLE `xxx` ALTER `brand_id` SET DEFAULT NULL 
  • 在插入期間爲supplier_id列提供一些值。不需要努力,但取決於場景。如果您選擇此項,請將生成器類設爲分配。

  • 向該列添加自動增量,並使用該代碼向其添加主鍵。我認爲這對你有好處,但請重新檢查: -

    ALTER TABLE xxx CHANGE brand_idbrand_id INT(10)AUTO_INCREMENT PRIMARY KEY;


  • 希望這有助於..