GVKun编程网logo

如何在JPA persistence.xml中使用Hibernate SchemaUpdate类?(jpa+hibernate)

15

如果您想了解如何在JPApersistence.xml中使用HibernateSchemaUpdate类?的相关知识,那么本文是一篇不可错过的文章,我们将对jpa+hibernate进行全面详尽的解释

如果您想了解如何在JPA persistence.xml中使用Hibernate SchemaUpdate类?的相关知识,那么本文是一篇不可错过的文章,我们将对jpa+hibernate进行全面详尽的解释,并且为您提供关于5 Hibernate:Java Persistence API (JPA) 入门、Hibernate JPA如何在persistence.xml中配置动态更新、Hibernate-OGM [PersistenceUnit:person]无法建立Hibernate SessionFactory、hibernate.cfg.xml 和 persistence.xml的有价值的信息。

本文目录一览:

如何在JPA persistence.xml中使用Hibernate SchemaUpdate类?(jpa+hibernate)

如何在JPA persistence.xml中使用Hibernate SchemaUpdate类?(jpa+hibernate)

我有一个使用SchemaUpdate的主要方法,可以在控制台上显示要更改/创建的表,并且在我的Hibernate项目中可以正常工作:

 public static void main(String[] args) throws IOException {  //first we prepare the configuration  Properties hibProps = new Properties();  hibProps.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("jbbconfigs.properties"));  Configuration cfg = new AnnotationConfiguration();  cfg.configure("/hibernate.cfg.xml").addProperties(hibProps);  //We create the SchemaUpdate thanks to the configs  SchemaUpdate schemaUpdate = new SchemaUpdate(cfg);  //The update is executed in script mode only  schemaUpdate.execute(true, false);  ...

我想在JPA项目中重用此代码,它没有hibernate.cfg.xml文件(也没有.properties文件),但是有一个persistence.xml文件(如JPA规范指定的在META-
INF目录中自动检测到) 。

我尝试了这种过于简单的调整,

Configuration cfg = new AnnotationConfiguration();cfg.configure();

但由于该异常而失败。

Exception in thread "main" org.hibernate.HibernateException: /hibernate.cfg.xml not found

有人做过吗?谢谢。

答案1

小编典典

卡里姆(Kariem)走在正确的道路上,但让我尝试澄清一下。

假设您具有普通的JPA标准配置,除了classpath上的Hibernate
jars外,没有任何Hibernate特定的配置。如果您以J2SE引导模式运行,那么您已经有一些类似于Java或Spring配置等的代码:

Map<String, Object> props = getJPAProperties();EntityManagerFactory emf =     Persistence.createEntityManagerFactory("persistence-unit-name", props);

要运行SchemaUpdate,只需使用以下代码即可:

Map<String, Object> props = getJPAProperties();Ejb3Configuration conf =     new Ejb3Configuration().configure("persistence-unit-name", props);new SchemaUpdate(conf.getHibernateConfiguration()).execute(true, false);

我不确定这在容器环境中如何运行,但是在简单的J2SE或Spring类型的配置中,仅此而已。

5 Hibernate:Java Persistence API (JPA) 入门

5 Hibernate:Java Persistence API (JPA) 入门

Java Persistence API (JPA),Java 持久层 API,是 JCP 组织发布的 java EE 标准规范,通过注解或 XML 描述实体对象和数据库表的映射关系。

Hibernate 实现了 JPA 规范,以下展示 Hibernate JPA 开发的完整步骤:

1 使用 Maven 管理 Hibernate 依赖

参看 4 Hibernate:使用注解(Annotation)

2 创建 JPA 配置文件 persistence.xml

Hibernate JPA 开发不需要创建 Hibernate 特定配置文件 hibernate.cfg.xml,取而代之的是创建 JPA 自有配置文件 persistence.xml,JPA 规范定义的启动过程不同于 Hibernate 启动过程。

<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="hibernate.jpa">
    <description>
      Persistence unit for the JPA tutorial of the Hibernate Getting Started Guide
    </description>

    <class>hibernate.Person</class>

    <properties>
      <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
      <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/test" />
      <property name="javax.persistence.jdbc.user" value="root" />
      <property name="javax.persistence.jdbc.password" value="123456" />

      <property name="hibernate.show_sql" value="true" />
      <property name="hibernate.hbm2ddl.auto" value="create" />
    </properties>
  </persistence-unit>

</persistence>

注意:

  • 需要为 persistence-unit 设置 name 属性,此名称唯一;
  • 对比 hibernate.cfg.xml,除数据库连接配置部分属性名称有所不同,其他配置保持一致。

3 使用注解创建持久化类

package hibernate;

import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.hibernate.annotations.GenericGenerator;

@Entity
@Table(name = "person")
public class Person {

    private int id;

    private String account;

    private String name;

    private Date birth;

    public Person() {}

    public Person(String account, String name, Date birth) {
        this.account = account;
        this.name = name;
        this.birth = birth;
    }

    @Id // 实体唯一标识
    @GeneratedValue(generator = "increment") // 使用名为“increment”的生成器
    @GenericGenerator(name = "increment", strategy = "increment") // 定义名为“increment”的生成器,使用Hibernate的"increment"生成策略,即自增
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getAccount() {
        return account;
    }

    public void setAccount(String account) {
        this.account = account;
    }

    public String getName() {
        return name;
    }

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

    @Temporal(TemporalType.TIMESTAMP)
    public Date getBirth() {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }

    @Override
    public String toString() {
        return "Person [id=" + id + ", account=" + account + ", name=" + name + ", birth=" + birth + "]";
    }

}

4 通过 JPA API 编写访问数据库的代码

package hibernate;

import java.text.ParseException;
import java.util.Date;
import java.util.List;

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

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class EntityManagerIllustrationTest {

    private EntityManagerFactory entityManagerFactory;

    @Before
    public void setUp() throws Exception {
        entityManagerFactory = Persistence.createEntityManagerFactory("hibernate.jpa");
    }

    @After
    public void tearDown() throws Exception {
        entityManagerFactory.close();
    }

    @Test
    public void test() throws ParseException {
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        entityManager.getTransaction().begin();
        entityManager.persist(new Person("tony", "Tony Stark", new Date()));
        entityManager.persist(new Person("hulk", "Bruce Banner", new Date()));
        entityManager.getTransaction().commit();
        entityManager.close();

        entityManager = entityManagerFactory.createEntityManager();
        entityManager.getTransaction().begin();
        List<Person> result = entityManager.createQuery("FROM Person", Person.class).getResultList();
        for (Person person : result) {
            System.out.println(person);
        }
        entityManager.getTransaction().commit();
        entityManager.close();
    }

}

单元测试日志:

六月 26, 2017 12:01:22 上午 org.hibernate.jpa.internal.util.LogHelper logPersistenceUnitInformation
INFO: HHH000204: Processing PersistenceUnitInfo [
    name: hibernate.jpa
    ...]
六月 26, 2017 12:01:23 上午 org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.10.Final}
六月 26, 2017 12:01:23 上午 org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
六月 26, 2017 12:01:23 上午 org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
六月 26, 2017 12:01:23 上午 org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver resolveEntity
WARN: HHH90000012: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-mapping. Use namespace http://www.hibernate.org/dtd/hibernate-mapping instead.  Support for obsolete DTD/XSD namespaces may be removed at any time.
六月 26, 2017 12:01:28 上午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
六月 26, 2017 12:01:28 上午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/test]
六月 26, 2017 12:01:28 上午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=root, password=****}
六月 26, 2017 12:01:28 上午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
六月 26, 2017 12:01:28 上午 org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Mon Jun 26 00:01:29 CST 2017 WARN: Establishing SSL connection without server''s identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn''t set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to ''false''. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
六月 26, 2017 12:01:30 上午 org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
Hibernate: drop table if exists PERSON
六月 26, 2017 12:01:32 上午 org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@73511076] for (non-JTA) DDL execution was not in auto-commit mode; the Connection ''local transaction'' will be committed and the Connection will be set into auto-commit mode.
Hibernate: create table PERSON (ID integer not null auto_increment, ACCOUNT varchar(255), NAME varchar(255), BIRTH datetime, primary key (ID)) engine=MyISAM
六月 26, 2017 12:01:32 上午 org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@42257bdd] for (non-JTA) DDL execution was not in auto-commit mode; the Connection ''local transaction'' will be committed and the Connection will be set into auto-commit mode.
六月 26, 2017 12:01:33 上午 org.hibernate.tool.schema.internal.SchemaCreatorImpl applyImportSources
INFO: HHH000476: Executing import script ''org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl@4b629f13''
Hibernate: insert into PERSON (ACCOUNT, NAME, BIRTH) values (?, ?, ?)
Hibernate: insert into PERSON (ACCOUNT, NAME, BIRTH) values (?, ?, ?)
六月 26, 2017 12:01:33 上午 org.hibernate.hql.internal.QueryTranslatorFactoryInitiator initiateService
INFO: HHH000397: Using ASTQueryTranslatorFactory
Hibernate: select person0_.ID as ID1_0_, person0_.ACCOUNT as ACCOUNT2_0_, person0_.NAME as NAME3_0_, person0_.BIRTH as BIRTH4_0_ from PERSON person0_
Person [id=1, account=tony, name=Tony Stark, birth=2017-06-26 00:01:33.0]
Person [id=2, account=hulk, name=Bruce Banner, birth=2017-06-26 00:01:34.0]
六月 26, 2017 12:01:34 上午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:mysql://localhost:3306/test]

