使用休眠时遇到意外行为

时间:2016-10-31 06:14:38

标签: java hibernate wildfly

我正在使用wildfly和hibernate处理webapp。

以下是我的一些代码和配置文件。

hibernate.cfg.xml中:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
                                         "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
 <session-factory name="">
  <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
  <property name="hibernate.connection.password">removed</property>
  <property name="hibernate.connection.url">jdbc:postgresql:reportbuilderwebservices</property>
  <property name="hibernate.connection.username">removed</property>
  <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
  <property name="hibernate.show_sql">true</property>
  <property name="hibernate.current_session_context_class">thread</property>
  <property name="hibernate.format_sql">true</property>
  <property name="hibernate.use_sql_comments">true</property>
  <property name="hibernate.connection.pool_size">10</property>
  <property name="hibernate.hbm2ddl.auto">create</property>
  <mapping class="org.declercq.reportbuilderback.models.User"/>
  <mapping class="org.declercq.reportbuilderback.models.Permission"/>
  <mapping class="org.declercq.reportbuilderback.models.Role"/>
  <mapping class="org.declercq.reportbuilderback.models.Vulnerability"/>
  <mapping class="org.declercq.reportbuilderback.models.Finding"/>
 </session-factory>
</hibernate-configuration>

我的模型类User.java带注释:

package org.declercq.reportbuilderback.models;



import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;


@Entity 
@Table(name = "users")
public class User implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id @GeneratedValue
    @Column(name="id")
    private int id;

    @Column(name="username")
    private String userName;

    @Column(name="password")
    private String password;

    @Column(name="email")
    private String emailAddress;

    public User(String userName, String password, String emailAddress) {
        super();
        this.userName = userName;
        this.password = password;
        this.emailAddress = emailAddress;
    }

    public User() {
        super();
    }

    public int getId() {
        return id;
    }

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

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

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

    public String getEmailAddress() {
        return emailAddress;
    }

    public void setEmailAddress(String emailAddress) {
        this.emailAddress = emailAddress;
    }






}

我的DAO方法:

public List<User> getAllUsers(){
        System.out.println("0");
        Session session=HibernateUtil.getSessionFactory().getCurrentSession();
        System.out.println("0,5");
        Transaction tx = null;
        List<User>allUsers=null;
        try{
            tx = session.beginTransaction();
            System.out.println("1");
            allUsers = session.createQuery("from User u").getResultList();
            System.out.println("2");
            tx.commit();
            System.out.println("3");

        }
        catch(HibernateException e){
            if(tx != null){
                tx.rollback();
                System.out.println("4");
            }
            return allUsers;
        }
        finally{
            session.close();
            System.out.println("5");
            return allUsers;
        }
    }

我的hibernate.util:

package org.declercq.reportbuilderback.dao;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
    private static final SessionFactory sessionFactory;
    static {
        try {
            Configuration configuration = new Configuration().configure();
            configuration.configure("hibernate.cfg.xml");
            StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
            sessionFactory = configuration.buildSessionFactory(ssrb.build());


        } catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);

            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

我的网络服务:

package org.declercq.reportbuilderback.webservices;

import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import org.declercq.reportbuilderback.dao.UserDao;
import org.declercq.reportbuilderback.models.User;

@Path("/userwebservice")
public class UserWebService {

    @Path("/users")
    @GET
    @Produces("application/json")
    public List<User> listUsers(){
        System.out.println("HERE");
        List<User>allUsers=new UserDao().getAllUsers();
        System.out.println("Now here");
        System.out.println("Size: "+allUsers.size());
        return allUsers;                
    }

}

