在测试CRUD
时,我使用了createQuery()
方法来生成HQL
查询以从MySQL
DB返回数据。
我的代码带有下划线并显示错误消息:
无法解析符号“学生”此检查控制是否
持久性QL查询经过错误检查
我认为数据库模型类中的@Entity
注释存在一些问题。
学生.java
import javax.persistence.*;
@Entity
@Table(name="student")
public class Student {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private int id;
@Column(name="first_name")
private String firstName;
@Column(name="last_name")
private String lastName;
@Column(name="email")
private String email;
public Student() {
}
QueryStudentDemo.java
public class QueryStudentDemo {
public static void main(String[] args) {
//create session factory
SessionFactory factory = new Configuration()
.configure("hibernate.cfg.xml")
.addAnnotatedClass(Student.class)
.buildSessionFactory();
//create session
Session session = factory.getCurrentSession();
try{
//use the session object to save Java object
//begin the transaction
session.beginTransaction();
//query students
List<Student> studentList = session.createQuery("from Student").getResultList();
//display the students
for (Student student: studentList){
System.out.println("Student: " + student);
}
//commit transaction
session.getTransaction().commit();
System.out.println("Transaction done!");
}finally {
factory.close();
}
hibernate.cfg.xml
<!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.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hb_student_tracker?useSSL=false&serverTimezone=UTC</property>
<property name="connection.username">hbstudent</property>
<property name="connection.password">hbstudent</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.MySQL8Dialect</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>
最佳答案
我认为您的hibernate.cfg.xml
丢失了<mapping class="your classname" />
-首先将您在学生班级中的表格名称更改为@Table(name =“ student”)到@Table(name =“ Student”)
第二次使用Session session = factory.openSession();这而不是Session session = factory.getCurrentSession();
列出studentList = session.createQuery(“来自Student”)。getResultList();替换为
查询查询= session.createQuery(s);
列出studentList = query.list();
之后,您可以运行