尝试使用Hibernate执行SELECT操作时出错

时间:2012-02-13 09:26:04

标签: java sql hibernate java-ee

我是hibernate的新手,我在尝试使用Hibernate从表中选择数据时遇到错误, 我已经尝试了两种方法并面临以下错误。

方法1

   private static void queryPerson(Session session) {

    String SQL_QUERY ="Select person.ID as ID,person.NAME as NAME ,person.SURNAME AS SURNAME,person.ADDRESS  as ADDRESS From person";
         Query query = session.createQuery(SQL_QUERY);
         for(Iterator it=query.iterate();it.hasNext();){
         Object[] row = (Object[]) it.next();
         System.out.println("ID: " + row[0]);
         System.out.println("Name: " + row[1]);
         System.out.println("Amount: " + row[2]);
         session.getTransaction().commit();
         }

这会引发以下错误:

 Exception in thread "main" org.hibernate.hql.ast.QuerySyntaxException: person is not mapped [Select person.ID as ID,person.NAME as NAME ,person.SURNAME AS SURNAME,person.ADDRESS  as ADDRESS From person]
at org.hibernate.hql.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:180)
at org.hibernate.hql.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:111)
at org.hibernate.hql.ast.tree.FromClause.addFromElement(FromClause.java:93)
at org.hibernate.hql.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:327)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3441)

方法2:

  private static void queryPerson(Session session) {
  Query query = session.createQuery("from Person");                 
    List <Person>list = query.list();
    java.util.Iterator<Person> iter = list.iterator();
    while (iter.hasNext()) {

        Person person = iter.next();
        System.out.println("Person: \"" + person.getName() +"\", " + person.getSurname() +"\", " +person.getAddress());
  session.getTransaction().commit();

    }

引发以下错误:

Caused by: org.postgresql.util.PSQLException: ERROR: column person0_.id does not exist
Position: 8
at    org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2102)
at   org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1835)

如果有人能指出我哪里出错了会很棒。 谢谢! 编辑: Person.hbm.xml       

<class name="com.sample.Person" table="Person">

    <id name="id" column="ID">
        <generator class="native" />
    </id>

    <property name="name">
        <column name="NAME" length="16" not-null="false" />
    </property>

    <property name="surname">
        <column name="SURNAME" length="16" not-null="false" />
    </property>

    <property name="address">
        <column name="ADDRESS" length="16" not-null="false" />
    </property>

</class>

的hibernate.cfg.xml       

    

    <!-- hibernate dialect -->
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>


    <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
    <property name="hibernate.connection.url">jdbc:postgresql://localhost/testDB</property>
    <property name="hibernate.connection.username">postgres</property>
    <property name="hibernate.connection.password"></property>
    <property name="hibernate.show_sql">true</property> 
    <property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>

    <!-- Automatic schema creation (begin) === -->
    <property name="hibernate.hbm2ddl.auto">validate</property>


    <!-- Simple memory-only cache -->
    <property name="hibernate.cache.provider_class">org.hibernate.cache.HashtableCacheProvider</property>

    <!-- Enable Hibernate's automatic session context management -->
    <property name="current_session_context_class">thread</property>

    <!-- ############################################ -->
    <!-- # mapping files with external dependencies # -->
    <!-- ############################################ -->

    <mapping resource="com/sample/Person.hbm.xml" />

</session-factory>

