在Java中,一对多映射可以使用集合来实现。常见的一对多映射关系有两种方式:List和Map。
public class OneToManyMapping {
private List<ManyEntity> manyList;
// 构造方法
public OneToManyMapping() {
manyList = new ArrayList<>();
}
// 添加多个实体到列表中
public void addManyEntity(ManyEntity manyEntity) {
manyList.add(manyEntity);
}
// 获取所有多个实体
public List<ManyEntity> getManyList() {
return manyList;
}
}
public class ManyEntity {
private String name;
// 构造方法
public ManyEntity(String name) {
this.name = name;
}
// 获取实体名称
public String getName() {
return name;
}
}
// 使用示例
OneToManyMapping oneToManyMapping = new OneToManyMapping();
oneToManyMapping.addManyEntity(new ManyEntity("Entity 1"));
oneToManyMapping.addManyEntity(new ManyEntity("Entity 2"));
List<ManyEntity> manyList = oneToManyMapping.getManyList();
for (ManyEntity manyEntity : manyList) {
System.out.println(manyEntity.getName());
}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class OneToManyMapping {
private Map<String, List<ManyEntity>> manyMap;
// 构造方法
public OneToManyMapping() {
manyMap = new HashMap<>();
}
// 添加多个实体到映射中
public void addManyEntity(String key, ManyEntity manyEntity) {
if (manyMap.containsKey(key)) {
manyMap.get(key).add(manyEntity);
} else {
List<ManyEntity> manyList = new ArrayList<>();
manyList.add(manyEntity);
manyMap.put(key, manyList);
}
}
// 获取指定key的多个实体
public List<ManyEntity> getManyEntities(String key) {
return manyMap.get(key);
}
}
public class ManyEntity {
private String name;
// 构造方法
public ManyEntity(String name) {
this.name = name;
}
// 获取实体名称
public String getName() {
return name;
}
}
// 使用示例
OneToManyMapping oneToManyMapping = new OneToManyMapping();
oneToManyMapping.addManyEntity("Key 1", new ManyEntity("Entity 1"));
oneToManyMapping.addManyEntity("Key 1", new ManyEntity("Entity 2"));
oneToManyMapping.addManyEntity("Key 2", new ManyEntity("Entity 3"));
List<ManyEntity> manyList1 = oneToManyMapping.getManyEntities("Key 1");
for (ManyEntity manyEntity : manyList1) {
System.out.println(manyEntity.getName());
}
List<ManyEntity> manyList2 = oneToManyMapping.getManyEntities("Key 2");
for (ManyEntity manyEntity : manyList2) {
System.out.println(manyEntity.getName());
}
以上是两种常见的一对多映射的配置方式。具体选择哪种方式取决于实际需求和使用场景。