英文:
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:
- Parent ( columnA(Primary Key), columnB )
- 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<Child, 'What to write here?'>{
}
答案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 = "columnA")
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "columnA")
private Parent parent;
In your ChildRepository:
public interface ChildRepository extends JpaRepository<Child, ChildId>{}
PS: you can apply other ways according to business logic
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论