我有3个表,'menu','ingredients'和'menu-ingredients'(这一个包含外键)检查图像-Database
现在,当我在Menu.java类中设置一对多关系时,hibernate会以某种方式认为我在其上具有批注的 list 是表名:
Ingredients.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
Menu.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
答案 0 :(得分:0)
您的数据库中有一个关联表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
:第三张表的相关列
关联实体(成分)。