我使用的是Hibernate4和Spring3。
Hibernate不是在更新,而是在尝试插入。
我的实体类:
@Entity
@Table(name="APP_SERVER")
public class ServerEntity {
@Id
@GeneratedValue(generator="seq_item", strategy = GenerationType.SEQUENCE)
@SequenceGenerator(name="seq_item",sequenceName="SEQ_APP_SERVER")
@Column(name="APP_SERVER_KEY")
private int app_server_key;
@Column(name="SYS_ID" , unique=true)
private String sys_id;
@Column(name="SERVER_NAME")
private String server_name;
}我的服务类:
@Service("ServerService")
public class ServerServiceImpl implements ServerService{
// other code
@Override
@Transactional
public void addServer(ServerEntity server) {
serverDao.addServer(server);
}
}Dao类:
@Repository("ServerDao")
public class ServerDaoImpl implements ServerDao {
@Override
public void addServer(ServerEntity server) {
try{
this.sessionFactory.getCurrentSession().saveOrUpdate(server);
}catch (Exception e) {
e.printStackTrace();
}
}
}其他类:
ServerEntity serverEntity = new ServerEntity();
serverEntity.setSys_id((result.getSysId()));
serverEntity.setServer_name(result.getName());
ServerService serverService = (ServerService)
applicationContext.getBean("ServerService");
serverService.addServer(serverEntity);表:
CREATE TABLE "APP_SERVER"
( "APP_SERVER_KEY" NUMBER NOT NULL ENABLE,
"CMDB_SYS_ID" VARCHAR2(64) NOT NULL UNIQUE ENABLE ,
"SERVER_NAME" VARCHAR2(255) NOT NULL ENABLE,
PRIMARY KEY ("APP_SERVER_KEY") ENABLE
) ;异常即将到来:
05:36:40,292 INFO [STDOUT] Hibernate: insert into USER.APP_SERVER (SYS_ID,SERVER_NAME) values (?, ?)
05:36:40,558 INFO [STDOUT] WARN : org.hibernate.engine.jdbc.spi.SqlExceptionHelper - SQL Error: 1, SQLState: 23000
05:36:40,558 INFO [STDOUT] ERROR: org.hibernate.engine.jdbc.spi.SqlExceptionHelper - ORA-00001: unique constraint (USER.APP_SERVER_UK1) violated
05:36:40,684 INFO [STDOUT] Exception occured... org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [OIMUSER.SPP_SERVER_UK1]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement这就是为什么hibernate是插入而不是更新。sys_id已经存在于数据库中,这里我希望hibernate更新它,因为sys-id已经存在。
需要进行哪些代码更改。请提个建议。
发布于 2014-07-14 19:00:06
你可以试试这样的东西
Student ss = new Student();
Student get = (Student) s.load(Student.class, new Long(id));
get.setDegree(newDegree);
tx.commit();如果你的对象处于持久化状态,那么加载你的对象的代理并操纵它。操作完成后,提交事务。您的对象将由hibernate自动更新。
发布于 2014-07-14 19:05:09
这可能是因为缺少正确的equals函数,该函数应该基于实体的ID,换句话说,Hibernate不能计算出这是相同的记录
https://stackoverflow.com/questions/24734116
复制相似问题