当前位置: 首页 > 知识库问答 >
问题:

Spring Data JPA ManyToOne双向

盖辉
2023-03-14
@Entity
public class Department {
    @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int id;
    private String name;

    @OneToMany(mappedBy="department")
    private Collection<Student> students;

    public Department() {
    }

    public Department(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public Collection<Student> getStudents() {
        return students;
    }

    public void setStudent(Collection<Student> students) {
        this.students = students;
    }

    public String toString() {
        return "Department id: " + getId() +
                ", name: " + getName();
    }
}



@Entity
public class Student {
    @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int id;
    private String name;

    @ManyToOne (cascade=CascadeType.ALL)
    private Department department;

    public Student() {
    }

    public Student(String name, Department department) {
        this.name = name;
        this.department = department;
    }

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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



    public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }

    public String toString() {
        return "\n\nID:" + id + "\nName:" + name + "\n\n" + department;
    }
}
@Repository
public interface DepartmentRepository extends JpaRepository<Department, Integer> {
    Department findByName(String name);

}

@Repository
public interface StudentRepository extends JpaRepository<Student, Integer> {
    Student findByName(String name);
}

服务

@Service
public class StudentService {
    private final StudentRepository studentRepository;

    @Autowired
    public StudentService(StudentRepository studentRepository) {
        this.studentRepository = studentRepository;

    }

    public void addToDatabase(Student student) {
        this.studentRepository.saveAndFlush(student);

    }

    public Student getStudentByName(String name) {
        return studentRepository.findByName(name);
    }
}
@Service
public class DepartmentService {
    private final DepartmentRepository departmentRepository;

    @Autowired
    public DepartmentService(DepartmentRepository departmentRepository) {
        this.departmentRepository = departmentRepository;

    }

    public void addToDataBase(List<Department> department) {
        this.departmentRepository.save(department);
        department.forEach(this.departmentRepository::saveAndFlush);
    }
    public Department getDepartmentByName(String name){
        return  this.departmentRepository.findByName(name);
    }
}

我的主要方法

@Component
public class Terminal implements CommandLineRunner {
    private final StudentService studentService;
    private final DepartmentService departmentService;

    @Autowired
    public Terminal(StudentService studentService, DepartmentService departmentService) {
        this.studentService = studentService;
        this.departmentService = departmentService;
    }

        @Override
        public void run(String... strings) throws Exception {
            Department department = new Department("dep1");
            Department department1 = new Department("dep2");
            Department department2 = new Department("dep3");
            Department department3 = new Department("dep4");
            List<Department> departments = new ArrayList<>(Arrays.asList(department, department1, department2, department3));
            this.departmentService.addToDataBase(departments);
    //
            Student student = new Student("pesho", department);
            Student student11 = new Student("gosho", department1);
            this.studentService.addToDatabase(student11);
            this.studentService.addToDatabase(student);
            student = new Student("sasho", department2);
            this.studentService.addToDatabase(student);
    //        System.out.println(this.studentService.getStudentByName("gosho").getDepartment1());
    //        System.out.println("CHECKING ONE TO ONE BIDIRECTIONAL: " + this.departmentService.getDepartmentByName("dep1").getStudent());

        }
    }

所以在这里,当我尝试在students表中添加学生时,它给出了一个错误,错误是Falling

Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist: app.models.Department

共有1个答案

苗盛
2023-03-14

您为学生类中的部门添加了Cascade=CascadeType.All并将部门保存为separete。This.DepartmentService.AddToDatabase(departments);

修复:不呼叫

departmentService.addToDataBase(departments);

或从学生中删除CascadeType.All

 类似资料:
  • 问题内容: 我们的应用程序使用无限滚动来浏览大量异构项目列表。有一些皱纹: 对于我们的用户来说,通常有10,000个项目的列表,并且需要滚动3k +。 这些都是丰富的项目,因此在浏览器性能变得无法接受之前,我们只能在DOM中拥有几百个。 这些物品的高度各不相同。 这些项目可能包含图像,我们允许用户跳转到特定日期。这很棘手,因为用户可以跳到列表中需要在视口上方加载图像的位置,这会在加载时将内容下推。

  • 我有一个关于浮点数的机器ε的天真问题。 我们知道,双浮点数的机器ε约为10^-16,而浮点数的最小严格正值可以小到10^{-300}。既然机器ε是相对误差的上限,那么使用这个比机器ε小得多的数字10^{-300}有什么意义呢? 我一定是误解了浮点表示。你能澄清一下吗?

  • 本文向大家介绍双向链表和双向循环链表?相关面试题,主要包含被问及双向链表和双向循环链表?时的应答技巧和注意事项,需要的朋友参考一下 双向链表: 包含两个指针,一个prev指向前一个节点,一个next指向后一个节点。 双向循环链表: 最后一个节点的 next 指向head,而 head 的prev指向最后一个节点,构成一个环。

  • 问题内容: 我有2个类:User和UserPicture具有1:1的关系。 UserPicture中的“ user”将被加载,而UserPicture中的“ userPicture”则不会加载-我错了吗? 编辑 必须添加,我只是创建一个UserPicture并插入它们(使用现有的userId)-也许我需要在UserPicture中级联“ user”? 问题答案: 您必须映射您的课程。

  • 主要内容:双向链表的创建目前我们所学到的 链表,无论是动态链表还是 静态链表,表中各节点中都只包含一个指针(游标),且都统一指向直接后继节点,通常称这类链表为 单向链表(或 单链表)。 虽然使用单链表能 100% 解决逻辑关系为 "一对一" 数据的存储问题,但在解决某些特殊问题时,单链表并不是效率最优的存储结构。比如说,如果算法中需要大量地找某指定结点的前趋结点,使用单链表无疑是灾难性的,因为单链表更适合 "从前往后"

  • Output after 4 epochs on CPU: ~0.8146. Time per epoch on CPU (Core i7): ~150s. 在 CPU 上经过 4 个轮次后的输出:〜0.8146。 CPU(Core i7)上每个轮次的时间:〜150s。 from __future__ import print_function import numpy as np from k

  • 例如,我正在进行web自动化测试,假设我有两个非常基本的场景: 测试a)步骤1:将记录添加到数据库步骤2:检查网站是否正确显示记录 测试b)步骤1:在网站上编辑记录步骤2:检查记录是否正确保存在数据库中 根据记录,假设它是一个带有“值”的简单文本字段 因此,对于第一种情况,我将使用Assert equal: 但是,对于第二种情况,它将是: 所以基本上它们都做相同的事情,但都是相反的,为了在断言不正

  • Mpx针对表单组件提供了wx:model双向绑定指令,类似于v-model,该指令是一个语法糖指令,监听了组件抛出的输入事件并对绑定的数据进行更新,默认情况下会监听表单组件的input事件,并将event.detail.value中的数据更新到组件的value属性上。 简单实用示例如下: <view> <input type="text" wx:model="{{message}}"> <