gpt4 book ai didi

java - 非法状态异常 : a relationship that was not marked cascade PERSIST

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

我正在尝试以一对多的方式在 PostgreSQL 数据库中持久保存两个实体“类别”和“问题”(类别有很多问题,一个问题属于一个类别)。

经过大量搜索和尝试,将 CascadeType.PERSIST 添加到两个实体是我发现的错误的唯一解决方案,但在问题侧使用 CascadeType.PERSIST 时,类别表将充满重复项。有没有更好的解决方案,因为表中的类别应该是唯一的。

@Entity
@Table(name = "Category")
public class Category {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "CID")
private int categoryId;
@Column(name = "CNAME")
private String categoryName;
@OneToMany(mappedBy = "category" , cascade = CascadeType.PERSIST)
public List<Question> questions;

@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Category)) {
return false;
}
Category category = (Category) o;
return categoryId == category.categoryId
&& getCategoryName().equals(category.getCategoryName())
&& questions.equals(category.questions);
}

@Override
public int hashCode() {
return Objects.hash(getCategoryName());
}
@Entity
@Table(name = "Question" )
public class Question {
@Id
@Column(name = "QID")
private int id;
@Column(name = "QText")
private String question;
@ManyToOne()
private Category category;



@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Question)) {
return false;
}
Question question = (Question) o;
return getId() == question.getId();
}

@Override
public int hashCode() {
return Objects.hash(getId());
}

public persist(){
EntityManager em = getEntityManager();
em.getTransaction().begin();
for (Category c : data.getCategories()) {
em.persist(c);
}
em.getTransaction().commit();
em.close();
}

最佳答案

我在本地计算机上解决问题的唯一方法是将实体 ID 的类型:int 更改为 Long

基于您的代码的工作示例:

类别实体

package io.ahenteti.java;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@Entity
@Table(name = "Category")
@AllArgsConstructor
@NoArgsConstructor
@NamedQueries({@NamedQuery(name = Category.FIND_ALL, query = "SELECT c FROM Category c")})
public class Category {

public static final String FIND_ALL = "Category.findAll";

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "CID")
private Long categoryId;

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

@OneToMany(mappedBy = "category", cascade = CascadeType.PERSIST)
public List<Question> questions = new ArrayList<>();

@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Category)) {
return false;
}
Category category = (Category) o;
return categoryId == category.categoryId && getCategoryName().equals(category.getCategoryName()) && questions
.equals(category.questions);
}

@Override
public int hashCode() {
return Objects.hash(getCategoryName());
}
}

问题

package io.ahenteti.java;

import java.util.Objects;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@Entity
@Table(name = "Question")
@AllArgsConstructor
@NoArgsConstructor
@NamedQueries({@NamedQuery(name = Question.FIND_ALL, query = "SELECT q FROM Question q")})
public class Question {

public static final String FIND_ALL = "Question.findAll";
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "QID")
private Long id;
@Column(name = "QText")
private String question;
@ManyToOne()
private Category category;

@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Question)) {
return false;
}
Question question = (Question) o;
return getId() == question.getId();
}

@Override
public int hashCode() {
return Objects.hash(getId());
}
}

persistence.xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<persistence
xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd"
version="2.2">

<persistence-unit name="persistence-unit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>io.ahenteti.java.Question</class>
<class>io.ahenteti.java.Category</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:demo"/>
<property name="hibernate.hbm2ddl.auto" value="create"/>
</properties>
</persistence-unit>
</persistence>

主要

package io.ahenteti.java;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
import java.util.List;

public class Main {

public static void main(String[] args) {
EntityManager em = Persistence.createEntityManagerFactory("persistence-unit").createEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
em.persist(createCategory("C1"));
em.persist(createCategory("C2"));
em.persist(createCategory("C3"));
transaction.commit();
System.out.println("number of categories in database: " + getAllCategories(em).size());
System.out.println("number of questions in database: " + getAllQuestions(em).size());
}

private static List<Question> getAllQuestions(EntityManager em) {
TypedQuery<Question> getAllQuestions = em.createNamedQuery(Question.FIND_ALL, Question.class);
return getAllQuestions.getResultList();
}

private static List<Category> getAllCategories(EntityManager em) {
TypedQuery<Category> getAllCategories = em.createNamedQuery(Category.FIND_ALL, Category.class);
return getAllCategories.getResultList();
}

private static Category createCategory(String category) {
Category res = new Category();
res.setCategoryName(category);
for (int i = 0; i < 5; i++) {
res.getQuestions().add(createQuestion(res, category + " - Q" + i));
}
return res;
}

private static Question createQuestion(Category category, String question) {
Question q1 = new Question();
q1.setQuestion(question);
q1.setCategory(category);
return q1;
}

}

输出

number of categories in database: 3
number of questions in database: 15

希望有帮助:)

关于java - 非法状态异常 : a relationship that was not marked cascade PERSIST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59078887/

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