Transaction not successfully started 异常的解决
static void count()
{
Session session = sessionFactory.openSession();
Transaction tran = session.beginTransaction();//此处开启了事务处理
Query query = session.createQuery(" from Product");
List<Product> list = query.list();
try
{
for (Product p : list)
{
// 输出测试
System.out.println("name:" + p.getName());
ProductType type = p.getType();
// 输出测试
System.out.println("name:" + type.getName());
type.setCount(type.getCount() + 1);
// 更新类型的数量
session.update(type);
ProductType parent = type.getParents();
while (parent != null)
{
// 输出测试
System.out.println("name:" + parent.getName());
parent.setCount(parent.getCount() + 1);
// 更新类型的数量
session.update(type);
parent = parent.getParents();
}
//tran.commit();在此处提交了事务
}
tran.commit();
} catch (Exception e)
{
if (tran != null)
{
tran.rollback();
}
}
finally
{
session.close();
}
}
太粗心大意了,刚开始使用Hibernate还是不太熟练。O(∩_∩)O~