【问题标题】:One-to-many : java.sql.SQLSyntaxErrorException: Table 'table_name' doesn't exist一对多:java.sql.SQLSyntaxErrorException:表'table_name'不存在
【发布时间】:2019-01-15 09:19:09
【问题描述】:

我有 3 个表,“菜单”、“成分”和“菜单成分”(这个包含外键)检查图像 - Database

现在,当我在 Menu.java 类中设置一对多关系时,休眠以某种方式认为我有注释的 list 是表名:

成分.java:

@Entity
@Table(name = "ingredients")
public class Ingredients {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;

@Column(name = "ingredient")
private String ingredientName;

@Column(name = "description")
private String ingredientDescription;
//Getters/Setters/Constructor

菜单.java:

@Entity
@Table(name = "menu")
public class Menu {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;

@Column(name = "name")
private String name;

// Mapping To second table
@OneToMany(cascade = CascadeType.ALL)
private List<Ingredients> ingridients = new ArrayList<>();
// notice the name of this list 'ingridients' and then check the stacktrace.

主类:

@SpringBootApplication
public class RecipeappApplication implements CommandLineRunner {

@Autowired
RecipeRepository recipeRepository;

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

}

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

    Menu menu = new Menu("Pizza");
    menu.getIngridients().add(new Ingredients("Cheese","3 slices"));
    menu.getIngridients().add(new Ingredients("Bacon","3 pieces"));


    recipeRepository.save(menu);
    //recipeRepository.save() <- is just the entitymanager.persist() call.
}

和错误:

java.lang.IllegalStateException: Failed to execute CommandLineRunner
...
Caused by: org.springframework.dao.InvalidDataAccessResourceUsageException: could not execute statement; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not execute statement
...
Caused by: org.hibernate.exception.SQLGrammarException: could not execute statement
...
Caused by: java.sql.SQLSyntaxErrorException: Table 'recipe.menu_ingridients' doesn't exist

【问题讨论】:

  • 为什么不定义一个连接列?
  • 在定义@JoinColumn(name = "menu_id") 后:原因:java.sql.SQLSyntaxErrorException: Unknown column 'menu_id' in 'field list'

标签: java mysql hibernate spring-boot jpa


【解决方案1】:

在您的数据库中,您有一个关联表 menu_ingredient,因此您需要使用 @JoinTable 对其进行映射:

@OneToMany(cascade = CascadeType.ALL)
@JoinTable(name = "menu_ingredient",
        joinColumns = @JoinColumn(name = "menu_id"),
        inverseJoinColumns = @JoinColumn(name = "ingredient_id"))
private List<Ingredients> ingredients;
  • @JoinTable 注解用于使用第三张表连接两个表(此处为menu_ingredient
  • joinColumns:与当前实体(菜单)相关的第三个表的列。
  • inverseJoinColumns:第三张表的列相关 关联实体(成分)。

【讨论】:

  • 哦,谢谢它有效! :) 你能解释一下 JoinTable/JoinColumn/InverseJoinColumns 的作用吗?我一边写代码一边努力学习,所以我真的不知道这个注解是做什么的。
  • 我已经更新了我的答案,但您可能想查看有关 JPA 实体关系的教程。例如this
猜你喜欢
  • 2017-12-09
  • 2015-05-24
  • 2020-01-05
  • 2023-04-04
  • 2016-08-18
  • 2016-08-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多