hibernate不从数据库检索数据



hi我试图从mysql表中读取所有数据并将其显示在jsp上,但由于jsp加载了除表中数据外的其他数据,我似乎无法从表中检索任何数据,因为我试图找到问题的根源,我发现我的DAO没有从表中获取数据,因此没有数据传递到servlet和jsp,我所做的所有谷歌搜索我都找不到一个可以解决我的问题的,任何关于这件事的帮助都将非常感谢

这是我的DAO类

public class StudentDAO {

@SuppressWarnings("unchecked")
public List<Student> getAllStudents() {
Transaction transaction = null;
List<Student> students = new ArrayList<>();
String hql = "from model.Student";
try {
Session session = HibernateUtil.getSessionFactory().openSession();
transaction = session.beginTransaction();
Query query = session.createQuery(hql); //get all student objects
students = query.list();
System.out.println(students + "list of students"); // trying to query the problem
System.out.println(students);
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
}
return students;
}

这是我的Hibernate Util类

public class HibernateUtil {
private static SessionFactory sessionFactory;
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
try {
Configuration configuration = new Configuration();
Properties settings = new Properties();

// Hibernate settings equivalent to hibernate.cfg.xml's properties
settings.put(Environment.DRIVER, "com.mysql.cj.jdbc.Driver");
settings.put(Environment.URL, "jdbc:mysql://localhost:3306/week05");
settings.put(Environment.USER, "user1");
settings.put(Environment.PASS, "user1");
settings.put(Environment.DIALECT, "org.hibernate.dialect.MySQL5Dialect");
settings.put(Environment.SHOW_SQL, "true");
settings.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread");
settings.put(Environment.HBM2DDL_AUTO, "create-drop");
configuration.setProperties(settings);
configuration.addAnnotatedClass(Student.class);//jpa entity mapping
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();

sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Exception e) {
e.printStackTrace();
}
}
return sessionFactory;
}
}

这是我的servlet类,如果我配置错误:

@WebServlet({ "/", "/new", "/edit", "/update", "/delete", "/insert" })
public class StudentServlet extends HttpServlet {
private static final long serialVersionUID = 2L;
private StudentDAO studentDao;
String home = "/Week05";
public StudentServlet() {
this.studentDao = new StudentDAO();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String sPath = request.getServletPath();
//switch statement to call appropriate method
switch (sPath) {
case "/new":
try {
showNewForm(request, response);
} catch (ServletException | IOException e) {
e.printStackTrace();
}
break;
case "/insert":
try {
insertStudent(request, response);
} catch (SQLException | IOException e) {
e.printStackTrace();
} 
break;
case "/delete":
try {
deleteStudent(request, response);
} catch (SQLException | IOException e) {
e.printStackTrace();
}
break;
case "/update":
try {
updateStudent(request, response);
} catch (SQLException | IOException e) {
e.printStackTrace();
}
break;
case "/edit":
try {
editStudent(request, response);
} catch (ServletException | IOException e) {
e.printStackTrace();
}
break;
default:
try {
listAllStudents(request, response); //home page 
} catch (ServletException | IOException | SQLException e) {
e.printStackTrace();
} 
break; 
} 
}
// functions to fetch data from studentDao and display data on appropriate jsp
private void listAllStudents(HttpServletRequest request, HttpServletResponse response) 
throws ServletException, IOException, SQLException {
List<Student> allStudents = studentDao.getAllStudents();
request.setAttribute("listStudents", allStudents);
System.out.println(allStudents+"hello");
RequestDispatcher dispatch = request.getRequestDispatcher("index.jsp"); //home page  | list all objects from table
dispatch.forward(request, response);
}

这是我的index.jsp,以防万一也是

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" 
pageEncoding="ISO-8859-1" import="java.util.*" import="model.Student"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, intial-scale=1 shink-to-fit=yes">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" 
integrity="sha384...">
</head>
<body>
<nav class="navbar navbar-dark bg-primary pd-8">
<a class="navbar-brand">&nbsp;&nbsp;&nbsp;&nbsp;XYZ University</a>
</nav>
<div class="container-fluid">
<div class="container">
<div class="form container-fluid p-4">
<a href="<%=request.getContextPath()%>/new" class="btn btn-success" >Add
Student</a>
</div>
<br>

<!--Assigning ArrayList object containing student data to the local object -->
<% ArrayList<Student> studentList = (ArrayList) request.getAttribute("listStudents"); %> 
<table class="table table-bordered">

<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<%
if(request.getAttribute("listStudents") != null)  {
Iterator<Student> iterator = studentList.iterator();
while(iterator.hasNext()) {
Student studentDetails = iterator.next();
%>
<tr><td><%=studentDetails.getFirstname()%></td>
<td><%=studentDetails.getLastname()%></td>
<td><%=studentDetails.getEmail()%></td>
<td><a href="<%=request.getContextPath()%>/edit?id=<%=studentDetails.getId()%>
&firstname=<%=studentDetails.getFirstname() %>&lastname=<%=studentDetails.getLastname()%>
&email=<%=studentDetails.getEmail()%>">Update</a>
&nbsp;&nbsp;&nbsp;&nbsp; <a href="<%=request.getContextPath()%>/delete?id=<%=studentDetails.getId()%>">Delete</a></td>
</tr>
<% 
}
}
%>
</tbody>

</table>
</div>
</div>

<footer class="text-center text-lg-start p-4">
<div class="bg-primary text-center p-3">
© 2021 Copyright:
<a class="text-dark" href=""> SAiS Botswana</a>
</div>
</footer> 
</body>
</html>

PS tl/dr我能够正确地将数据插入表格,但无法检索

这是我的jpa类对象:

@Entity
@Table(name="students")
public class Student {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private int id;
@Column(name = "firstname")
private String firstname;
@Column(name = "lastname")
private String lastname;
@Column(name = "email")
private String email;



public Student() {
}
public Student(int id, String firstname, String lastname, String email) {
super();
this.id = id;
this.firstname = firstname;
this.lastname = lastname;
this.email = email;
}
public Student(String firstname, String lastname, String email) {
super();
this.firstname = firstname;
this.lastname = lastname;
this.email = email;
}

public int getId() {
return id;
}
public String getFirstname() {
return firstname;
}
public String getLastname() {
return lastname;
}

public String getEmail() {
return email;
}

public void setId(int id) {
this.id = id;
}

public void setFirstname(String firstname) {
this.firstname = firstname;
}

public void setLastname(String lastname) {
this.lastname = lastname;
}
public void setEmail(String email) {
this.email = email;
}
}

这是我在服务器启动后收到的控制台日志:

INFO: Server startup in 3040 ms
nullhello
Aug 10, 2021 4:09:49 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate ORM core version 5.5.6.Final
Aug 10, 2021 4:09:50 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
Aug 10, 2021 4:09:50 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Aug 10, 2021 4:09:51 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.cj.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/week05]
Aug 10, 2021 4:09:51 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {password=****, user=user1}
Aug 10, 2021 4:09:51 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Aug 10, 2021 4:09:51 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Aug 10, 2021 4:09:51 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
Hibernate: drop table if exists hibernate_sequence
Aug 10, 2021 4:09:54 PM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@31a0e986] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Hibernate: drop table if exists students
Hibernate: create table hibernate_sequence (next_val bigint) engine=MyISAM
Aug 10, 2021 4:09:54 PM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@356bba04] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Hibernate: insert into hibernate_sequence values ( 1 )
Hibernate: create table students (id integer not null, email varchar(255), firstname varchar(255), lastname varchar(255), primary key (id)) engine=MyISAM
Hibernate: select next_val as id_val from hibernate_sequence for update
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
Hibernate: insert into students (email, firstname, lastname, id) values (?, ?, ?, ?)

**试试这种方法**

<%
List<Student> List = listStudents.getlistStudents();
%>

<%
for (Student  st: List) {
int id = st.getId();

%>
<tr><td><%=st.getFirstname()%></td>
<td><%=st.getLastname()%></td>
<td><%=st.getEmail()%></td>
<td><a href="<%=request.getContextPath()%>/edit?id= 
<%=st.getId()%>
&firstname=<%=st.getFirstname() %>&lastname= 
<%=st.getLastname()%>
&email=<%=st.getEmail()%>">Update</a>
&nbsp;&nbsp;&nbsp;&nbsp; <a href=" 
<%=request.getContextPath()%>/delete?id= 
<%=st.getId()%>">Delete</a></td>
</tr>
<% 
}
}
%>

refence ShowAllFlat.jsp

最新更新