Hibernate不执行查询

时间:2015-09-04 22:54:11

标签: hibernate postgresql

我知道,类似的问题在stackoverflow上出现了很多次,但我找不到解决问题的方法,因为一切似乎都能正常工作。

我想从ID为5的PostgreSQL数据库中获取用户。用户存在于数据库中(使用pg-Admin程序检查)。 ID字段的类型为bigint。当我调试解决方案时,我可以在控制台上看到(我正在使用Eclipse),Hibernate确实加载了整个映射文件并连接到数据库。

我正在使用Hibernate 4.3和PostgreSQL 9.3

我创建了一个通用的CRUD类来检索我想要的任何类。

我使用以下方法通过id检索对象:

@Override
public T GetInstanceById(long id) 
{
    Session session = null;
    T instance = null;

    try 
    {
        session = HibernateUtil.getSessionFactory().openSession();
        instance = (T) session.get(type, id);
    } 

    catch (Exception e) {}
    finally 
    {
        if (session != null && session.isOpen()) 
        {
            session.close();
        }
    }
    return instance;
}

这是我的 HibernateUtil 类:

package mapping.config;

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

public class HibernateUtil
{
    private static SessionFactory sessionFactory = buildSessionFactory();
    private static ServiceRegistry serviceRegistry;

    private static SessionFactory buildSessionFactory() {

        Configuration configuration = new Configuration().configure(HibernateUtil.class.getResource("hibernate.cfg.xml"));

        serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();        
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);

        return sessionFactory;

    }

   public static SessionFactory getSessionFactory()
   {
      return sessionFactory;
   }

   public static void shutdown()
   {
      getSessionFactory().close();
   }
}

在hibernate.cfg.xml中我定义了以下几行:

    <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
    <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
    <property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/example</property>
    <property name="hibernate.connection.username">*******</property>
    <property name="hibernate.connection.password">*******</property>

和一些映射。

我的TestMethod看起来像这样:

ICrud<User> crud = new CrudBase<User>(User.class);
User user = crud.GetInstanceById(5);
String guiLanguage = user.getGuiLanguage();

最后我的控制台输出:

Sep 05, 2015 12:36:38 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
Sep 05, 2015 12:36:38 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.11.Final}
Sep 05, 2015 12:36:38 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Sep 05, 2015 12:36:38 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Sep 05, 2015 12:36:38 AM org.hibernate.cfg.Configuration configure
INFO: HHH000044: Configuring from URL: file:...hibernate.cfg.xml
Sep 05, 2015 12:36:38 AM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
Sep 05, 2015 12:36:38 AM org.hibernate.cfg.Configuration addResource
/////////////////////////////A lot of ressources added//////////////////////
Sep 05, 2015 12:36:41 AM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Sep 05, 2015 12:36:41 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
Sep 05, 2015 12:36:41 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [org.postgresql.Driver] at URL [jdbc:postgresql://localhost:5432/example]
Sep 05, 2015 12:36:41 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=postgres, password=****}
Sep 05, 2015 12:36:41 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
Sep 05, 2015 12:36:41 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Sep 05, 2015 12:36:42 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
Sep 05, 2015 12:36:42 AM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
Sep 05, 2015 12:36:43 AM org.hibernate.mapping.RootClass checkCompositeIdentifier
///////////////////the next bla bla bla because of not overriding equals() for composite keys///////////////////////////////////////////////////////////////
Sep 05, 2015 12:36:45 AM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Sep 05, 2015 12:36:45 AM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory

在控制台输出结束时,现在应该有一个不会出现的休眠查询。

可以解决什么问题?

1 个答案:

答案 0 :(得分:0)

请说明您如何映射用户实体。如果您使用注释,请确保您没有忘记添加@Entity。

如果你想查看hibernate执行的实际查询,请检查你的hibernate.cfg.xml中是否有show_sql属性(提供的代码片段不包含该属性)。

其他一切看起来都不错。

您的简化示例:

import org.hibernate.*;
import org.hibernate.cfg.*;
import org.hibernate.boot.registry.*;
import javax.persistence.*;

public class App {

  public static void main(String[] args) {
    final Configuration           configuration   = new Configuration().configure(App.class.getResource("hibernate.cfg.xml"));
    final StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
    final SessionFactory          sf              = configuration.buildSessionFactory(serviceRegistry);
    final Session                 session         = sf.openSession();
    System.out.println(session.get(User.class, 5L));
    session.close();
  }

  @Entity
  @Table(name = "users")
  public static class User {
    @Id
    Long id;
    String guiLanguage;

    public String toString() { return String.format("User#%d[guiLanguage: %s]", id, guiLanguage); }
  }
}

的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>
    <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQL9Dialect</property>
    <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
    <property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/postgres</property>
    <property name="hibernate.connection.username">postgres</property>
    <property name="hibernate.connection.password">postgres</property>
    <property name="show_sql">true</property>
    <mapping class="App$User"/>
  </session-factory>
</hibernate-configuration>

分贝:

CREATE TABLE users (id BIGINT NOT NULL, guiLanguage VARCHAR(255), PRIMARY KEY (id));
INSERT INTO users VALUES (5, 'en');

打印以下内容:

Hibernate: select app_user0_.id as id1_0_0_, app_user0_.guiLanguage as guiLangu2_0_0_ from users app_user0_ where app_user0_.id=?
User#5[guiLanguage: us]