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

Self-referencing relationship

Example

@Entity
@Data
class Author {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    long id;

    private Integer author_id;

    @ManyToOne
    @JoinColumn(name = "sponsor_id")
    private Author author;

}

interface AuthorRepository extends JpaRepository<Author, Long> {

}

@RestController
class AuthorController {
    @Autowired
    AuthorRepository authorRepository;

    @GetMapping("/saveStudent")
    public Author save() {
        Author a = new Author();
        a.setAuthor_id(101);
        return authorRepository.save(a);
    }


    @GetMapping("/saveTwo")
    public Author save2() {
        Author a = new Author();
        a.setAuthor_id(102);

        Optional<Author> b = authorRepository.findById(60L);
        a.setAuthor(b.get());
        return authorRepository.save(a);
    }

    @GetMapping("/saveThree")
    public Author save3() {
        Author a = new Author();
        a.setAuthor_id(103);

        Optional<Author> b = authorRepository.findById(60L);
        a.setAuthor(b.get());
        return authorRepository.save(a);
    }

    @GetMapping("/saveFour")
    public Author save4() {
        Author a = new Author();
        a.setAuthor_id(102);

        Optional<Author> b = authorRepository.findById(61L);
        a.setAuthor(b.get());
        return authorRepository.save(a);
    }
}

The table is like

Return of the last record

Leave a Reply