我正在使用Hibernate4和Spring 3。
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);
}
}
道上课:
@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已经存在时更新它。
需要更改代码。请建议。
答案 0 :(得分:0)
您可以尝试这样的事情
Student ss = new Student();
Student get = (Student) s.load(Student.class, new Long(id));
get.setDegree(newDegree);
tx.commit();
如果您的对象处于持久状态,则加载对象的代理&操纵它。一旦完成操作,就提交事务。您的对象由hibernate自动更新。
答案 1 :(得分:0)
这可能是错误的正确的等于函数,它应该基于你的实体的ID,换句话说,Hibernate不能算出那是同一个记录