java复合主键未映射
表:
CREATE TABLE `parent_table` (
`parent_id` int NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`parent_id`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
CREATE TABLE `child_table` (
`child_id` int NOT NULL AUTO_INCREMENT,
`parent_id` int NOT NULL,
PRIMARY KEY (`child_id`,`parent_id`),
FOREIGN KEY `fk2` (`parent_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
实体类:
@Setter
@Getter
@Entity
@Table(name = "parent_table")
public class Parent implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "parent_id")
private int parentId;
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL,orphanRemoval = true)
private List<Child> childs=new ArrayList<Child>();
}
@Getter
@Setter
@EqualsAndHashCode
public class ChildPK implements Serializable {
//default serial version id, required for serializable classes.
private static final long serialVersionUID = 1L;
@Column(name="parent_id",nullable = false)
private int parentId;
@Column(name="child_id")
private int childId;
}
@Getter
@Setter
@EqualsAndHashCode
@Entity
@IdClass(ChildPK.class)
@Table(name = "child_table")
public class Child implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name="child_id")
private int childId;
@Id
@TableGenerator(name = "child_id_generator", table = "id_sequence", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.TABLE, generator = "child_id_generator")
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "parent_id",insertable = false,updatable = false)
private Parent parent;
}
class MainClass{
public static void main(String[] args)
{
entityManager.persist(parent);//in child_table parent_id storing as 0
}
}
在子表中,父id列作为外键和复合主键的一部分
嵌入类内部无法使用标识生成器。所以我在这里使用ID类。为子_id列生成自动增量值
我无法将从父\u表生成的父\u id值作为外键值存储到子\u表中,它将存储为0
有人能帮我检查一下映射吗
提前谢谢
# 1 楼答案
# 2 楼答案
如果子id已经是唯一的,为什么需要父id作为主键的一部分?只需使用: