gpt4 book ai didi

java - 无法在 Hibernate 中保存多对多关系

转载 作者:行者123 更新时间:2023-12-02 12:57:15 24 4
gpt4 key购买 nike

这实在是让我很困惑。

我有以下类(class):

Ingredient.java

@Entity
@Table(name = "INGREDIENTS", uniqueConstraints =
{@UniqueConstraint(columnNames = "NAME")})
public class Ingredient implements Serializable{

@Id
@GeneratedValue
@Column(name = "ingredient_id")
private Long id;

@Column(nullable = false, name = "name")
private String name;

@Column(nullable = false, name = "name")
private Long calories;

public Ingredient() {
}

public Ingredient(String name, Long calories) {
this.name = name;
this.calories = calories;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Long getCalories() {
return calories;
}

public void setCalories(Long calories) {
this.calories = calories;
}

public Long getId(){
return this.id;
}

public void setId(Long id) {
this.id = id;
}

}

Meal.java

@Entity
@Table(name = "MEALS")
public class Meal implements Serializable {

@ManyToOne
private User user;

@Id
@GeneratedValue
@Column(name = "meal_id")
private Long id;

@ElementCollection(targetClass = Ingredient.class)
private Set<Ingredient> ingredients = new HashSet<>(0);

//More fields and constructors

@ManyToMany(targetEntity = Ingredient.class, cascade = CascadeType.ALL)
@JoinTable(name = "ingredient_meal", joinColumns = {@JoinColumn(name = "meal_id")}, inverseJoinColumns = {@JoinColumn(name = "ingredient_id")})
public List<Ingredient> getIngredients() {
return ingredients;
}

public void setIngredients(List<Ingredient> ingredients) {
this.ingredients = ingredients;
}


public Long getId(){
return this.id;
}

public void setId(Long id) {
this.id = id;
}

这是我保存实体的代码:

SessionFactory sessionFactory = 
entityManagerFactory.unwrap(SessionFactory.class);

Session session = sessionFactory.openSession();
session.beginTransaction();

/***/
Meal coolMeal = new Meal(user, new Date(115, 0, 8), new Time(19, 0, 0), "8 -
Moules Frites", 1000L);
coolMeal.getIngredients().add(new Ingredient("Fish2", 100L));
session.persist(coolMeal);
try{
session.getTransaction().commit();
}catch(Throwable e){
e.printStackTrace();
throw e;
}
session.close();

但我不断收到此异常:

org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: calories.tracker.app.model.Ingredient
at org.hibernate.engine.internal.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:294)
at org.hibernate.type.EntityType.getIdentifier(EntityType.java:537)
at org.hibernate.type.ManyToOneType.nullSafeSet(ManyToOneType.java:165)
at org.hibernate.persister.collection.AbstractCollectionPersister.writeElement(AbstractCollectionPersister.java:899)
at org.hibernate.persister.collection.AbstractCollectionPersister.recreate(AbstractCollectionPersister.java:1308)
at org.hibernate.action.internal.CollectionRecreateAction.execute(CollectionRecreateAction.java:67)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:463)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:349)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:350)
at

但是,如果我以这种方式保留对象:

    Ingredient i1 = new Ingredient("Potatoes2", 100L);
session.persist(i1);
Meal coolMeal = new Meal(user, new Date(115, 0, 8), new Time(19, 0, 0),
"8 - Moules Frites", 1000L);
coolMeal.getIngredients().add(i1);

效果很好,为什么呢?一切都和here一模一样.

最佳答案

您为 ingredients 字段声明两个映射。
一个在现场,另一个在 setter/getter 中:

@ElementCollection(targetClass = Ingredient.class)
private Set<Ingredient> ingredients = new HashSet<>(0);
....
@ManyToMany(targetEntity = Ingredient.class, cascade = CascadeType.ALL)
@JoinTable(name = "ingredient_meal", joinColumns = {@JoinColumn(name = "meal_id")}, inverseJoinColumns = {@JoinColumn(name = "ingredient_id")})
public List<Ingredient> getIngredients() {
return ingredients;
}

您应该删除该字段的注释:

@ElementCollection(targetClass = Ingredient.class)

@ElementCollection 旨在映射非实体类,而 Ingredient 是实体:

根据 Javadoc:

元素集合

Defines a collection of instances of a basic type or embeddable class

关于java - 无法在 Hibernate 中保存多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44394954/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com