Hibernate 5.2.10:无法执行解组

时间:2017-11-17 20:38:44

标签: java xml hibernate java-9

编辑5:已解决

主要问题是我使用的是JDK 9,其中JAXB API不再在默认的类路径上。这是link where I've found solution

我在示例教程中使用了hibernate版本4.3.6并且一切都运行良好,但是当我将版本更新到5.2.10时我遇到了问题(我知道负责getSessionFactory的代码不同所以我改了它。)

我的第一个功能:

private static SessionFactory getSessionFactory(){
    Configuration configuration = new Configuration().configure();
    StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
            .applySettings(configuration.getProperties());
    SessionFactory sessionFactory = configuration.buildSessionFactory(builder.build());
    return sessionFactory;
}

我在5.2.10版本中的功能:

private static SessionFactory getSessionFactory(){

    StandardServiceRegistry registry;
    SessionFactory sessionFactory;
    registry = new StandardServiceRegistryBuilder().configure().build();

    MetadataSources sources = new MetadataSources(registry);

    Metadata metadata = sources.getMetadataBuilder().build();

    sessionFactory = metadata.getSessionFactoryBuilder().build();
    return sessionFactory;

}

例外:

  

线程“main”中的异常   org.hibernate.internal.util.config.ConfigurationException:无法   在RESOURCE中的第0行和第0列执行解组   hibernate.cfg.xml中。消息:null

和hibernate.cfg.xml

<?xml version="1.0" encoding="utf-8"?>
        <!DOCTYPE hibernate-configuration SYSTEM


"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQL94Dialect</property>
        <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
        <property name="hibernate.connection.url">jdbc:postgresql://127.0.0.1:5432/postgres</property>
        <property name="hibernate.connection.username">postgres</property>
        <property name="hibernate.connection.password">123</property>
        <property name="hibernate.hbm2ddl.auto">update</property>
        <property name="show_sql">false</property>
        <property name="hibernate.current_session_context_class">thread</property>
        <mapping class="com.example.Item"/>
    </session-factory>
</hibernate-configuration>

问题出在哪里?我已经尝试了一切。

编辑:pom.xml

  <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>pl.example</groupId>
<artifactId>example</artifactId>
<version>1.0-SNAPSHOT</version>

<build>
    <plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.7.0</version>
        <configuration>
            <source>1.8</source>
            <target>1.8</target>
        </configuration>
    </plugin>
    </plugins>
</build>

<dependencies>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>42.1.4</version>
    </dependency>

    <dependency>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.7.0</version>
    </dependency>


    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.2.10.Final</version>
    </dependency>
</dependencies>

编辑2

public class HibernateUtil {
    private static final SessionFactory sessionFactory;
static {
    try {
        StandardServiceRegistry standardRegistry =
                new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
        Metadata metaData =
                new MetadataSources(standardRegistry).getMetadataBuilder().build();
        sessionFactory = metaData.getSessionFactoryBuilder().build();
    } catch (Throwable th) {

        System.err.println("Enitial SessionFactory creation failed" + th);
        throw new ExceptionInInitializerError(th);

    }
}
public static SessionFactory getSessionFactory() {

    return sessionFactory;

}

}

@Entity
@Table(name = "employee")
public class Employee implements Serializable{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="id")
    private int id;

    @Column(name="emp_name")
    private String empName;

    @Column(name="emp_address")
    private String empAddress;

    @Column(name="emp_mobile_nos")
    private String empMobileNos;

    public int getId() {
        return id;
    }

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

    public String getEmpName() {
        return empName;
    }

    public void setEmpName(String empName) {
        this.empName = empName;
    }

    public String getEmpAddress() {
        return empAddress;
    }

    public void setEmpAddress(String empAddress) {
        this.empAddress = empAddress;
    }

    public String getEmpMobileNos() {
        return empMobileNos;
    }

    public void setEmpMobileNos(String empMobileNos) {
        this.empMobileNos = empMobileNos;
    }

}

