【问题标题】:Retrieving object from mysql-database in spring+hibernate project doesn't work?在 spring+hibernate 项目中从 mysql-database 中检索对象不起作用?
【发布时间】:2025-12-08 23:15:01
【问题描述】:

我创建了 2 个用于使用 hibernate 进行映射的类:

package com.pcd.ahmed.model;
import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Past;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.format.annotation.DateTimeFormat;

@Entity
@Table(name="etudiants")
public class Etudiant {
@Id
@GeneratedValue
@Size(min=4, max=6)
private String student_ID;

@NotEmpty
@Size(min=4, max=45)
private String firstname;

@NotEmpty
@Size(min=4, max=45)
private String lastname;

@NotNull
@Past
@DateTimeFormat(pattern="MM/dd/yyyy")
private Date date_birth;

@NotEmpty
@Size(min=3, max=4)
private String class_ID;
}

package com.pcd.ahmed.model;

import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Past;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.format.annotation.DateTimeFormat;

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

@Id
@GeneratedValue
private Long id;

@NotEmpty
@Size(min=4, max=20)
private String userName;

@NotEmpty
private String firstName;

@NotEmpty
private String lastName;

@NotEmpty
@Size(min=4, max=8)
private String password;
}

但是当我尝试使用存储库从 mysql-database 表中检索对象时:

package com.pcd.ahmed.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import com.pcd.ahmed.model.Student;

@Repository("studentRepository")
public interface StudentRepository extends JpaRepository<Student, Long> {

@Query("select s from Student s where s.userName = :userName")
Student findByUserName(@Param("userName") String userName);
}

package com.pcd.ahmed.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import com.pcd.ahmed.model.Etudiant;


@Repository("studentRepository1")
public interface StudentRepository1 extends JpaRepository<Etudiant, String> {

@Query("select s from etudiants s where s.student_ID = :student_ID")
Etudiant findBystudent_ID(@Param("student_ID") String student_ID);

}

中的错误:

package com.pcd.ahmed.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.pcd.ahmed.model.Etudiant;
import com.pcd.ahmed.model.Student;
import com.pcd.ahmed.repository.StudentRepository;
import com.pcd.ahmed.repository.StudentRepository1;

@Service("studentService")
public class StudentServiceImpl implements StudentService {

@Autowired
private StudentRepository studentRepository;
private StudentRepository1 studentRepository1;
@Transactional
public Student save(Student student) {
    return studentRepository.save(student);
}
public Student profileget(String userName, String password) {   
    Student stud = studentRepository.findByUserName(userName);

    if(stud != null && stud.getPassword().equals(password) && stud.getroles().equals("Parents")) {
        return stud;
    } 
    if(stud != null && stud.getPassword().equals(password) && stud.getroles().equals("Administrateur")) {
        return stud;
    }
    if(stud != null && stud.getPassword().equals(password) && stud.getroles().equals("Enseignant")) {
        return stud;
    }
    if(stud != null && stud.getPassword().equals(password) && stud.getroles().equals("Infirmiere")) {
        return stud;
    }

    return null;        
}

public Etudiant studentget(String student_ID) { 
    Etudiant etud = studentRepository1.findBystudent_ID(student_ID);
    return etud;
}

public int findByLogin(String userName, String password,Student stud) { 
    stud = studentRepository.findByUserName(userName);

    if(stud != null && stud.getPassword().equals(password) && stud.getroles().equals("Parents")) {
        return 1;
    } 
    if(stud != null && stud.getPassword().equals(password) && stud.getroles().equals("Administrateur")) {
        return 2;
    }
    if(stud != null && stud.getPassword().equals(password) && stud.getroles().equals("Enseignant")) {
        return 3;
    }
    if(stud != null && stud.getPassword().equals(password) && stud.getroles().equals("Infirmiere")) {
        return 4;
    }

    return 0;       
}

public boolean findByUserName(String userName) {
    Student stud = studentRepository.findByUserName(userName);

    if(stud != null) {
        return true;
    }

    return false;
}


}

当我调用这个函数时:

public Etudiant studentget(String student_ID) { 
    Etudiant etud = studentRepository1.findBystudent_ID(student_ID);
    return etud;
}

它说:

org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [studentHibernateServlet] in context with path [/StudentEnrollmentWithSpring] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
    at      com.pcd.ahmed.service.StudentServiceImpl.studentget(StudentServiceImpl.java:42)
    at com.pcd.ahmed.controller.StudentController.login(StudentController.java:84)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:436)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1078)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)

第一个正在工作,但第二个“StudentRepository1”没有 那么我该如何解决呢?谢谢你

【问题讨论】:

  • 第二种方法到底怎么行不通?
  • 你遇到了什么错误?
  • 我确实修改它放了错误

标签: spring hibernate jakarta-ee


【解决方案1】:

你没有在 StudentServiceImpl 中连接你的 studentRepository1

我在我的 IDE 中重现了该错误。请更新下面看到的这个块,然后一切都会好起来的。

@Autowired
private StudentRepository studentRepository;
@Autowired
private StudentRepository1 studentRepository1;

【讨论】:

  • @Autowired private StudentRepository1 studentRepository1;
  • 在堆栈跟踪中,它表明在 studentget() 方法中有一些 null。我相信它是 com.pcd.ahmed.service.StudentServiceImpl.studentget(StudentServiceImpl.java:42) 处的 studentRepository1 java.lang.NullPointerException
  • 是的,但是@Autowired 不能用于一个以上的异常,并且在过去 3 天没有结果的情况下搜索解决方案
  • 它没有用。我尝试了但仍然不接受 2 @Autowired 所以即使其他页面也变成错误
【解决方案2】:

我认为您只是在 HQL 中有错字。而不是etudiants,尝试将其更改为Etudiant

@Repository("studentRepository1")
public interface StudentRepository1 extends JpaRepository<Etudiant, String> {

    // "Etudiant" was previously "etudiants"
    @Query("select s from Etudiant s where s.student_ID = :student_ID")
    Etudiant findBystudent_ID(@Param("student_ID") String student_ID);

}

更新 您在上面的问题中仍然缺少@Autowired

@Autowired
private StudentRepository studentRepository;
private StudentRepository1 studentRepository1;

需要:

@Autowired
private StudentRepository studentRepository;

@Autowired
private StudentRepository1 studentRepository1;

由于您一直在编辑问题,因此跟踪您的问题也很令人困惑。

【讨论】:

  • 我试过了,但还是一样的问题
  • 还要检查数据库表中的列名。从编码标准的角度来看,您确实应该为实体中的每个字段使用 @Column 注释,例如 @Column(name = "STUDENT_ID")
  • 我确实修改了问题并将错误放在最后
  • 这不是一个完整的异常堆栈跟踪。 “在 com.pcd.ahmed.service.StudentServiceImp”之前是什么?
  • 我一直加的