Java 使用SELECT new from JPA时如何处理null
我使用Jpa和Spring,但当我从db获取数据时遇到了问题 实体Java 使用SELECT new from JPA时如何处理null,java,spring,spring-boot,jpa,spring-data-jpa,Java,Spring,Spring Boot,Jpa,Spring Data Jpa,我使用Jpa和Spring,但当我从db获取数据时遇到了问题 实体 @Entity public class Employee { @Id private String id private String noteId private String email //get and set } @Entity public class Note{ @Id private String id private String value p
@Entity
public class Employee {
@Id
private String id
private String noteId
private String email
//get and set
}
@Entity
public class Note{
@Id
private String id
private String value
private String description
//get and set
}
我使用JPA接收来自数据库的所有信息,其中包含两个表note和Employee。
我写的查询看起来像
存储库
@Query("SELECT NEW com.example.response.ResponseDto(e.id,e.email,n.description,n.value) FROM Employee e JOIN NOTE n ON e.noteId = n.id WHERE e.id = :id and n.value = :value")
ResponseDto findAllEmployeeAndNote(String id, String value)
当我在数据库中输入正确的id和值时。我得到了成功的回应。但当我在数据库中输入id和值时,却找不到。JPA抛出异常:结果不能为空
我希望自定义消息
结果不能为空
并引发我的自定义异常。如何处理它捕获JPA异常并抛出您的自定义异常(理想情况下将JPA异常设置为原因)?@Thomas您的意思是当我调用findAllEmployeeAndNote时,我使用的是try Catch it?请您在使用findAllEmployeeAndNote
的地方添加代码。您可以返回Optional
谢谢。可选或尝试捕获也可以工作。非常感谢