此代码工作正常,返回单行:
public static Customer GetCustomerFromDB() {
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
configuration.addAnnotatedClass(com.english.Customer.class);
configuration.configure();
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
Session session = sessionFactory.openSession();
session.beginTransaction();
Customer customer = session.get(Customer.class, 1);
session.getTransaction().commit();
session.close();
sessionFactory.close();
return customer;
}
我需要来自表客户的DB中的所有行。表客户包含一个元素。小变化。删除session.get()并添加以下行:
//same code as above
CriteriaQuery<Customer> criteriaQuery = session.getCriteriaBuilder().createQuery(Customer.class);
criteriaQuery.from(Customer.class);
List<Customer> contacts = session.createQuery(criteriaQuery).getResultList();
Customer customer = contacts.get(0);
//same code
错误: java.lang.NoClassDefFoundError:antlr / RecognitionException
POM:
//...
<!-- https://mvnrepository.com/artifact/antlr/antlr -->
<dependency>
<groupId>antlr</groupId>
<artifactId>antlr</artifactId>
<version>3.0ea8</version>
</dependency>
//...
答案 0 :(得分:0)
您只需执行此操作即可获取所有行:
String hql = "FROM Customer";
Query query = session.createQuery(hql);
List results = query.list();