编辑:这是我使用的Person类:

 package com.sample;

 public class Person {
  Long id;
   String name;
   String surname;
   String address;

public Long getId() {
    return id;
}
private void setId(Long id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getSurname() {
    return surname;
}
public void setSurname(String surname) {
    this.surname = surname;
}
public String getAddress() {
    return address;
}
public void setAddress(String address) {
    this.address = address;
 }
}           

3 个答案:

答案 0 :(得分:4)

试试这个:

person.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
  <class name="com.sample.Person" table="Person">
      <id name="id" column="ID">
        <generator class="native" />
    </id>
    <property name="name">
        <column name="NAME" length="16" not-null="false" />
    </property>

    <property name="surname">
        <column name="SURNAME" length="16" not-null="false" />
    </property>

    <property name="address">
        <column name="ADDRESS" length="16" not-null="false" />
    </property>
</class>
</hibernate-mapping>

hibernate.cfg.xml

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

<hibernate-configuration>
<session-factory>
      ...your database configurations and mapping file...

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

HibernateUtil.java

public class HibernateUtil {

        private static final SessionFactory sessionFactory;

        static {
            try {
                // Create the SessionFactory from hibernate.cfg.xml
                // ------ --- -------------- ---- -----------------
                sessionFactory = new Configuration().configure()
                        .buildSessionFactory();
            } catch (Throwable ex) {
                // Make sure you log the exception, as it might be swallowed
                // ---- ---- --- --- --- ---------- -- -- ----- -- ---------
                System.err.println("Initial SessionFactory creation failed." + ex);
                throw new ExceptionInInitializerError(ex);
            }
        }

        /**
         * Get the configured session factory
         * 
         * @return session factory
         */
        public static SessionFactory getSessionFactory() {
            return sessionFactory;
        }
    }

一个例子:

public class PersonExample{
    public static void main(String[] args) {
        Session session = null;
        try {
            SessionFactory sessionFactory = new Configuration().configure()
                    .buildSessionFactory();
            session = sessionFactory.openSession();
            System.out.println("Starting select");
            List<Person> persons= session.createSQLQuery("select {p.*} from Person p").addEntity("p", Person.class).list();
            for (Iterator<Person> it = persons.iterator(); it.hasNext();) {
            Person stObject = it.next();
               System.out.println("ID: " + stObject.getId());
               System.out.println("Surname: " + stObject.getSurname());
               System.out.println("Name: " + stObject.getName());
               System.out.println("Address: " + stObject.getAddress());
            }
            System.out.println("Finished select");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        } finally {
            // Actual contact insertion will happen at this step
            session.flush();
            session.close();
        }

    }
}

答案 1 :(得分:1)

您是否为类Person提供了注释@Entity?

HQL与SQL不同。我认为您的查询有问题:

  

String SQL_QUERY =“选择person.ID作为ID,person.NAME作为NAME,person.SURNAME作为SURNAME,person.ADDRESS作为ADDRESS来自人”;

尝试以下方法: HQL:从Person选择person.id,person.name,person.surname,person.address

表名始终为大写,与您的类名匹配。 对于列名,这些必须与您的实例变量匹配。

更新(使用Unitils进行Hibernate映射测试):

import org.junit.Test;
import org.junit.runner.RunWith;
import org.unitils.UnitilsJUnit4TestClassRunner;
import org.unitils.orm.hibernate.HibernateUnitils;
import org.unitils.spring.annotation.SpringApplicationContext;

/**
 * Unitils mapping test class.
 * 
 */
@SpringApplicationContext({ "spring.xml" })
@RunWith(UnitilsJUnit4TestClassRunner.class)
public class HibernateMappingTest {

    @Test
    public void testMappingToDatabase() {
        HibernateUnitils.assertMappingWithDatabaseConsistent();
    }

}

答案 2 :(得分:1)

缺少映射类和别名的名称。您的查询应该是,

Select person.ID as ID,person.NAME as NAME ,person.SURNAME AS SURNAME,person.ADDRESS  as ADDRESS From Person as person

注意首都&#39; P&#39;在&#39;来自人物&#39;。我假设方法1和方法2中的代码库是相同的。在方法2中,班级名称是&#39; Person&#39;不是&#39; person&#39;除非你打算执行本机sql。在这种情况下,您应该调用session.createSQLQuery并尝试是否能够直接在db上执行相同的查询。

从方法2异常跟踪,您的映射是错误的。验证表是否存在且映射中的列名是否正确。