数据库查询结果:

输入图片说明

Hibernate JPA如何在persistence.xml中配置动态更新

Hibernate JPA如何在persistence.xml中配置动态更新

我不想在我的java源代码中进行配置,可以像这样完成:

@org.hibernate.annotations.Entity(        dynamicUpdate = true)

因为我希望它是可配置的。

我不使用hibernate.properties,而仅使用persistence.xml,就像我使用JPA一样。我怎样才能使dynamicUpdate作为true使用的所有实体persistence.xml只?

答案1

小编典典

您正在将JPA标准与Hibernate实现一起使用。在这种情况下,您尝试配置特定于Hibernate实现的内容,而不是JPA标准的一部分。如果它是有助于配置实现的属性,则可以通过persistence.xml将许多属性传递给实现,但是在这种情况下,如果您尝试为每个实体配置属性,则必须这样做。hibernate方式。您可能已经通过Bozho的非常相似的答案看到了这个问题。

有了所有这些,如果您决定继续使用org.hibernate。*注释进行配置,则由于注释值必须是常量表达式,因此您将无法使其真正可配置。

一个有趣的解决方案是在启动侦听器中修改某些持久性类并添加属性。

Hibernate-OGM [PersistenceUnit:person]无法建立Hibernate SessionFactory

Hibernate-OGM [PersistenceUnit:person]无法建立Hibernate SessionFactory

