2015-04-03 116 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;


  • 希望这有助于..