java - 一对多 : java. sql.SQLSyntaxErrorException:表 'table_name' 不存在

标签 java mysql hibernate spring-boot jpa

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

现在,当我在 Menu.java 类中设置一对多关系时,hibernate 会以某种方式认为我有注释的 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

最佳答案

在您的数据库中,您有一个关联表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:第三个​​表相关的列 关联实体(成分)。

关于java - 一对多 : java. sql.SQLSyntaxErrorException:表 'table_name' 不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54195835/

相关文章:

java - java tomcat是以 "first come first serve"形式还是并行处理数据?

java - 如何从元素中获取值?

java - 尝试在 Spring + MySQL 中创建表之间的关系时出错

MYSQL查询匹配符号个数

mysql - 通过mysql更新woocommerce产品名称

java - 如何获取 hibernate 内部属性?

hibernate - 如何确定 hibernate 是否有 'lazy' 加载了代理或真实对象?

java - java中的主线程是否在它可能使用运行时类创建的任何进程完成执行之前完成

php - 无法从 webservice ionic 框架检索数据

hibernate - Grails-DuplicateKeyException