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
這意味着它無法在品牌表中找到品牌!