我是 Hibernate 的新手,在尝试使用 Hibernate 从表中选择数据时遇到错误, 我为此尝试了两种方法并遇到了以下错误。
方法一
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)
方法二:
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)
如果有人能指出我哪里出错了就太好了。 谢谢! 编辑: 人.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;
}
}
最佳答案
试试这个:
人.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>
hibernate 工具.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();
}
}
}
关于java - 尝试使用 Hibernate 执行 SELECT 操作时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9258121/