保持实体并将其保存为插入文件

时间:2016-11-02 20:11:17

标签: java hibernate jpa hsqldb

我正在使用HSQLDB(2.3.4)和Hibernate JPA(2.0)来创建和更新实体(Customer)。我的实体Customer使用@Entity注释,ID标注为

@Id
@GenericGenerator(name = "genCustomer", strategy = "increment")    
@GeneratedValue(generator = "genCustomer")`

我创建和更新客户的代码如下:

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

public class HibernateCustomerTest {
private static EntityManager em;

public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("hsqldb-ds");
em = emf.createEntityManager();

EntityTransaction transaction = em.getTransaction();

transaction.begin();

Customer found = em.find(Customer.class, 

System.out.println(found); // null

Customer customer1 = new Customer();

em.persist(customer1);
transaction.commit();
customer1.setCompany("asdfegj");
transaction.begin();
em.merge(customer1);
transaction.commit();
customer1 = em.find(Customer.class, 1L);
System.out.println(customer1.getCompany());

em.close();
}

}

实际上,这非常有效。期望的输出确实是asdfegj

如果我试图找到创建的实体。它总是导致null。缺少什么?

我在file mode中使用HSQLDB。与<property name="hibernate.hbm2ddl.auto" value="update" />。 +

我的persistence.xml看起来像是:

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="hsqldb-ds" transaction-type="RESOURCE_LOCAL">

    <description>HSQLDB Persistence Unit</description>
    <provider>org.hibernate.ejb.HibernatePersistence</provider>

    <class>de.example.model.Customer</class>

    <properties>
        <property name="javax.persistence.jdbc.driver" value="org.hsqldb.jdbcDriver" />
        <property name="javax.persistence.jdbc.url" value="jdbc:hsqldb:file:data/rechnungen" />
        <property name="javax.persistence.jdbc.user" value="sa" />
        <property name="javax.persistence.jdbc.password" value="" />
        <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect" />
        <property name="hibernate.hbm2ddl.auto" value="update"  />
        <property name="hibernate.show_sql" value="true" />
        <property name="hibernate.format_sql" value="true" />
        <property name="hibernate.transaction.flush_before_completion"
            value="true" />
    </properties>
</persistence-unit>

如何使用Java代码创建实体并将这些表和其他语句的SQL存储到.script文件中。

澄清我的意愿:

因此,当我执行一次代码时,应该创建表(如果它当然不存在),并且实体应该被持久化并更新。

当我第二次执行代码时,我在第一次执行中创建的实体仍然存在。

0 个答案:

没有答案