91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

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
合肥市| 突泉县| 铅山县| 南岸区| 梁山县| 西乌| 绵竹市| 开鲁县| 吉木乃县| 宁阳县| 莫力| 望奎县| 淅川县| 江口县| 晋中市| 临颍县| 韶山市| 禹州市| 南宁市| 云安县| 无锡市| 嫩江县| 多伦县| 城市| 渭南市| 石屏县| 鱼台县| 金塔县| 上高县| 娱乐| 周至县| 北票市| 麦盖提县| 金门县| 丁青县| 神农架林区| 沁水县| 兴仁县| 马边| 乌审旗| 南阳市|