Вызвано: java. sql .SQLSyntaxErrorException: в синтаксисе SQL возникла ошибка; проверьте руководство, соответствующее вашей MySQL версии сервера - PullRequest
0 голосов
/ 29 февраля 2020

Я новичок в Hibernate и пытаюсь поработать над отношениями «один ко многим» с кодом ниже, но я получаю исключения. Может кто-нибудь помочь мне, пожалуйста, где я ошибаюсь

MainClass

@SpringBootApplication
public class TicketBookingManagementAppApplication implements CommandLineRunner {

    @Autowired
    PostsRepository postsRepository;

    public static void main(String[] args) {
        SpringApplication.run(TicketBookingManagementAppApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {

        Comments comments1 = new Comments();
        comments1.setName("comment1");
        comments1.setDesc("desc1");

        Comments comments2 = new Comments();
        comments2.setName("comment2");
        comments2.setDesc("desc2");

        Posts posts = new Posts();
        posts.setName("post5");
        posts.getComments().add(comments1);
        posts.getComments().add(comments2);

        postsRepository.save(posts);
    }
}

Сообщений

@Entity
@Table(name = "posts")
public class Posts {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int post_id;
    private String name;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "posts", cascade = CascadeType.ALL)
    private Set<Comments>comments=new HashSet<>();

    public int getPost_id() {
        return post_id;
    }
    public void setPost_id(int post_id) {
        this.post_id = post_id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Set<Comments> getComments() {
        return comments;
    }

    public void setComments(Set<Comments> comments) {
        this.comments = comments;
    }

}

Комментарии:

@Entity
@Table(name = "comments")
public class Comments {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int comment_id;
    private String name;
    private String desc;

      @ManyToOne
      @JoinColumn(name = "post_id", nullable = false)
    private Posts posts;

    public int getComment_id() {
        return comment_id;
    }
    public void setComment_id(int comment_id) {
        this.comment_id = comment_id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getDesc() {
        return desc;
    }
    public void setDesc(String desc) {
        this.desc = desc;
    }

}

Исключение

Caused by: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc, name, post_id) values ('desc1', 'comment1', null)' at line 1

enter image description here

1 Ответ

1 голос
/ 29 февраля 2020

Дочерний объект содержит отношения, поэтому вам нужно установить родительское поле:

@Override
public void run(String... args) throws Exception {

    Comments comments1 = new Comments();
    comments1.setName("comment1");
    comments1.setDesc("desc1");

    Comments comments2 = new Comments();
    comments2.setName("comment2");
    comments2.setDesc("desc2");

    Posts posts = new Posts();
    comments1.setPosts(posts);
    comments2.setPosts(posts);
    posts.setName("post5");
    posts.getComments().add(comments1);
    posts.getComments().add(comments2);

    postsRepository.save(posts);
}

Редактировать: Проблема в том, что вы назвали свое поле desc, ведьма будет переведена в имя столбца desc. Это зарезервированное ключевое слово в sql (order by ... desc).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...