在更新表格中的某些数据时,我遇到了Hibernate的问题。
如果我生成新记录,则会在表格中成功记录。但是,如果我想要做的是执行主键的更新,如果托管bean的范围是“RequestScoped”,则抛出以下错误: “批量更新从更新[0]返回意外行数;当前行数:0;预期:1 ”
如果托管bean的范围是“ViewScoped”,则错误如下: “无法提取ResultSet ”。
如果我修改的是另一个数据,记录将被令人满意地记录下来。
我理解修改主键可能是权限问题,因为这又是来自另一个表的外键,但最后一个表还没有包含记录。 如果从pgAdmin我更改主键,我可以毫无问题地执行它,因此它不是参照完整性问题。
这让我很困惑。
我添加了POJO代码:
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
/**
* Combustibles generated by hbm2java
*/
public class Combustibles implements java.io.Serializable {
private int idcombustible;
private String descripcion;
private boolean baja;
private Date fechabaja;
private Set valeses = new HashSet(0);
public Combustibles() {
}
public Combustibles(int idcombustible, String descripcion, boolean baja) {
this.idcombustible = idcombustible;
this.descripcion = descripcion;
this.baja = baja;
}
public Combustibles(int idcombustible, String descripcion, boolean baja, Date fechabaja, Set valeses) {
this.idcombustible = idcombustible;
this.descripcion = descripcion;
this.baja = baja;
this.fechabaja = fechabaja;
this.valeses = valeses;
}
public int getIdcombustible() {
return this.idcombustible;
}
public void setIdcombustible(int idcombustible) {
this.idcombustible = idcombustible;
}
public String getDescripcion() {
return this.descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public boolean isBaja() {
return this.baja;
}
public void setBaja(boolean baja) {
this.baja = baja;
}
public Date getFechabaja() {
return this.fechabaja;
}
public void setFechabaja(Date fechabaja) {
this.fechabaja = fechabaja;
}
public Set getValeses() {
return this.valeses;
}
public void setValeses(Set valeses) {
this.valeses = valeses;
}
}
同样来自映射文件:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated 24/03/2017 21:42:13 by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
<class name="Pojos.Combustibles" table="combustibles" schema="public" optimistic-lock="version">
<id name="idcombustible" type="int">
<column name="idcombustible" />
<generator class="assigned" />
</id>
<property name="descripcion" type="string">
<column name="descripcion" not-null="true" />
</property>
<property name="baja" type="boolean">
<column name="baja" not-null="true" />
</property>
<property name="fechabaja" type="time">
<column name="fechabaja" length="15" />
</property>
<set name="valeses" table="vales" inverse="true" lazy="true" fetch="select">
<key>
<column name="idcombustible" not-null="true" />
</key>
<one-to-many class="Pojos.Vales" />
</set>
</class>
</hibernate-mapping>
我添加了Managed Bean的代码,里面是名为 modifyCombustible()的方法,负责更新。
package ManagedBeansRequest;
import Daos.DaoCombustibles;
import HibernateUtil.HibernateUtil;
import Pojos.Combustibles;
import java.util.List;
import javax.inject.Named;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import org.hibernate.Session;
import org.hibernate.Transaction;
/**
*
* @author Gustavo
*/
@Named(value = "mbCombustibles")
@RequestScoped
public class MbCombustibles {
private Combustibles combustible;
private List<Combustibles> listaCombustibles;
private Session sesion;
private Transaction transaccion;
/**
* Creates a new instance of MbCombustibles
*/
public MbCombustibles() {
this.combustible = new Combustibles();
}
public void registrar() throws Exception{
//Antes era public String, pero se cambió a "void" ya que en la vista se cambió el "action" que requiere una cadena, por "actionListener"
this.sesion = null;
this.transaccion = null;
try{
this.sesion = HibernateUtil.getSessionFactory().openSession();
this.transaccion = this.sesion.beginTransaction();
DaoCombustibles daoC = new DaoCombustibles();
daoC.registrar(this.sesion, this.combustible);
this.transaccion.commit();
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Registro","Se registró satisfactoriamente el combustible"));
//RequestContext.getCurrentInstance().execute("limpiarFormulario('frmRegistrarCombustible')");
this.combustible = new Combustibles(); //Esto reemplaza a la función javascript de borrado de campos del formulario, debido a que al instanciar un nuevo objeto, viene con sus atributos limpios
//return "/combustibles/combustiblealta"; //Se reemplaza el return, ya que en la vista se cambió el "action" que requiere una cadena, por "actionListener"
}catch(Exception e){
if(this.transaccion != null){
this.transaccion.rollback();
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Ocurrió un error","Descripcion: " + e.getMessage()));
}
return; //Se reemplaza el return "null", ya que en la vista se cambió el "action" que requiere una cadena, por "actionListener"
}
finally{
if(sesion != null){
sesion.close();
}
}
}
public List<Combustibles> getTodos(){
this.sesion = null;
this.transaccion = null;
try{
DaoCombustibles daoC = new DaoCombustibles();
this.sesion = HibernateUtil.getSessionFactory().openSession();
this.transaccion = this.sesion.beginTransaction();
this.listaCombustibles = daoC.verTodos(this.sesion);
this.transaccion.commit();
return listaCombustibles;
}catch(Exception e){
if(this.transaccion != null){
this.transaccion.rollback();
}
return null;
}finally{
if(this.sesion != null){
this.sesion.close();
}
}
}
public void modificarCombustible() throws Exception{
//Antes era public String, pero se cambió a "void" ya que en la vista se cambió el "action" que requiere una cadena, por "actionListener"
this.sesion = null;
this.transaccion = null;
try{
this.sesion = HibernateUtil.getSessionFactory().openSession();
this.transaccion = this.sesion.beginTransaction();
DaoCombustibles daoC = new DaoCombustibles();
daoC.modificar(this.sesion, this.combustible);
this.transaccion.commit();
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Registro","Se guardaron satisfactoriamente los cambios"));
//RequestContext.getCurrentInstance().execute("limpiarFormulario('frmRegistrarCombustible')");
//this.combustible = new Combustibles(); //Esto reemplaza a la función javascript de borrado de campos del formulario, debido a que al instanciar un nuevo objeto, viene con sus atributos limpios
//return "/combustibles/combustiblealta"; //Se reemplaza el return, ya que en la vista se cambió el "action" que requiere una cadena, por "actionListener"
}catch(Exception e){
if(this.transaccion != null){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Ocurrió un error","Descripcion: " + e.getMessage()));
this.transaccion.rollback();
}
}
finally{
if(sesion != null){
sesion.close();
}
}
}
public Combustibles getCombustible() {
return combustible;
}
public void setCombustible(Combustibles combustible) {
this.combustible = combustible;
}
public List<Combustibles> getListaCombustibles() {
return listaCombustibles;
}
public void setListaCombustibles(List<Combustibles> listaCombustibles) {
this.listaCombustibles = listaCombustibles;
}
}
为了清楚起见,我还添加了视图的代码部分,从我调用PrimeFaces的对话框,以及对话框的完整代码:
<p:column>
<p:commandButton value="Editar" oncomplete="PF('dialogoEditarCombustible').show()" update=":frmEditarCombustible">
<f:setPropertyActionListener target="#{mbCombustibles.combustible}" value="#{fila}"/>
</p:commandButton>
</p:column>
<h:form id="frmEditarCombustible">
<p:dialog header="Editar Combustible" widgetVar="dialogoEditarCombustible" modal="true" resizable="false" width="900" showEffect="explode" hideEffect="explode" >
<p:panelGrid id="editarCombustible" columns="3">
<p:outputLabel value="Identificador de Combustible:" for="txtIdentificador"/>
<p:inputText id="txtIdentificador" label="Identificador" value="#{mbCombustibles.combustible.idcombustible}">
<f:validator validatorId="validadorVacio"/>
</p:inputText>
<p:message for="txtIdentificador"/>
<p:outputLabel value="Nombre de combustible:" for="txtDescripcion"/>
<p:inputText id="txtDescripcion" label="Nombre" value="#{mbCombustibles.combustible.descripcion}">
<f:validator validatorId="validadorVacio"/>
</p:inputText>
<p:message for="txtDescripcion"/>
<p:commandButton value="Confirmar Edición" actionListener="#{mbCombustibles.modificarCombustible()}" update=":frmListaCombustibles,editarCombustible"/>
</p:panelGrid>
</p:dialog>
</h:form>
答案 0 :(得分:2)
虽然您可能会发现某些平台允许更改表行的主键值,但对于任何符合关系的数据库而言,这通常是不可接受的做法。
修改行的PK值的可接受方法是首先禁用或删除拥有该行的表上的PK。这可能导致具有FK约束的任何其他表可能也必须被改变以在之前禁用或丢弃FK。完成后,您可以对PK或其值进行必要的更改,而不会出现任何数据库问题。完成更改后,您需要重新添加或启用PK,然后再关联相关的FK。
这只是一个关系数据库的本质,它具有 nothing 来专门用于Hibernate。
我相信(我必须仔细检查代码是绝对的)Hibernate默认指定PK列为insertable=true, updatable=false
。换句话说,它假设关系符合性,PK不会改变,除非如上所述发生一些手工工作。
因此,即使您尝试修改java代码中的值,Hibernate也会默默地忽略您的列更新,因此您看到的错误就是这样的结果。