为什么在使用JPA注释时不能将String作为主键?
我正在尝试创建具有字符串类型作为ID的注册页面。并获取IdentifierGenerationException异常:
org.hibernate.id.IdentifierGenerationException:此类的ID必须在调用save()之前手动分配
HomeController.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HomeController
{
@Autowired
StudRepo repo;
@RequestMapping("/home")
public void addStud(@ModelAttribute("students") Students students)
{
repo.save(students);
}
}
POJO :
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Students
{
@Id
private String name;
private String grade;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
@Override
public String toString() {
return "Students [name=" + name + ", grade=" + grade + "]";
}
}
Repo:
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Component;
@Component
public interface StudRepo extends JpaRepository<Students, String>
{
}
JSP :
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="students" method="get">
Student Name : <input type="text" name="name" /> <br> Student
Grade : <input type="text" name="grade" /> <br>
<input type="submit" name="Log Me In" />
</form>
</body>
</html>
Error :
ids for this class must be manually assigned before calling save(): com.example.demo.Students; nested exception is org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): com.example.demo.Students
为什么在使用JPA注释时不能将String作为主键?
我希望将String作为创建的主键表。