将hibernate与嵌入式derby一起使用

将hibernate与嵌入式derby一起使用,第1张

将hibernate与嵌入式derby一起使用

我将Apache Derby与Hibernate一起用于测试项目的一个模型类(它们的 equalshashCode
实现,查询等)。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();


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5427794.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-11
下一篇 2022-12-11

发表评论

登录后才能评论

评论列表(0条)

保存