【问题标题】:Can anyone help me with this drawback with Hibernate and JSF?任何人都可以帮助我解决 Hibernate 和 JSF 的这个缺点吗?
【发布时间】:2017-04-07 14:43:07
【问题描述】:

我在更新表中的某些数据时遇到了 Hibernate 问题。

如果我生成一条新记录,它就成功记录在表中。但是,如果我想做的是更新主键,如果托管 bean 的范围是“RequestScoped”,我会抛出以下错误: "批量更新从更新 [0] 返回了意外的行数;当前行数:0;预期:1"

如果托管bean的范围是“ViewScoped”,则报错如下: “无法提取结果集”。

如果我修改的是其他数据,则记录记录满意。

我知道修改主键可能是权限问题,因为这又是另一个表的外键,但最后一个表还不包含记录。 如果我从 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>

【问题讨论】:

  • 你能添加你用来执行更新的代码吗?如果您尝试使用普通 JPA 来更新主键,您可能无法做到。但是,您可以使用查询来执行此操作,如 here 所示。但是,您应该重新评估这是否是您真正想做的事情。通常,主键的全部目的是它不应该改变。
  • @DanielBickler:伙计,我已经上传了托管 Bean 代码和部分视图。我理解你告诉我的关于主键的设计是不能改变的,但是尝试,看到我被允许在 Postgres 的基础上而不是在视图中更改主键,我提出了疑问。通过谷歌搜索,我发现没有任何解释可以让我满意。

标签: java hibernate jsf primefaces postgresql-9.3


【解决方案1】:

虽然您可能会发现某些平台允许更改表行的主键值,但对于任何符合关系的数据库而言,这通常是不可接受的做法。

修改行的 PK 值的公认方法是首先禁用或删除拥有该行的表上的 PK。这可能会导致任何其他具有 FK 约束的表也可能必须在之前更改以禁用或删除 FK。完成后,您可以对 PK 或其值进行任何必要的更改,而不会出现任何数据库问题。完成更改后,您需要重新添加或启用 PK,然后是关联的 FK。

这只是关系数据库的本质,它与 Hibernate 没有任何关系。

我相信(我必须仔细检查代码是否绝对)Hibernate 默认指定 PK 列是 insertable=true, updatable=false。换句话说,它假定关系合规性,除非发生如上所述的一些手动工作,否则 PK 不会改变。

因此,即使您尝试修改 java 代码中的值,Hibernate 也会默默地忽略您的列更新,因此您看到的错误就是这样的结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-03
    • 1970-01-01
    • 2022-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-03
    • 1970-01-01
    相关资源
    最近更新 更多