我有一种情况,我必须将OneToMany映射的两个表连接起来。 我想知道Java 8 Stream中是否有一个API可以创建单个实体,左表中的列是普通成员,右表中的列作为值列表。
示例数据:
表1
id name
1 abc
表2
id table1_id note
1 1 qwerty
2 1 asdfgh
3 1 zxcvbn
联接这两个表。我得到这样的东西
select name, note from table1 join table2 on table2.table1_id=table1.id;
abc qwerty
abc asdfgh
abc zxcvbn
当前输出的java对象是以下类的列表
class NotesComments{
String name;
String notes;
}
预期输出是一个带有多个注释的Java类:
class NotesComments{
String name;
List<String> notes;
}
答案 0 :(得分:0)
您可以使用基于Java-8的收集器API来完成此操作。
您可以看到此示例
class Table2 {
int id;
int table1_id;
String note;
public Table2(int id, int table1_id, String note) {
this.id = id;
this.table1_id = table1_id;
this.note = note;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getTable1_id() {
return table1_id;
}
public void setTable1_id(int table1_id) {
this.table1_id = table1_id;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
}
class Table1 {
private int id;
private String name;
Table1(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
// Table3Final-正如您在问题中提到的。
Stream<Table1> table1List = Stream.of(new Table1(1, "abc"));
Stream<Table2> table2List = Stream.of(new Table2(1, 1, "qwerty"),
new Table2(2, 1, "asdfgh"),
new Table2(3, 1, "zxcvbn"));
Stream<Table3Final> table3GeneratedStream = table1List
.flatMap(en -> table2List
.filter(table2Entry -> en.getId() == table2Entry.getTable1_id())
.collect(Collectors.groupingBy(Table2::getTable1_id, Collectors.mapping(Table2::getNote, Collectors.toList())))
.entrySet()
.stream()
.map(mapEntry -> new Table3Final(en.getName(), mapEntry.getValue())));
/*System.out.println(table3GeneratedStream.count());*/
table3GeneratedStream.forEach(entry -> {
System.out.println("--------------Name---------------------------");
System.out.println(entry.getName());
System.out.println("----------------Notes-------------------------");
entry.notes.forEach(System.out::println);
});