如何使用Hibernate在表中插入新行?

时间:2019-03-06 20:04:10

标签: java mysql database hibernate

我试图了解JPA / Hibernate,能够创建新数据库,但不了解如何在我的数据库中插入新行 数据库。 这是代码:

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Person implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;
    private String adress;
    private String phoneNumber;

    public void setName(String name) {
        this.name = name;
    }

    public void setAdress(String adress) {
        this.adress = adress;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    public String getName() {
        return name;
    }

    public String getAdress() {
        return adress;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long 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 Person)) {
            return false;
        }
        Person other = (Person) 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 "entinty.Person[ id=" + id + " ]";
    }


}

创建数据库的类为:

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

public class Main {

    public static void main(String args[]) {

        Person p = new Person();
        p.setName("xxx");
        p.setAdress("yyy");
        p.setPhoneNumber("zzz");
        EntityManagerFactory emf = javax.persistence.Persistence.createEntityManagerFactory("testPU");
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        try {
            em.persist(p);
            em.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
            em.getTransaction().rollback();
        }

        em.close();
        emf.close();



    }

}

在这一点上,我有一张有一行的表(写为“ xxx-yyy-zzz”)。如何添加新行?创建新的Person不起作用,因为它创建了新表...我只能使用Session和SessionFactory找到解决方案,但是我无法使用它,因为我无法理解如何生成hibernate.cfg.xml(在一般如何创建会话对象)。 是否有仅使用EntityManager的解决方案?或者如何生成/编写hibernate.cfg.xml文件?有没有办法使用Netbeans自动生成它?

编辑:这是我的persistence.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="testPU" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <class>test.Person</class>
    <properties>
      <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/stackoverflow?zeroDateTimeBehavior=convertToNull"/>
      <property name="javax.persistence.jdbc.user" value="root"/>
      <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
      <property name="javax.persistence.jdbc.password" value="leonida95."/>
      <property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
      <property name="javax.persistence.schema-generation.database.action" value="create"/>
    *****
    </properties>
  </persistence-unit>
</persistence>

1 个答案:

答案 0 :(得分:0)

持久性单元文件中,您将拥有类似

的内容
<properties>
   <property name="hibernate.connection.url" value="..." />
   <property name="hibernate.connection.driver_class" value="..."/>
   ...
</properties>

要在构建EntityManagerFactory时创建表,只需添加

<property name="hibernate.hbm2ddl.auto" value="create" />

您的代码可以正常工作。
您可以根据需要多次调用persist,它将向目标表中添加行。

em.persist(person1);
em.persist(person2);
...

persist不会创建表格。