我收到以下错误

Exception in thread “main” javax.persistence.PersistenceException: [PersistenceUnit: person] Unable to build Hibernate SessionFactory at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:1249) at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.access$600(EntityManagerFactoryBuilderImpl.java:120) at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:860) at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850) at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:425) at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:849) at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:75) at org.hibernate.ogm.jpa.HibernateOgmPersistence.createEntityManagerFactory(HibernateOgmPersistence.java:63) at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55) at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39) at com.ihappyk.utility.Utility.setUpEntityManagerFactory(Utility.java:11) at com.ihappyk.work.PersonWorker.main(PersonWorker.java:14) Caused by: org.hibernate.MappingException: Could not instantiate id generator [entity-name=com.ihappyk.model.Person] at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.createIdentifierGenerator(DefaultIdentifierGeneratorFactory.java:123) at org.hibernate.mapping.SimpleValue.createIdentifierGenerator(SimpleValue.java:225) at org.hibernate.internal.SessionFactoryImpl.(SessionFactoryImpl.java:323) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1859) at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:857) … 9 more Caused by: org.hibernate.HibernateException: Unanticipated return type [java.lang.Long] for UUID conversion at org.hibernate.id.UUIDGenerator.configure(UUIDGenerator.java:111) at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.createIdentifierGenerator(DefaultIdentifierGeneratorFactory.java:117) … 13 more

