我正在尝试用Hibernate编写一个查询,以获取带有where子句的给定游戏的所有类型。但是当我运行我的应用程序时,我得到了这个错误:
Initial SessionFactory creation failed. org.hibernate.internal.util.config.ConfigurationException: Could not locate cfg.xml resource [hibernate.cfg.xml]我知道为了将POJO类映射到对应的表类,需要使用hibernate.cfg.xml进行映射,但我直接在POJO类中使用注释来映射它们,而不是XML。在这种情况下,使用SessionFactory似乎是错误的方法,这就引出了我的问题:在使用注释时,调用HQL查询的正确方式是什么?
谢谢
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
String query = "FROM Genre WHERE idGame = " + id;
List genres = (List) session.createQuery(query).list();发布于 2020-06-22 13:10:50
hibernate配置文件还用于定义不同的JDBC连接设置,因此需要创建一个。
您可以像这样创建一个
<!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>
<!-- JDBC Database connection settings -->
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/[DATABASE_NAME]?useSSL=false&serverTimezone=UTC</property>
<property name="connection.username">[USERNAME]</property>
<property name="connection.password">[PASSWORD]</property>
<!-- JDBC connection pool settings ... using built-in test pool -->
<property name="connection.pool_size">1</property>
<!-- Select our SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Echo the SQL to stdout -->
<property name="show_sql">true</property>
<!-- Set the current session context -->
<property name="current_session_context_class">thread</property>
</session-factory>
</hibernate-configuration>您还需要将其放在项目的根目录中(就像在src文件夹中一样)。替换DATABASE_NAME、用户名、密码,并请仔细检查定义的其他属性。
然后,您可以构建如下所示的SessionFactory
SessionFactory factory = new Configuration()
.configure("hibernate.cfg.xml")
.addAnnotatedClass(Student.class)
.buildSessionFactory();如果"hibernate.cfg.xml“arg位于根目录(这是hibernate查找配置文件的默认路径),则可以将其从configure中删除。或者您可以手动更改cfg文件的路径,在arg中提及它。
然后从SessionFactory获取Session
Session session = factory.getCurrentSession();发布于 2020-06-22 13:06:58
我需要添加hibernate.cfg.xml?Yes you need a cfg.xml for hibernate才能让它知道它的DB conf吗?也许你可以参考以下内容:
https://stackoverflow.com/questions/62507230
复制相似问题