我有配置hibernate的问题,从DB获取所有实体的列表。我错过了什么,但不知道是什么。这是我的实体和cfg.xml配置文件: 插入实体到DB没有问题,只有从DB获取它的问题。 实体看起来像这样:
@Entity
public class Person {
@Id
@GeneratedValue
private long id;
private String name;
private int age;
{getters setters}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
和主要课程:
public static void main(String[] args) {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("myh2");
EntityManager entityManager = entityManagerFactory.createEntityManager();
createPerson(entityManager);
Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().
applySettings(configuration.getProperties());
SessionFactory factory = configuration.buildSessionFactory(builder.build());
Session session = factory.openSession();
String hql = "select p from " + Person.class.getSimpleName() + " p";
List<Person> list = (List<Person>) session.createQuery(hql).list();
System.out.println(list);
session.close();
entityManager.close();
entityManagerFactory.close();
}
hibernate.cfg.xml文件看起来像这样(我也尝试添加映射类,但也会出现同样的问题)
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">org.h2.Driver</property>
<property name="connection.url">jdbc:h2:./db/repository</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.H2Dialect</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<!-- <mapping class="second.level.cache.Person"/> -->
</session-factory>
</hibernate-configuration>