Java 使用或在中从数据库加载数据

Java 使用或在中从数据库加载数据,java,jsf-2.2,Java,Jsf 2.2,我要做的是将数据库中的信息显示到数据中,这些信息应该可以编辑 我只有一个.xhtml页面,我希望在该页面中包含所有CRUD操作。 当前项目正在进行插入、选择和删除操作。 谢谢,我们将非常感谢您的帮助 这是.xhtml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xh

我要做的是将数据库中的信息显示到数据中,这些信息应该可以编辑

我只有一个.xhtml页面,我希望在该页面中包含所有CRUD操作。 当前项目正在进行插入、选择和删除操作。 谢谢,我们将非常感谢您的帮助

这是.xhtml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html">
    <h:head>
        <h:outputStylesheet library="css" name="styles.css"/>
        <title>#{msgs.indexTitulo}</title>
    </h:head>

    <h:body>

        <h:messages errorClass="errors" />

        <h:outputText value="#{msgs.indexTitulo}" styleClass="emphasis"/>


        <h:form>
            <h:panelGrid columns="2">
                #{msgs.nombrePlaca}
                <h:inputText id="placa" value="#{vehiculo.placa}" required="true" label="#{msgs.nombrePlaca}" />

                #{msgs.marca}
                <h:inputText value="#{vehiculo.marca}" required="true" label="#{msgs.marca}" />


                #{msgs.modelo}
                <h:inputText value="#{vehiculo.modelo}" required="true" label="#{msgs.modelo}"/>


                #{msgs.color}
                <h:inputText value="#{vehiculo.color}" required="true" label="#{msgs.color}"/>


                #{msgs.campoAgencia}   #{msgs.si}
                <h:selectBooleanCheckbox value="#{vehiculo.agencia}"/>


                #{msgs.anio}
                <h:inputText value="#{vehiculo.anio}" required="true" label="#{msgs.anio}" />
                <br/>


            </h:panelGrid>
            <h:commandButton value="#{msgs.botonSubmit}" action="#{vehiculo.insertVehiculo()}"/>

            <h:button value="Limpiar" type="reset"/>


        </h:form>

        <h:form >

            <!-- -->

            <h:dataTable id="myTable" value="#{vehiculo.seleccionar()}" var="vehiculo">
                <h:column>                  
                    <f:facet name="header">Placa</f:facet>                  
                    #{vehiculo.placa}
                </h:column>
                <h:column>
                    <f:facet name="header">Marca</f:facet>
                    #{vehiculo.marca}
                </h:column>
                <h:column>
                    <f:facet name="header">Modelo</f:facet>
                    #{vehiculo.modelo}
                </h:column>
                <h:column>
                    <f:facet name="header">Color</f:facet>
                    #{vehiculo.color}
                </h:column>

                <h:column>
                    <f:facet name="header">ID</f:facet>
                    #{vehiculo.id}
                </h:column>



                <h:column>
                    <h:commandLink value="Eliminar vehiculo" action="#{vehiculo.eliminarVehiculo(vehiculo.id)}"/>

                </h:column>

                <h:column>

                    <h:commandButton value="Actualizar vehiculo" action="#{vehiculo.seleccionarPorID(vehiculo.id)}" >

                     <f:ajax execute="@form" render="myTable" />


                    </h:commandButton>


                </h:column>
            </h:dataTable>


            <!-- -->



        </h:form>

    </h:body>
</html>
这是豆子

    package beans;

import conexionJDBC.ConexionJDBC;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

@ManagedBean(name = "vehiculo")
@RequestScoped
public class Vehiculo implements Serializable {

    private int id;
    private Integer placa;
    private String marca;
    private String color;
    private Integer anio;
    private String modelo;   //Modelo del carro, ejemplo: Civic
    private boolean agencia; //Si es comprado en agencia

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public Integer getPlaca() {
        return placa;
    }

    public void setPlaca(Integer placa) {
        this.placa = placa;
    }

    public String getMarca() {
        return marca;
    }

