我想在 独立应用程序* 中将 hibernate 与 嵌入式derby 一起使用,并且我有一些问题: *
如果您还可以建议我一些适合这种方法的好教程,那将是可取的,谢谢。
我将Apache Derby与Hibernate一起用于测试项目的一个模型类(它们的 equals , 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();