如何在 Hibernate 5 中从 xml 创建 table?

How to create table from xml in Hibernate 5?

我在此文件中保留 table 架构 tableaddress.orm.xml

<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings version="2.1"
    xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/orm"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <entity class="Address">
        <attributes>
            <basic name="city" attribute-type="String" />
            <basic name="country" attribute-type="int" />
            <basic name="province" attribute-type="double" />
            <basic name="postalCode" attribute-type="boolean">
            </basic>
            <basic name="street" attribute-type="String" />
        </attributes>
    </entity>
</entity-mappings>

以下是我尝试使用 Hibernate

创建 table 的方法
public class App 
{
    public static void main( String[] args )
    {

    Properties prop= new Properties();
    prop.setProperty("hibernate.connection.url", "jdbc:mariadb:......");
    prop.setProperty("dialect", "org.hibernate.dialect.MariaDB53Dialect");
    prop.setProperty("hibernate.connection.username", "user");
    prop.setProperty("hibernate.connection.password", "password");
    prop.setProperty("hibernate.connection.driver_class", "org.mariadb.jdbc.Driver");

     SessionFactory sessionFactory = new Configuration()
             .addResource("tableaddress.orm.xml").addProperties(prop).buildSessionFactory();
     Session session = sessionFactory.openSession();
     session.beginTransaction();
     session.getTransaction().commit();
     session.close(); 
    }
} 

它应该可以工作,没有编译错误,但由于某种原因没有创建 table

错误java.lang.NoClassDefFoundError: javax/transaction/SystemException

这可能是由于 Hibernate 中的 bug/feature。

javax.transaction 在 5.0.4 中从 Hibernate 中移除(好吧,标记为 "provided"),但在 5.0.7 中又恢复了(参见 https://hibernate.atlassian.net/browse/HHH-10307

"JTA no longer transitively provided (HHH-10178) causes problems for apps not using JTA"

)

假设您使用的是 5.04、5.0.5 或 5.0.6,您的选择是升级 Hibernate,或添加以下依赖项:

<dependency>
    <groupId>javax.transaction</groupId>
    <artifactId>jta</artifactId>
    <version>1.1</version>
</dependency>