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
以上是我的产品表。为brand
和category
这样我第一次查询:
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
这意味着它无法在品牌表中找到品牌!