保存我的对象时出现休眠异常

Posted

技术标签:

【中文标题】保存我的对象时出现休眠异常【英文标题】:Hibernate exception while saving my object 【发布时间】:2015-06-29 13:55:04 【问题描述】:

它不是保存我的对象,而是在到达保存方法时引发问题。

你可以在控制台中看到这样的:

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.
Exception in thread "main" java.lang.NullPointerException
    at com.liveSpreaker.presentation.HibernateTest.<init>(HibernateTest.java:58)
    at com.liveSpreaker.presentation.HibernateTest.main(HibernateTest.java:65)

我的喜欢:

package com.live.beans;

public class User 

    private int id;
    private String Name;
    private String email;
    private String password;

    public int getId() 
        return id;
    

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

    public String getName() 
        return Name;
    

    public void setName(String name) 
        Name = name;
    

    public String getEmail() 
        return email;
    

    public void setEmail(String email) 
        this.email = email;
    

    public String getPassword() 
        return password;
    

    public void setPassword(String password) 
        this.password = password;
    

    public User(int id, String name, String email, String password) 
        super();
        this.id = id;
        Name = name;
        this.email = email;
        this.password = password;
    

    public User(String name, String email, String password) 
        super();
        Name = name;
        this.email = email;
        this.password = password;
    


    @Override
    public String toString() 
        return "User [id=" + id + ", Name=" + Name + ", email=" + email
                + ", password=" + password + "]";
    


User.hbm.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.live.beans">
    <class name="User" table="user">
        <id name="id"
            type="int" 
            column="id" 
            length="15"/>
        <property name="name" 
                  type="string"
                  column="name"
                  length="45"
        />
        <property name="email" 
                  type="string"
                  column="email"
                  length="45"
        />
        <property name="password" 
                  type="string"
                  column="password"
                  length="45"
        />
    </class>

</hibernate-mapping>

我的班级HibernateTest.java

package com.live.presentation;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import com.live.beans.User;

public class HibernateTest 

    private Session session;
    private static SessionFactory sessionFactory;
    private static ServiceRegistry serviceRegistry;

    public static SessionFactory createSessionFactory() 
            Configuration configuration = new Configuration();
            configuration.configure("hibernate.cfg.xml");
            serviceRegistry = new ServiceRegistryBuilder().applySettings(
                    configuration.getProperties()).buildServiceRegistry();
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
            return sessionFactory;
    
    private void openSession()
        SessionFactory sessionFactory = createSessionFactory();
        Session session = sessionFactory.openSession();
        session.beginTransaction();
    

    private void closeSession()
        session.getTransaction().commit();
        session.close();
    

    public HibernateTest() 
        openSession();
        User p = new User(1, "Ali", "ali@gmail.com", "password");
        session.save(p);
        System.out.println("sauvegarde reussi");
        closeSession();
    

public static void main(String[] args) 

    new HibernateTest();

pom.xml

<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>p01</groupId>
  <artifactId>p01</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.6</source>
          <target>1.6</target>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.4</version>
        <configuration>
          <warSourceDirectory>WebContent</warSourceDirectory>
          <failOnMissingWebXml>false</failOnMissingWebXml>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <name>HibernateTest</name>
  <url>http://maven.apache.org</url>
  <dependencies>
          <dependency>
          <groupId>com.sun.faces</groupId>
          <artifactId>jsf-api</artifactId>
          <version>2.1.7</version>
        </dependency>
        <dependency>
          <groupId>com.sun.faces</groupId>
          <artifactId>jsf-impl</artifactId>
          <version>2.1.7</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.0.1.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>4.2.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate.common</groupId>
            <artifactId>hibernate-commons-annotations</artifactId>
            <version>4.0.1.Final</version>
            <classifier>tests</classifier>
        </dependency>
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.0-api</artifactId>
            <version>1.0.1.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.0.1.Final</version>
        </dependency>
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.0.0.GA</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.6.4</version>
        </dependency>
        <dependency>
            <groupId>org.jboss.logging</groupId>
            <artifactId>jboss-logging</artifactId>
            <version>3.1.0.CR2</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.6.4</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.10</version>
        </dependency>


    </dependencies>
</project>

hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>

        <property name="hibernate.connection.url">jdbc:mysql://localhost/ment</property>

        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>

        <property name="hibernate.connection.username">root</property>

        <property name="hibernate.connection.password"></property>

        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <property name="hibernate.show_sql">false</property>

        <mapping resource="com.live.hibernate.User.hbm.xml" />

    </session-factory>
</hibernate-configuration>

文件夹结构

src
 |-- com
 |   live
 |    |-- hibernate
 |    |    `-- User.hbm.xml
 |   live
 |    |`--beans
 |    |    `-- User.java
 |   live
 |     `--presentation
 |        `-- HibernateTest.java
 |--hibernate.cfg.xml
WebContent
 |-- META-INF
 |-- WEB-INF
 |         
 |-- index.xhtml
 pom.xml

当我到达 HibernateTest.java 类中的这一行时出现异常(我的意思是在调试时):

session.save(p);

虽然我使用User p = new User(1,"Ali", "ali@gmail.com", "password"); 我在session.save(p); 中遇到了同样的问题。

我正在使用 MySQL,我创建了名为 ment 的数据库和一个包含四列(id、姓名、电子邮件、密码)的表 user

【问题讨论】:

这里的问题可能不在于您的 Hibernate 测试配置;看起来有些东西在设置之前正在调用 Log4j。要么你之前没有自己设置,要么你正在使用的库有一个没有进行初始化的调用。 @ShotgunNinja :非常感谢,但我不这么认为,因为我遇到了问题并修复了它,我记得它总是调用 Log4j。我认为我的问题不属于 Log4j 【参考方案1】:

您的会话变量(您在 HibernateTest 的构造函数中使用的变量)尚未初始化。因此,它仍然是 null,这会导致 session.save(p); 抛出 NPE。

openSession()中的代码改为

private void openSession()
    SessionFactory sessionFactory = createSessionFactory();
    session = sessionFactory.openSession();
    session.beginTransaction();

即,在您的字段上打开新会话,而不是在该方法范围内的私有变量上打开,该变量在该方法运行后消失。

【讨论】:

以上是关于保存我的对象时出现休眠异常的主要内容,如果未能解决你的问题,请参考以下文章

定义映射时出现休眠异常

尝试启动 Tomcat 时出现休眠异常

在休眠中使用@Column 注释时出现异常

在 Mono 对象上执行 block() 时出现异常我从 ReactiveMongoRepository 对象返回

在 Linux 下运行时出现奇怪的休眠异常

使用 NSCoding Swift 保存对象时出现异常