代码之家  ›  专栏  ›  技术社区  ›  corydoras

使用不是主键字段映射的JPA?

  •  0
  • corydoras  · 技术社区  · 16 年前

    我很难让这个工作起来,我想知道我所做的只是没有意义吗?

    public class Application {
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        @Column(name="id")
        private long id;
        ....
    }
    
    @MappedSuperclass
    public abstract class Sample {
        @Id @GeneratedValue(strategy = GenerationType.AUTO)
        private long id;
    
        @OneToOne (cascade=CascadeType.ALL)
        protected Application application;
        ....
    }
    
    // TestSample contains a list that is mapped not by the primary key of the Sample
    public class TestSample extends Sample {
        @OneToMany(mappedBy="application", cascade=CascadeType.ALL, fetch=FetchType.LAZY)
        private List<Part> parts = new ArrayList<Part>();
        ....
    }
    
    public class Part {
        @Id @GeneratedValue(strategy = GenerationType.AUTO)
        private long id = 0;
    
        @ManyToOne (cascade=CascadeType.ALL, fetch=FetchType.LAZY)
        Application application;
    }
    

    parts 我得到一张空名单。

    如果我通过更改这些类来破坏数据库结构,则可以使其正常工作:

    // TestSample contains a list that is mapped not by the primary key of the Sample
    public class TestSample extends Sample {
        @OneToMany(mappedBy="testSample", cascade=CascadeType.ALL, fetch=FetchType.LAZY)
        private List<Part> parts = new ArrayList<Part>();
        ....
    }
    
    public class Part {
        @Id @GeneratedValue(strategy = GenerationType.AUTO)
        private long id = 0;
    
        @ManyToOne (cascade=CascadeType.ALL, fetch=FetchType.LAZY)
        TestSample testSample;
    }
    

    application
      id : number
      ....
    
    test_sample
      id : number
      application_id : number
      ...
    
    part
      id : number
      application_id : number
    

    如果我将其更改为不太理想的工作方式,则最后一个表会有所不同:

    part
      id : number
      test_sample_id : number
    

    因为id在所有情况下都是自动生成的,所以没有共享的主键。实际上,我要做的是使用mappedby,其中mappedby引用的字段不是名为“TestSample”的表/类的主键。我不确定这在JPA中是否有意义。

    1 回复  |  直到 16 年前
        1
  •  0
  •   Pascal Thivent    16 年前

    OneToMany与“Part”类是双向的。我觉得这很难解释(:

    你的一对多关联 TestSample Part 双向的 mappedBy 不正确(的 application 拥有这种关系,它甚至不知道 test_sample ),你的地图没有意义。有些事情需要改变。

    我认为你应该展示 表不是生成的表(因为映射是不连贯的,所以生成的结果不能令人满意)。你说的是妥协,所以我相信你已经知道了预期的结果。请出示。