    public void setMarca(String marca) {
        this.marca = marca;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public Integer getAnio() {
        return anio;
    }

    public void setAnio(Integer anio) {
        this.anio = anio;
    }

    public String getModelo() {
        return modelo;
    }

    public void setModelo(String modelo) {
        this.modelo = modelo;
    }

    public boolean isAgencia() {
        return agencia;
    }

    public void setAgencia(boolean agencia) {
        this.agencia = agencia;
    }

    /**
     * Default constructor.
     */
    public Vehiculo() {
    }

    public Vehiculo(int id, Integer placa, String marca, String color, Integer anio, String modelo, boolean agencia) {
        this.id = id;
        this.placa = placa;
        this.marca = marca;
        this.color = color;
        this.anio = anio;
        this.modelo = modelo;
        this.agencia = agencia;
    }

    //Metodos para acceder a la BD//
    //INSERT
    public void insertVehiculo() throws SQLException {

        Connection conn = null;
        PreparedStatement pstmt = null;

        ConexionJDBC getConn = new ConexionJDBC();


        try {
            conn = getConn.getConnection();

            String sql = "INSERT INTO vehiculo(placa, marca, color, modelo, anio, agencia) VALUES (?,?,?,?,?,?)";
            pstmt = conn.prepareStatement(sql);


            pstmt.setInt(1, placa);
            pstmt.setString(2, marca);
            pstmt.setString(3, color);
            pstmt.setString(4, modelo);
            pstmt.setInt(5, anio);
            pstmt.setBoolean(6, agencia);


            pstmt.executeUpdate();


        } catch (SQLException e) {
            System.out.println("Exception" + e);
        } finally {
            getConn.closeConnection(conn);
            getConn.closeStatement(pstmt);
        }

    }

    //SELECT
    public List seleccionar() throws SQLException {

        Connection conn = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;

        ConexionJDBC getConn = new ConexionJDBC();


        List<Vehiculo> resultado = new ArrayList();

        try {


            conn = getConn.getConnection();

            String sql = "SELECT * FROM vehiculo";
            pstm = conn.prepareStatement(sql);

            rs = pstm.executeQuery();



            while (rs.next()) {

                Vehiculo vehiculo = new Vehiculo();

                vehiculo.setPlaca(rs.getInt("placa")); //Importante usar las comillas IMPORTANTISIMO
                vehiculo.setMarca(rs.getString("marca"));
                vehiculo.setModelo(rs.getString("modelo"));
                vehiculo.setColor(rs.getString("color"));
                vehiculo.setId(rs.getInt("id"));

                /* Antes se hacia asi:
                 placa = rs.getInt(placa);
                 marca = rs.getString(marca);
                 modelo = rs.getString(modelo);
                 color = rs.getString(color);
                 */
                resultado.add(vehiculo);

            }



        } catch (SQLException e) {
        } finally {
            getConn.closeConnection(conn);
            getConn.closeResultset(rs);
            getConn.closeStatement(pstm);
        }
        return resultado;

    }

    //Eliminar
    public void eliminarVehiculo(int id) throws SQLException {

        Connection conn = null;
        PreparedStatement pstmt = null;

        ConexionJDBC getConn = new ConexionJDBC();

        try {
            String sql = "Delete from vehiculo where id=" + id;

            conn = getConn.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.executeUpdate();


        } catch (Exception ex) {
        } finally {
            getConn.closeConnection(conn);
            getConn.closeStatement(pstmt);
        }

    }

    //UPDATE
    public void actualizarVehiculo(int id) throws SQLException {

        Connection conn = null;
        PreparedStatement pstm = null;
        ConexionJDBC getConn = new ConexionJDBC();

        try {
            conn = getConn.getConnection();

            String sql = "UPDATE vehiculo SET placa=?, marca=?, color=?, modelo=?, anio=?, agencia=? WHERE id=" + id;

            pstm.setInt(1, placa);
            pstm.setString(2, marca);
            pstm.setString(3, color);
            pstm.setString(4, modelo);
            pstm.setInt(5, anio);
            pstm.setBoolean(6, agencia);

            pstm.executeUpdate();

        } catch (SQLException e) {
        } finally {
            getConn.closeConnection(conn);
            getConn.closeStatement(pstm);
        }


    }

    //Select por ID
    public List<Vehiculo> seleccionarPorID(int id) throws SQLException {

        Connection conn = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;

        ConexionJDBC getConn = new ConexionJDBC();

        List<Vehiculo> resultado = new ArrayList();


        try {

            conn = getConn.getConnection();

            String sql = "Select * from vehiculo where id=" + id;
            pstm = conn.prepareStatement(sql);

            rs = pstm.executeQuery();

            while (rs.next()) {
                Vehiculo vehiculo = new Vehiculo();

                vehiculo.setId(rs.getInt("id"));
                vehiculo.setPlaca(rs.getInt("placa")); //Importante usar las comillas IMPORTANTISIMO
                vehiculo.setMarca(rs.getString("marca"));
                vehiculo.setModelo(rs.getString("modelo"));
                vehiculo.setColor(rs.getString("color"));
                vehiculo.setId(rs.getInt("id"));

                resultado.add(vehiculo);
            }


        } catch (SQLException e) {
        } finally {
            getConn.closeConnection(conn);
            getConn.closeResultset(rs);
            getConn.closeStatement(pstm);
        }

        return resultado;

    }
}

我认为本教程对您非常有用。使用JSF的2个简单CRUD web应用程序:


我认为你有两个错误: 1.SeleccialPorId应返回字符串,而不是列表。
2.您应该编写方法GetSelecionar,它将返回List或Vehiculo[]。

谢谢您,RaSh,谢谢您,dansouza

我找到了一种用从数据库中获取的值填充的方法,非常简单

只需在ManagedBean中创建一个方法:

 //Fill the inputText with values
    public void loadFields(int id, int placa, String marca, String modelo, String color, boolean agencia, int anio) {

        //Filling values into the form

        setId(id);
        setMarca(marca);
        setPlaca(placa);
        setModelo(modelo);
        setColor(color);
        setAgencia(agencia);
        setAnio(anio);
    }
然后在.xhtml页面中:

 <h:commandButton value="Actualizar vehiculo" action="#{vehiculoMB.cargarCampos(vehi.id, vehi.placa, vehi.marca, vehi.modelo, vehi.color, vehi.agencia, vehi.anio)}"  >

                    </h:commandButton>
我知道这不是一个最佳实践,但我正在学习JSF


希望这对任何需要它的人都有帮助。

您有什么问题?如何使用或从数据库中加载数据?