在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());
}
以上是兩種常見的一對多映射的配置方式。具體選擇哪種方式取決于實際需求和使用場景。