如何将数据从 xhtml 表单插入到 netbeans 中的 Java 数据库?

How can I insert data from an xhtml form to a Java DB in netbeans?

我想使用 netbeans 和 java 数据库将表单中的数据输入到数据库中。我的问题是我不知道如何将用户在表单中输入的数据传递给数据库。

我已经尝试创建一个实体 class 并通过它连接它,但是根据我所遵循的指南,我最终可以访问整个数据库而不仅仅是表单

编辑:这是一个学校项目,我还没有被教过 JDBC,至少现在是这样。


<?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:h="http://xmlns.jcp.org/jsf/html"
      xmlns:f="http://xmlns.jcp.org/jsf/core">
    <h:head>
        <title>Registration</title>
        <h:outputStylesheet name="css/jsfcrud.css"/>
        <h:outputStylesheet library="css" name="styles.css"/>
    </h:head>
    <h:body>
        <h3>Registration Page</h3>
        <h:form>
            <h:panelGrid columns="3"
                         columnClasses="rightalign,leftalign,leftali
                         gn">
                <h:outputLabel value="Category: " for="category"/>
                <h:selectOneMenu id="category" label="Category"
                                 value="#{registrationBean.
                                          category}" >
                    <f:selectItem itemLabel="Simple." itemValue="Simple"/>
                    <f:selectItem itemLabel="Suite." itemValue="Suite"/>
                    <f:selectItem itemLabel="Luxurious" itemValue="Luxurious"/>
                </h:selectOneMenu>
                <h:message for="category"/>
                <h:outputLabel value="People: " for="people"/>
                <h:selectOneMenu id="people" label="People"
                                 value="#{registrationBean.
                                          people}" >
                    <f:selectItem itemLabel="Mr." itemValue="1"/>
                    <f:selectItem itemLabel="Mrs." itemValue="2"/>
                    <f:selectItem itemLabel="Miss" itemValue="3"/>
                    <f:selectItem itemLabel="Miss" itemValue="4"/>
                </h:selectOneMenu>
                <h:message for="people"/>
                <h:outputLabel value="Duration:" for="duration"/>
                <h:inputText id="duration" label="Duration"
                             required="true"
                             value="#{registrationBean.duration}" />

                <h:message for="duration" />
                <h:panelGroup/>
                <h:commandButton id="register" value="Register"
                                 action="confirmation" />
            </h:panelGrid>
        </h:form>
        <br />
        <h:link outcome="/room/List" value="Show All Room Items"/>
    </h:body>

</html>

@Entity
public class Room implements Serializable {

    @Id
    @Basic(optional = false)
    @NotNull
    @Column(nullable = false)
    private Integer id;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 20)
    @Column(nullable = false, length = 20)
    private String category;
    @Basic(optional = false)
    @NotNull
    @Column(nullable = false)
    private int people;
    @Basic(optional = false)
    @NotNull
    @Column(nullable = false)
    private int duration;

    private static final long serialVersionUID = 1L;
    @Id

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }

    public Integer getPeople() {
        return people;
    }

    public void setPeople(Integer people) {
        this.people = people;
    }

    public Integer getDuration() {
        return duration;
    }

    public void setDuration(Integer duration) {
        this.duration = duration;
    }

    public Integer getId() {
        return id;
    }

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

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Room)) {
            return false;
        }
        Room other = (Room) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.ensode.jsf.hotelreservations.Room[ id=" + id + " ]";
    }

    public Room() {
    }

    public Room(Integer id) {
        this.id = id;
    }

    public Room(Integer id, String category, int people, int duration) {
        this.id = id;
        this.category = category;
        this.people = people;
        this.duration = duration;
    }


}

public class RoomJpaController implements Serializable {

    public RoomJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Room room) throws RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            em.persist(room);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Room room) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            room = em.merge(room);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = room.getId();
                if (findRoom(id) == null) {
                    throw new NonexistentEntityException("The room with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Long id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Room room;
            try {
                room = em.getReference(Room.class, id);
                room.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The room with id " + id + " no longer exists.", enfe);
            }
            em.remove(room);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Room> findRoomEntities() {
        return findRoomEntities(true, -1, -1);
    }

    public List<Room> findRoomEntities(int maxResults, int firstResult) {
        return findRoomEntities(false, maxResults, firstResult);
    }

    private List<Room> findRoomEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Room.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Room findRoom(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Room.class, id);
        } finally {
            em.close();
        }
    }

    public int getRoomCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Room> rt = cq.from(Room.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}

这是persistance.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
  <persistence-unit name="HotelReservationsPU" transaction-type="JTA">
    <jta-data-source>java:app/roomintro</jta-data-source>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties>
      <property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
    </properties>
  </persistence-unit>
</persistence>

结果是表单在工作时不会在数据库中插入任何数据。

亲爱的 Harrys Lorentzatos:

在正常的 java 项目中,为了将数据存储在数据库中,您使用 Hibernate 或其他实现 JPA 规范的框架。

通常你会使用 maven 项目,在 pom.xml 文件中你有一些像这样的休眠依赖项:

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>${hibernate.core.version}</version>
    </dependency>

通常你存储整个对象

您在此处输入的代码:

    utx.begin();
    em = getEntityManager();
    em.persist(room);
    utx.commit(); 

看起来您正在使用一些 JPA 实现。 但是为了了解您的问题将有助于查看 pom.xml 或 hibernate.properties.

等配置文件

您可以上传完整的代码以便更好地理解。 Y 与您分享一些我学习 Hibernate 并将数据存储在 mysql 数据库中的项目 https://github.com/marianocali/concesionario

这是一个使用 Hibernate 的项目的简单示例,您可以在其中看到与您的项目类似的所有配置代码。

文件 persistence.xml 在您的 java 类 和数据库中的表之间创建映射。

已编辑: 您的 persistence.xml 文件必须包含有关数据库连接的信息: 看看这两个例子:https://github.com/marianocali/concesionario/blob/master/src/main/resources/META-INF/persistence.xml

https://gist.github.com/halyph/2990769

您必须在文件中添加所有这些信息。

如果这对您有帮助,请为答案投票:) 如果您需要更多帮助,请告诉我
问候。
马里亚诺