我正在做一个 Spring Boot 项目,我有两个通过 OneToMany 关系相互关联的表
public class PackGroupEntity{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String description;
private Double qty;
private Integer packingNr;
@Temporal(TemporalType.TIMESTAMP)
private Date deliveredTime;
@OneToMany(mappedBy = "packGroup", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
private List<PackArticlesEntity> packArticles= new ArrayList<>();
}
和
public class PackArticlesEntity{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Double qty;
private Double confirmedName;
@Enumerated(EnumType.STRING)
private ArticleStatus status;
private Double weight;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "pack_group_id")
private PackGroupEntity packGroup;
}
我在这两个表上循环插入数据,首先我按包装号对文章进行分组,我将为此创建一个包含文章列表的 PackGroup:
Map<Integer, List<RecivedArticlesDTO >> groupedArticles =
recivedArticlesListDTO.stream().collect(Collectors.groupingBy(RecivedArticlesDTO::getPackingNr));
for (Map.Entry<Integer, List<RecivedArticlesDTO>> entry : groupedArticles.entrySet()) {
List<RecivedArticlesDTO > groups = entry.getValue();
PackGroupEntity packGroup = new PackGroupEntity();
packGroup.setPackingNr(entry.getKey())
//some manipulations and setting data for each field
List<PackArticlesEntity> listWithArticles = new ArrayList<>();
groups.forEach(pack -> {
PackArticlesEntity packArticle= new PackArticlesEntity();
packArticles.setQty(pack.getQty);
//some manipulations and setting data for each field
listWithArticles.add(packArticles);
}
packGroup.setPackArticles(listWithArticles);
// here I have to save the data using native query
packGroupService.savePackGroupData(packGroup);
}
这样,它太慢了,所以我想在本机查询上做。问题是我有很多 packGroups 和很多 packArticles 需要保存。我想以某种方式只与 DB 建立一个连接以发送要保存的包组列表和打包文章,但我不知道如何在本机查询中执行此操作。这仅适用于一个 pack_group 但我不知道如何传递packArticles
本机查询,因为它是一个列表
@Query(value = "insert into pack_group " +
" (id,packing_nr, description, qty, deliveredTime, packArticles) " +
" values (1?, 2?, 3?, 4?, 5?, 6?)", nativeQuery = true)
void savePackGroupData(id, packing_nr, description, qty, packArticles);
有人可以帮忙吗?
编辑:我想从插入返回 id
String query = String.format("insert into pack_group(group, remark, description ) " +
"values ( %s, %s, %s)", "x","y","z" );
Query q = entityManager.createNativeQuery(query );
BigInteger biid = (BigInteger) q.getSingleResult();
long id = biid.longValue();
我得到这个错误com.microsoft.sqlserver.jdbc.SQLServerException: The statement did not return a result set.