我想在独立应用中使用 hibernate 和嵌入式derby ,我有一些问题:
如果您还可以建议我使用这种方法的一些好的教程,那么请提前感谢。
答案 0 :(得分:31)
我使用Apache Derby和Hibernate来测试我项目的一个模型类(他们的等于, hashCode 实现,查询等)。 MySQL用作生产数据库。我选择Derby而不是HSQLDB,因为我遇到了一些与Hibernate和HSQLDB不兼容的问题,这意味着,鉴于我的实体(他们的名字,模式,密钥)及其关系,Hibernate无法在HSQLDB中创建我的数据库模式,虽然它可以与德比。那就是说,也许我搞砸了什么;也可以解决不兼容问题。
无论如何,这是我在测试中使用的内容(我修改了我的pom.xml
,以便它将Derby作为运行时依赖项并运行单个测试,只是为了制作确定它有效。)
pom.xml
<dependencies>
...
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.6.8.Final</version>
</dependency>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
<version>10.8.2.2</version>
<scope>runtime</scope>
</dependency>
<!--
an slf4j implementation is needed by
hibernate so that it could log its *stuff*
-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.6.4</version>
<scope>runtime</scope>
</dependency>
...
</dependencies>
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="test">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>Test</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver"/>
<!--
if you don't have a database already created
append ;create=true to end of the jdbc url
-->
<property name="javax.persistence.jdbc.url" value="jdbc:derby:test"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="root"/>
<!--
if you just created the database, maybe
you want hibernate to create a schema for you
<property name="hibernate.hbm2ddl.auto" value="create"/>
-->
</properties>
</persistence-unit>
</persistence>
Test
实体@Entity
@Table(name = "test")
public class Test {
@Id
public int id;
@Basic
public String data;
}
EntityManagerFactory emf = Persistence.createEntityManagerFactory("test");
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
Test test = em.find(Test.class, 1);
if (test == null) {
test = new Test();
test.id = 1;
test.data = "a";
tx.begin();
em.persist(test);
tx.commit();
}
System.out.format("Test{id=%s, data=%s}\n", test.id, test.data);
em.close();
emf.close();