【问题标题】:How to join 2 tables without the unique key variables declared explicitly?如何在没有明确声明的唯一键变量的情况下加入 2 个表?
【发布时间】:2022-08-21 15:37:55
【问题描述】:

JPA 在没有明确声明的唯一键变量的情况下加入 2 个表?

我有这两张桌子,学生可以在那里借很多书。

D B:

book
    - id
    - book_name
    - student_id
    
    
student
    -id
    -student_name

JPA:

实体 :

  @Entity (\"book\")
    class Book {

    @Column (\"book_name\")
    private String bookName;
    
        @ManyToOne
       @JoinColumn(name = \"student_id\", insertable=false, updatable=false)
       private Student student;
    
    ..
    ..
    }

学生实体:

  @Entity (\"student\")
    class Student {
    
    @Column (\"student_name\")
    private String student_name;
    
    
       @OneToMany(mappedBy = \"student\")
    private List <Book> book;
    ..
    }
    

出于某种原因,它抱怨

org.springframework.orm.jpa.JpaObjectRetrievalFailureException: Unable to find com.Student with id 7402

  • 你能展示一下它抛出异常的代码吗?还有几行堆栈跟踪?你为什么不使用@Id 字段?

标签: java jpa one-to-many


【解决方案1】:

这些表没有通过任何一个这样的内部关系FK字段。即使两个表清楚地共享同一列,也没有任何连接。这使得映射操作JPA偏硬。

我最终只是宣布这样的:

@Id
private Long id;

除此之外,我的实体更具可读性。

最后管理任何CRUD通过 Spring Data JPA (JpaRepository) 进行操作。并利用@Query 进行检索,因为此注释似乎独立于基础表/模式关系。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-30
    • 2019-07-22
    • 1970-01-01
    • 1970-01-01
    • 2020-05-21
    • 1970-01-01
    • 2023-02-24
    • 1970-01-01
    相关资源
    最近更新 更多