Hibernate外键插入不起作用

时间:2015-04-03 22:16:51

标签: java mysql hibernate

我想使用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

这意味着它无法在品牌表中找到品牌!

1 个答案:

答案 0 :(得分:2)

我想我已经理解了我曾经面对过这个原因的原因 错误告诉你一切。您的专栏brand_id没有默认值。
因此在插入期间,DB无法确定要插入的内容。 现在你有三个选择:
1.使用 -

为brand_id列添加默认值
ALTER TABLE `xxx` ALTER `brand_id` SET DEFAULT NULL
  1. 在插入期间向supplier_id列提供一些值。不是最好的事情,但需要付出努力,但取决于方案。如果选择此选项,请将生成器类设为已分配。

  2. 向列添加自动增量,并使用代码向其添加主键。我认为这对你有好处,但请重新检查: -

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


  3. 希望这会有所帮助..