实用工具

public class Utility {    private static EntityManagerFactory entityManagerFactory;    //@BeforeClass    public static EntityManagerFactory setUpEntityManagerFactory() {        entityManagerFactory = Persistence.createEntityManagerFactory( "person" );        return entityManagerFactory;    }    //@AfterClass    public static void closeEntityManagerFactory() {        entityManagerFactory.close();    }}

坚持班

@Entitypublic class Person {        @Id        @GeneratedValue(generator = "uuid")        @GenericGenerator(name = "uuid", strategy = "uuid2")        private long id;        private String firstName;        private String lastName;        public long getId() {            return id;        }        public void setId(long id) {            this.id = id;        }        public String getFirstName() {            return firstName;        }        public void setFirstName(String firstName) {            this.firstName = firstName;        }        public String getLastName() {            return lastName;        }        public void setLastName(String lastName) {            this.lastName = lastName;        }        public Person(){        }        public Person(String firstName, String lastName) {            this.firstName = firstName;            this.lastName = lastName;        }    }

主班

public class PersonWorker {    public static void main(String[] args) {        // TODO Auto-generated method stub        EntityManagerFactory emf = Utility.setUpEntityManagerFactory();        EntityManager em = emf.createEntityManager();        em.getTransaction().begin();            // create a Person        Person bob = new Person( "Bob", "McRobb" );        em.persist( bob );        em.getTransaction().commit();        em.close();        emf.close();    }}

persistance.xml

<?xml version="1.0"?><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="person" transaction-type="JTA">        <provider>org.hibernate.ogm.jpa.HibernateOgmPersistence</provider>       <class>com.ihappyk.model.Person</class>        <properties>            <property name="hibernate.ogm.datastore.provider" value="mongodb" />            <property name="hibernate.ogm.datastore.database" value="hibernateOGM" />            <property name="hibernate.ogm.datastore.host" value="127.0.0.1" />            <property name="hibernate.ogm.datastore.port" value="27017" />            <property name="hibernate.ogm.datastore.provider" value="org.hibernate.ogm.datastore.mongodb.impl.MongoDBDatastoreProvider"/>            <property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.JBossStandAloneJtaPlatform"/>        </properties>    </persistence-unit></persistence>

答案1

小编典典

根本异常说明了一切:

Caused by: org.hibernate.HibernateException: Unanticipated return type [java.lang.Long] for UUID

您正在使用不支持的UUID ID生成器。在这种情况下,应使用String代替Long

hibernate.cfg.xml 和 persistence.xml

hibernate.cfg.xml 和 persistence.xml

在使用hibernate时,配置文件使用hibernate.cfg.xml但也可以使用persistence.xml,只是对应的api和代码流程是不一样的;前者是hibernate自己的一套东西吗?因为在代码里没有看到jpa相关的api,后者我知道是jpa规范的实现。

关于如何在JPA persistence.xml中使用Hibernate SchemaUpdate类?jpa+hibernate的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于5 Hibernate:Java Persistence API (JPA) 入门、Hibernate JPA如何在persistence.xml中配置动态更新、Hibernate-OGM [PersistenceUnit:person]无法建立Hibernate SessionFactory、hibernate.cfg.xml 和 persistence.xml等相关知识的信息别忘了在本站进行查找喔。

本文标签: