如何在定义JpaRepository的自定义接口时指定复合主键?

huangapple go评论61阅读模式
英文:

How to specify a Composite Primary Key while defining a Custom Interface as a JpaRepository?

问题

class Parent {
    @Id
    String columnA;

    String columnB;
}

class Child {
    @Id
    @ManyToOne
    @JoinColumn(name = "columnA") // Foreign key referencing Parent's columnA
    Parent parent; // ManyToOne relationship with Parent class

    @Id
    String columnC;
    
    String columnD;
}
public interface ChildRepository extends JpaRepository<Child, String> {
    // The composite primary key is made up of columnA and columnC
}
英文:

I have two Entity class with below attributes:

class Parent {
    @Id
    string columnA;

    string columnB;
}

class Child {
    //confused here: ManyToOne with Parent class
    
    string columnC;
    string columnD;
}

I want SQL Tables as below:

  1. Parent ( columnA(Primary Key), columnB )
  2. Child ( columnA(Foreign Key), columnC, columnD ) where,
  • primary key = (columnA, columnC) and,
  • (Child -> ManyToOne -> Parent) relationship.

Question1: How can I create the correct Entity class for the Child?

Question2: I want to have a childRepository interface that extends JpaRepository. I am confused, how to specify the composite primary key?

public interface childRepository extends JpaRepository&lt;Child, &#39;What to write here?&#39;&gt;{
}

答案1

得分: 1

Question-1: 这取决于您的业务逻辑。
Question-2: 创建新的类以存储子实体的标识

@Embeddable
public class ChildId implements Serializable{

   private String columnA;
   private String columnC;
   
   // getters and setters
}

在您的子类中

@EmbeddedId
private ChildId childId;

@MapsId(value = "columnA")
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "columnA")
private Parent parent;

在您的 ChildRepository 中

public interface ChildRepository extends JpaRepository<Child, ChildId>{}

PS根据业务逻辑您可以应用其他方法
英文:

Question-1: It depends on your business logic.<br/>
Question-2: Create new class in order to store child entity's ids

@Embeddable
public class ChildId implements Serializable{
   
   private String columnA;
   private String columnC;
   
   // getters and setters
}

In your child class:

@EmbeddedId
private ChildId childId;

@MapsId(value = &quot;columnA&quot;)
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = &quot;columnA&quot;)
private Parent parent;

In your ChildRepository:

public interface ChildRepository extends JpaRepository&lt;Child, ChildId&gt;{}

PS: you can apply other ways according to business logic

huangapple
  • 本文由 发表于 2020年5月30日 15:00:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/62098976.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定