我的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>reportbuilderback</groupId>
  <artifactId>org.declercq.reportbuilderback</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <dependencies>
    <dependency>
      <groupId>org.jboss.resteasy</groupId>
      <artifactId>resteasy-jaxb-provider</artifactId>
      <version>3.0.19.Final</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.jboss.resteasy</groupId>
      <artifactId>resteasy-client</artifactId>
      <version>3.0.19.Final</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.jboss.resteasy</groupId>
      <artifactId>async-http-servlet-3.0</artifactId>
      <version>3.0.19.Final</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.jboss.resteasy</groupId>
      <artifactId>resteasy-jaxrs</artifactId>
      <version>3.0.19.Final</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.jboss.resteasy</groupId>
      <artifactId>resteasy-multipart-provider</artifactId>
      <version>3.0.19.Final</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.2.3.Final</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.shiro</groupId>
        <artifactId>shiro-all</artifactId>
        <version>1.3.2</version>
    </dependency>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>9.4.1211.jre7</version>
    </dependency>
  </dependencies>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.5.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>3.0.0</version>
        <configuration>
          <warSourceDirectory>WebContent</warSourceDirectory>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

我的服务器输出:

奇怪的是,如果你在控制台中查看我的输出(我使用system.out.println),DAO代码会从创建事务直接跳到关闭会话,它甚至不会构建我的查询。 结果当然是我的数据库查询结果为null,因此nullpointerexception。我理解这一点,但我不知道为什么DAO代码没有正确执行...... 我认为这是因为我的pom配置,编译时的库与来自wildfly的库,但我不知道...

更新1:

按照以下说明更改我的代码后:

@SuppressWarnings({ "unchecked", "deprecation" })
    public List<User> getAllUsers(){
        System.out.println("0");
        Session session=HibernateUtil.getSessionFactory().getCurrentSession();
        System.out.println("0,5");
        Transaction tx = null;
        List<User>allUsers=null;
        try{
            tx = session.beginTransaction();
            System.out.println("1");
            //allUsers = session.createQuery("select u from User u").getResultList();
            allUsers=session.createCriteria(User.class).list();
            System.out.println("2");
            tx.commit();
            System.out.println("3");

        }
        catch(HibernateException e){
            if(tx != null){
                tx.rollback();
                System.out.println("4");
            }
            return allUsers;
        }
        finally{
            session.close();
            System.out.println("5");
            return allUsers;
        }
    }

我现在得到以下输出:

