[英]Hibernate Update giving java.lang.NullPointerException
I am trying the below code . 我正在尝试下面的代码。 Basically I am trying to update a row in database table through Hibernate.
基本上我想通过Hibernate更新数据库表中的一行。
ABCEntity obj = new ABCEntity ();
obj.setMetal(MetalEnum.valueOf(metal));
obj.setName(smelter_name);
obj.setSmelterId(smelter_id);
obj.setReferenceName(smelter_name);
obj.setId((long) 117806);
try {
// Saving in Known Smelter Table
Transaction tx = sessionFactory.getCurrentSession().beginTransaction();
sessionFactory.getCurrentSession().update(obj);
tx.commit();
} catch (Exception e) {
logger.info("Print object "+ obj.toString());
logger.info("Error for update: "+ e.getMessage());
}
So tracing the error log I am getting : 因此,我正在跟踪错误日志:
Print object ABCEntity@447a43f7[
id=117806
name=XYZ SMELTER
smelterId=ABC001
metal=METAL_A
referenceName=XYZ SMELTER
nextSteps=<null>
mineNames=<null>
mineLocation=<null>
comments=<null>
]
and 和
Error for update: null
What is the mistake here . 这是怎么回事。
you could try this sequence for updating a row in database using hibernate 您可以尝试使用以下顺序使用休眠模式更新数据库中的行
1st get the row you want to update, you can have a findByID() method 第一个获取要更新的行,可以有一个findByID()方法
using criteria 使用标准
public ABCEntity findById(Integer id) {
// TODO Auto-generated method stub
try {
ABCEntity instance = (ABCEntity) getSession()
.createCriteria(ABCEntity.class)
.add(Restrictions.eq(IDABCENTITY, id)).uniqueResult();
return instance;
} catch (RuntimeException re) {
throw re;
}
}
using hql 使用hql
public ABCEntity findById(Integer id) {
// TODO Auto-generated method stub
try {
ABCEntity instance = (ABCEntity) getSession().get(
"packageofclass.ABCEntity", id);
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
then reference the object 然后引用对象
ABCEntity obj = findById(1);
2nd is to update what field should be change, for example i want to change the name 第二是更新应更改的字段,例如我想更改名称
obj.setName("new name");
then to update the row you can do this 然后更新行,您可以执行此操作
public void update(ABCEntity transientInstance) {
// TODO Auto-generated method stub
try {
getSession().saveOrUpdate(transientInstance);
return transientInstance;
} catch (RuntimeException re) {
re.printStackTrace();
return null;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.