spring-data-jpa 在springBoot JPA中,findById()只接受整数类型的id,我想通过emailID来查找它,有没有类似findByEmailId的方法?

c8ib6hqw  于 2022-11-10  发布在  Spring
关注(0)|答案(4)|浏览(123)

我正在使用SpringBootApplication和JPA来定义控制器Map并执行CRUD操作。我想通过emailId从数据库中获取学生详细信息。我已经在DAO中编写了SQL查询,但它返回的sql行是String格式。我如何Map到StudentDetail对象?findById只接受整数类型的ID。我想通过emailID查找它。有没有类似findByEmailId的方法?
StudentDetail.java

@Table(name="studentpersonaldetails")
@Entity
public class StudentDetail {

    @Id
    @Column(name="emailid")
    String emailId;
    @Column(name="firstname")
    String firstName;
    @Column(name="lastname")
    String lastName;
    @Column(name="mobilenumber")
    String mobileNumber;
    String address;
    String batch;
    String course;
    String gender;
    String year;

    Paramaterised constructor, getters-setters &  toString method 
}

StudentController.java

@GetMapping("/getpersonaldetails/{emailId}")
    public StudentDetail getPersonalDetails(@PathVariable String emailId)
    {
        emailId = emailId.substring(1);
        return studentService.getPersonalDetails(emailId);      
    }

StudentService.java

public StudentDetail getPersonalDetails(String emailId) {   
        return studentDao.getPersonalDetails(emailId);
}

StudentDAO.java

@Query(value = "SELECT * FROM studentpersonaldetails WHERE emailId=?1", nativeQuery = true)
    StudentDetail getPersonalDetails(String emailId);

错误

org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.String] to type [com.cdac.hms.model.StudentDetail]
kyxcudwk

kyxcudwk1#

您可以创建一个StudentDetail类型的新对象,并使用来自的结果构建它吗?然后返回

var results = studentService.getPersonalDetails(emailId); 
StudentDetail sd = new StudentDetail(results);
return sd;
h5qlskok

h5qlskok2#

查询不正确,您必须更改参数。
请尝试以下代码:

@Query(value = "SELECT * FROM studentpersonaldetails WHERE emailId= :emailId", nativeQuery = true)
    StudentDetail getPersonalDetails(String emailId);
nlejzf6q

nlejzf6q3#

您不需要原生查询就可以完成这个简单的操作。

@Query("SELECT student FROM studentpersonaldetails student WHERE student.emailId= :emailId")
StudentDetail findStudentByEmailId(@Param("emailId") String emailId);

注意:我已经添加了param name并在Query中使用了它。

5jvtdoz2

5jvtdoz24#

根据这一点:https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.query-creation
您可以拥有:StudentDAO.java

public interface StudentDAO extends Repository<StudentDetail, String> {
  Optional<StudentDetail> findByEmailId(String emailId);
}

您也可以使用普通StudentDetail代替Optional

相关问题