08:32:37,957 INFO  [org.jboss.modules] (main) JBoss Modules version 1.5.2.Final
08:32:38,350 INFO  [org.jboss.msc] (main) JBoss MSC version 1.2.6.Final
08:32:38,467 INFO  [org.jboss.as] (MSC service thread 1-8) WFLYSRV0049: WildFly Full 10.1.0.Final (WildFly Core 2.2.0.Final) starting
08:32:41,471 INFO  [org.jboss.as.server.deployment.scanner] (DeploymentScanner-threads - 1) WFLYDS0004: Found org.declercq.reportbuilderback-0.0.1-SNAPSHOT.war in deployment directory. To trigger deployment create a file called org.declercq.reportbuilderback-0.0.1-SNAPSHOT.war.dodeploy
08:32:41,641 INFO  [org.jboss.as.server] (Controller Boot Thread) WFLYSRV0039: Creating http management service using socket-binding (management-http)
08:32:41,715 INFO  [org.xnio] (MSC service thread 1-6) XNIO version 3.4.0.Final
08:32:41,728 INFO  [org.xnio.nio] (MSC service thread 1-6) XNIO NIO Implementation Version 3.4.0.Final
08:32:41,856 INFO  [org.jboss.remoting] (MSC service thread 1-6) JBoss Remoting version 4.0.21.Final
08:32:41,958 INFO  [org.jboss.as.clustering.infinispan] (ServerService Thread Pool -- 38) WFLYCLINF0001: Activating Infinispan subsystem.
08:32:41,990 INFO  [org.jboss.as.jsf] (ServerService Thread Pool -- 44) WFLYJSF0007: Activated the following JSF Implementations: [main]
08:32:42,007 INFO  [org.jboss.as.naming] (ServerService Thread Pool -- 46) WFLYNAM0001: Activating Naming Subsystem
08:32:42,059 WARN  [org.jboss.as.txn] (ServerService Thread Pool -- 54) WFLYTX0013: Node identifier property is set to the default value. Please make sure it is unique.
08:32:42,097 INFO  [org.wildfly.extension.io] (ServerService Thread Pool -- 37) WFLYIO001: Worker 'default' has auto-configured to 8 core threads with 64 task threads based on your 4 available processors
08:32:42,123 INFO  [org.jboss.as.security] (ServerService Thread Pool -- 53) WFLYSEC0002: Activating Security Subsystem
08:32:42,126 INFO  [org.jboss.as.webservices] (ServerService Thread Pool -- 56) WFLYWS0002: Activating WebServices Extension
08:32:42,175 INFO  [org.jboss.as.connector] (MSC service thread 1-4) WFLYJCA0009: Starting JCA Subsystem (WildFly/IronJacamar 1.3.4.Final)
08:32:42,208 INFO  [org.wildfly.extension.undertow] (MSC service thread 1-5) WFLYUT0003: Undertow 1.4.0.Final starting
08:32:42,213 INFO  [org.jboss.as.security] (MSC service thread 1-6) WFLYSEC0001: Current PicketBox version=4.9.6.Final
08:32:42,473 INFO  [org.jboss.as.naming] (MSC service thread 1-6) WFLYNAM0003: Starting Naming Service
08:32:42,477 INFO  [org.jboss.as.mail.extension] (MSC service thread 1-7) WFLYMAIL0001: Bound mail session [java:jboss/mail/Default]
08:32:42,523 INFO  [org.jboss.as.connector.subsystems.datasources] (ServerService Thread Pool -- 33) WFLYJCA0004: Deploying JDBC-compliant driver class org.h2.Driver (version 1.3)
08:32:42,535 INFO  [org.jboss.as.connector.deployers.jdbc] (MSC service thread 1-8) WFLYJCA0018: Started Driver service with driver-name = h2
08:32:42,853 INFO  [org.wildfly.extension.undertow] (ServerService Thread Pool -- 55) WFLYUT0014: Creating file handler for path '/home/wouter/wildfly-10.1.0.Final/welcome-content' with options [directory-listing: 'false', follow-symlink: 'false', case-sensitive: 'true', safe-symlink-paths: '[]']
08:32:42,889 INFO  [org.wildfly.extension.undertow] (MSC service thread 1-8) WFLYUT0012: Started server default-server.
08:32:42,897 INFO  [org.wildfly.extension.undertow] (MSC service thread 1-7) WFLYUT0018: Host default-host starting
08:32:43,108 INFO  [org.jboss.as.ejb3] (MSC service thread 1-7) WFLYEJB0481: Strict pool slsb-strict-max-pool is using a max instance size of 64 (per class), which is derived from thread worker pool sizing.
08:32:43,109 INFO  [org.jboss.as.ejb3] (MSC service thread 1-4) WFLYEJB0482: Strict pool mdb-strict-max-pool is using a max instance size of 16 (per class), which is derived from the number of CPUs on this host.
08:32:43,251 INFO  [org.wildfly.extension.undertow] (MSC service thread 1-8) WFLYUT0006: Undertow HTTP listener default listening on 127.0.0.1:8080
08:32:43,729 INFO  [org.jboss.as.connector.subsystems.datasources] (MSC service thread 1-8) WFLYJCA0001: Bound data source [java:jboss/datasources/ExampleDS]
08:32:44,048 WARN  [org.jboss.as.domain.management.security] (MSC service thread 1-5) WFLYDM0111: Keystore /home/wouter/wildfly-10.1.0.Final/standalone/configuration/application.keystore not found, it will be auto generated on first use with a self signed certificate for host localhost
08:32:44,093 INFO  [org.jboss.as.server.deployment.scanner] (MSC service thread 1-8) WFLYDS0013: Started FileSystemDeploymentService for directory /home/wouter/wildfly-10.1.0.Final/standalone/deployments
08:32:44,112 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-6) WFLYSRV0027: Starting deployment of "org.declercq.reportbuilderback-0.0.1-SNAPSHOT.war" (runtime-name: "org.declercq.reportbuilderback-0.0.1-SNAPSHOT.war")
08:32:44,508 INFO  [org.infinispan.factories.GlobalComponentRegistry] (MSC service thread 1-4) ISPN000128: Infinispan version: Infinispan 'Chakra' 8.2.4.Final
08:32:44,547 INFO  [org.wildfly.extension.undertow] (MSC service thread 1-8) WFLYUT0006: Undertow HTTPS listener https listening on 127.0.0.1:8443
08:32:44,617 INFO  [org.infinispan.configuration.cache.EvictionConfigurationBuilder] (ServerService Thread Pool -- 64) ISPN000152: Passivation configured without an eviction policy being selected. Only manually evicted entities will be passivated.
08:32:44,614 INFO  [org.infinispan.configuration.cache.EvictionConfigurationBuilder] (ServerService Thread Pool -- 60) ISPN000152: Passivation configured without an eviction policy being selected. Only manually evicted entities will be passivated.
08:32:44,621 INFO  [org.infinispan.configuration.cache.EvictionConfigurationBuilder] (ServerService Thread Pool -- 60) ISPN000152: Passivation configured without an eviction policy being selected. Only manually evicted entities will be passivated.
08:32:44,616 INFO  [org.infinispan.configuration.cache.EvictionConfigurationBuilder] (ServerService Thread Pool -- 65) ISPN000152: Passivation configured without an eviction policy being selected. Only manually evicted entities will be passivated.
08:32:44,623 INFO  [org.infinispan.configuration.cache.EvictionConfigurationBuilder] (ServerService Thread Pool -- 65) ISPN000152: Passivation configured without an eviction policy being selected. Only manually evicted entities will be passivated.
08:32:44,633 INFO  [org.infinispan.configuration.cache.EvictionConfigurationBuilder] (ServerService Thread Pool -- 64) ISPN000152: Passivation configured without an eviction policy being selected. Only manually evicted entities will be passivated.
08:32:44,841 INFO  [org.jboss.ws.common.management] (MSC service thread 1-5) JBWS022052: Starting JBossWS 5.1.5.Final (Apache CXF 3.1.6) 
08:32:47,678 INFO  [org.jboss.weld.deployer] (MSC service thread 1-5) WFLYWELD0003: Processing weld deployment org.declercq.reportbuilderback-0.0.1-SNAPSHOT.war
08:32:47,783 INFO  [org.hibernate.validator.internal.util.Version] (MSC service thread 1-5) HV000001: Hibernate Validator 5.2.4.Final
08:32:48,163 INFO  [org.jboss.as.connector.deployers.jdbc] (MSC service thread 1-1) WFLYJCA0005: Deploying non-JDBC-compliant driver class org.postgresql.Driver (version 9.4)
08:32:48,236 INFO  [org.jboss.weld.Version] (MSC service thread 1-1) WELD-000900: 2.3.5 (Final)
08:32:48,315 INFO  [org.jboss.as.connector.deployers.jdbc] (MSC service thread 1-3) WFLYJCA0018: Started Driver service with driver-name = org.declercq.reportbuilderback-0.0.1-SNAPSHOT.war_org.postgresql.Driver_9_4
08:32:51,378 INFO  [org.jboss.resteasy.resteasy_jaxrs.i18n] (ServerService Thread Pool -- 64) RESTEASY002225: Deploying javax.ws.rs.core.Application: class org.declercq.reportbuilderback.webservices.ConfigApp
08:32:51,429 INFO  [org.wildfly.extension.undertow] (ServerService Thread Pool -- 64) WFLYUT0021: Registered web context: /org.declercq.reportbuilderback-0.0.1-SNAPSHOT
08:32:51,498 INFO  [org.jboss.as.server] (ServerService Thread Pool -- 34) WFLYSRV0010: Deployed "org.declercq.reportbuilderback-0.0.1-SNAPSHOT.war" (runtime-name : "org.declercq.reportbuilderback-0.0.1-SNAPSHOT.war")
08:32:51,731 INFO  [org.jboss.as] (Controller Boot Thread) WFLYSRV0060: Http management interface listening on http://127.0.0.1:9990/management
08:32:51,731 INFO  [org.jboss.as] (Controller Boot Thread) WFLYSRV0051: Admin console listening on http://127.0.0.1:9990
08:32:51,732 INFO  [org.jboss.as] (Controller Boot Thread) WFLYSRV0025: WildFly Full 10.1.0.Final (WildFly Core 2.2.0.Final) started in 14785ms - Started 476 of 724 services (404 services are lazy, passive or on-demand)
08:32:57,477 INFO  [stdout] (default task-3) HERE
08:32:57,480 INFO  [stdout] (default task-3) 0
08:32:57,639 INFO  [org.hibernate.Version] (default task-3) HHH000412: Hibernate Core {5.2.3.Final}
08:32:57,641 INFO  [org.hibernate.cfg.Environment] (default task-3) HHH000206: hibernate.properties not found
08:32:57,644 INFO  [org.hibernate.cfg.Environment] (default task-3) HHH000021: Bytecode provider name : javassist
08:32:58,527 INFO  [org.hibernate.annotations.common.Version] (default task-3) HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
08:32:58,725 WARN  [org.hibernate.orm.connections.pooling] (default task-3) HHH10001002: Using Hibernate built-in connection pool (not for production use!)
08:32:58,727 INFO  [org.hibernate.orm.connections.pooling] (default task-3) HHH10001005: using driver [org.postgresql.Driver] at URL [jdbc:postgresql:reportbuilderwebservices]
08:32:58,729 INFO  [org.hibernate.orm.connections.pooling] (default task-3) HHH10001001: Connection properties: {user=reportbuilderwebservices, password=****}
08:32:58,730 INFO  [org.hibernate.orm.connections.pooling] (default task-3) HHH10001003: Autocommit mode: false
08:32:58,734 INFO  [org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl] (default task-3) HHH000115: Hibernate connection pool size: 10 (min=1)
08:32:58,844 INFO  [org.hibernate.dialect.Dialect] (default task-3) HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
08:32:59,106 INFO  [org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl] (default task-3) HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
08:32:59,109 INFO  [org.hibernate.type.BasicTypeRegistry] (default task-3) HHH000270: Type registration [java.util.UUID] overrides previous : org.hibernate.type.UUIDBinaryType@48ea9b0e
08:32:59,449 INFO  [org.hibernate.tool.schema.internal.SchemaCreatorImpl] (default task-3) HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl@43b645ed'
08:32:59,632 INFO  [stdout] (default task-3) 0,5
08:32:59,636 INFO  [stdout] (default task-3) 1
08:32:59,640 WARN  [org.hibernate.orm.deprecation] (default task-3) HHH90000022: Hibernate's legacy org.hibernate.Criteria API is deprecated; use the JPA javax.persistence.criteria.CriteriaQuery instead
08:32:59,653 INFO  [stdout] (default task-3) 2
08:32:59,657 INFO  [stdout] (default task-3) 3
08:32:59,658 INFO  [stdout] (default task-3) 5
08:32:59,659 INFO  [stdout] (default task-3) Now here
08:32:59,660 INFO  [stdout] (default task-3) Size: 0

所以,这里有2个问题:1)由于某种原因,这会执行而前一个createQuery方法没有。我真的想知道为什么,因为这种方式(使用标准)显然已被弃用。 2)最重要的原因:我打印出所有用户的大小,大小为0,这是绝对不可能的,因为在该用户表中添加了3个用户帐户。

有人可以协助吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

createQuery返回null,这通常意味着查询字符串有问题。你可以尝试,例如:

allUsers = session.createQuery("from User").getResultList();

或符合JPA的方式:

allUsers = session.createQuery("select u from User u").getResultList();

或没有hql:

allUsers = session.createCriteria(User.class).list();