Home > AI > Backend > SpringBoot > mysql-connector-java >

@Id

Example 1:

@Entity
@Table(name = "STUDENTS")
class Student {

    @Id
    private long studentId;


}


interface StudentRepository extends JpaRepository<Student, Long> { }

@RestController
class StudentController {
    @Autowired
    StudentRepository studentRepository;

    @GetMapping("/saveStudent")
    public String save() {
        Student s = new Student();
        studentRepository.save(s);
        return "hello";
    }
}


Result: only save one record with id = 0

Example 2:

Entity
@Table(name = "STUDENTS")
class Student {

    @Id
    private long studentId;

    private String name;
    Student(String name){
        this.name = name;
    }


}


interface StudentRepository extends JpaRepository<Student, Long> { }

@RestController
class StudentController {
    @Autowired
    StudentRepository studentRepository;

    @GetMapping("/saveStudent")
    public String save() {
        Student s = new Student("mary");
        studentRepository.save(s);
        return "hello";
    }
}


Result: same as above. Only save one record with id = 0

Example 3:

@Entity
@Table(name = "STUDENTS")
class Student {

    @Id
    private long studentId;

    private String name;
    Student(String name){
        this.name = name;
    }

}



interface StudentRepository extends JpaRepository<Student, Long> { }

@RestController
class StudentController {
    @Autowired
    StudentRepository studentRepository;

    @GetMapping("/saveStudent")
    public Student save() {
        Random r = new Random();
        Student s = new Student(String.valueOf(r.nextInt()));
        return studentRepository.save(s);
    }
}

Result: same as above. Only save one record with id = 0

Leave a Reply