测试类。

  public class Test{
    public static void main(String[] args) throws Exception {

        SessionFactory sessFact = HibernateUtil.getSessionFactory();
        Session session = sessFact.getCurrentSession();
        org.hibernate.Transaction tr = session.beginTransaction();
        Employee emp = new Employee();
        emp.setEmpName("Deepak Kumar");
        emp.setEmpMobileNos("000000");
        emp.setEmpAddress("Delhi - India");
        session.save(emp);
        tr.commit();
        System.out.println("Successfully inserted");
        sessFact.close();
    }

}

编辑3

lis 17, 2017 11:54:50 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.10.Final}
lis 17, 2017 11:54:50 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
lis 17, 2017 11:54:50 PM org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver resolveEntity
WARN: HHH90000012: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-configuration. Use namespace http://www.hibernate.org/dtd/hibernate-configuration instead.  Support for obsolete DTD/XSD namespaces may be removed at any time.
Enitial SessionFactory creation failedorg.hibernate.internal.util.config.ConfigurationException: Unable to perform unmarshalling at line number 0 and column 0 in RESOURCE hibernate.cfg.xml. Message: null
Exception in thread "main" java.lang.ExceptionInInitializerError
    at pl.lostandfound.HibernateUtil.<clinit>(HibernateUtil.java:31)
    at pl.lostandfound.Test.main(Test.java:13)
Caused by: org.hibernate.internal.util.config.ConfigurationException: Unable to perform unmarshalling at line number 0 and column 0 in RESOURCE hibernate.cfg.xml. Message: null
    at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:133)
    at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:65)
    at org.hibernate.boot.cfgxml.internal.ConfigLoader.loadConfigXmlResource(ConfigLoader.java:57)
    at org.hibernate.boot.registry.StandardServiceRegistryBuilder.configure(StandardServiceRegistryBuilder.java:163)
    at pl.lostandfound.HibernateUtil.<clinit>(HibernateUtil.java:24)
    ... 1 more
Caused by: javax.xml.bind.JAXBException
 - with linked exception:
[java.lang.ClassNotFoundException: com.sun.xml.internal.bind.v2.ContextFactory]
    at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:241)
    at javax.xml.bind.ContextFinder.find(ContextFinder.java:477)
    at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:656)
    at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:599)
    at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:122)
    ... 5 more
Caused by: java.lang.ClassNotFoundException: com.sun.xml.internal.bind.v2.ContextFactory
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:185)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:496)
    at javax.xml.bind.ContextFinder.safeLoadClass(ContextFinder.java:594)
    at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:239)
    ... 9 more

编辑4

    log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Enitial SessionFactory creation failedorg.hibernate.internal.util.config.ConfigurationException: Could not locate cfg.xml resource [hibernate.cfg.xml]
Exception in thread "main" java.lang.ExceptionInInitializerError

1 个答案:

答案 0 :(得分:0)

我肯定会先修复ClassNotFound异常(java.lang.ClassNotFoundException:com.sun.xml.internal.bind.v2.ContextFactory)。这表明需要加载的类不存在......

也许添加以下依赖项可以解决您的问题:

<dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-impl</artifactId>
    <version>2.3.0</version>
</dependency>
<dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-core</artifactId>
    <version>2.3.0</version>
</dependency>

最新版本取自此处:https://mvnrepository.com/artifact/com.sun.xml.bind/jaxb-impl

如果仍然存在ClassNotFound异常......我会更仔细地查看JAXB hibernate正在使用的版本。分析依赖关系的一种非常好的方法是以下两个命令:

mvn clean dependency:analyze

mvn clean dependency:tree

对于Edit4:,请检查以下答案:

ConfigurationException: Could not locate cfg.xml resource [hibernate.cfg.xml] in project root folder

Location of hibernate.cfg.xml in project?