亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

java一對多映射怎么配置

小億
116
2023-12-14 03:22:39
欄目: 編程語言

在Java中,一對多映射可以使用集合來實現。常見的一對多映射關系有兩種方式:List和Map。

  1. 使用List實現一對多映射:
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());
}
  1. 使用Map實現一對多映射:
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());
}

以上是兩種常見的一對多映射的配置方式。具體選擇哪種方式取決于實際需求和使用場景。

0
沙湾县| 抚顺市| 琼中| 文登市| 库车县| 旬阳县| 云林县| 司法| 慈利县| 义乌市| 拉萨市| 永善县| 寿宁县| 旬邑县| 开原市| 百色市| 花莲市| 湖口县| 蓬安县| 乾安县| 诏安县| 绵竹市| 大英县| 汽车| 景谷| 武安市| 云林县| 麦盖提县| 洛南县| 丁青县| 西畴县| 娄底市| 扎囊县| 清丰县| 闸北区| 景德镇市| 永康市| 波密县| 新乡县| 吴忠市| 远安县|