如何使用ID插入记录列表?

时间:2013-08-21 00:11:33

标签: java hibernate hibernate-mapping

我有一个类需要添加人员,但我只有人的ID,我需要在将它们关联到myList之前检索所有对象吗?

class People{

 private long id;

 private String name;
 ....
}

class myList{

 private long id;

 @OneToMany
 private List<People> people;
 ...
}

class myModel{
  ....
  {
    List long selectedPeople  <<< has ids such as 8 9 7 6 45 6
    myList mylist = new MyList();
    mylist.setPeople(selectedPeople);
    session.save(mylist);
    ...
  }

1 个答案:

答案 0 :(得分:2)

为什么不这样做

List<People> toSave = new ArrayList<>();

for(Long id : selectedPeople){
   People people = new People();
   people.setId(id);
   toSave.add(people);
}
myList.setPeople(toSave);
session.save(myList);

此外,您的People课程可能会更好Person