例如,我在数据库表中有一个名为date的字段,我想在表中插入日期范围从2021-11-25到2021-11-30。我不知道如何编写查询将日期插入到新行中的每个日期的数据库中。如下所示:
谢谢你的帮助..。
发布于 2021-11-25 12:35:29
如何编写查询将日期插入到新行中的每个日期的数据库中。
好的,考虑到这个问题是用JPA标记的,我会给你一个JPA的答案。
你创造了一个像.
@Entity
class MyEntity {
@Id
@GeneratedValue
Long id;
DateTime myDate
}然后您可以创建这样的数据范围列表。
public static List<DateTime> getDateRange(DateTime start, DateTime end) {
List<DateTime> ret = new ArrayList<DateTime>();
DateTime tmp = start;
while(tmp.isBefore(end) || tmp.equals(end)) {
ret.add(tmp);
tmp = tmp.plusDays(1);
}
return ret;
}然后从这个列表创建实体,并使用存储库类插入它们。
这能解决你的问题吗?
发布于 2021-11-25 17:32:48
首先,您必须通过定义一个简单的方法来生成数据:
public List<LocalDate> dateRange(LocalDate from, LocalDate to) {
return from.datesUntil(to).collect(Collectors.toList());
}然后,您可以以您最喜欢的方式存储数据。
例如,使用:
// Your Entity
@Entity
public class DateEntity {
public DateEntity(LocalDate localDate) {
this.localDate = localDate;
}
@Id
@GeneratedValue
private Long id;
private LocalDate localDate;
}
// Your Repository
@Repository
public interface DateEntityRepository extends JpaRepository<DateEntity, Long> {
}
// And the glue
List<DateEntity> dateEntities = dateRange(from, to).stream()
.map(localDate -> new DateEntity(localDate))
.collect(Collectors.toList());
dateEntityRepository.saveAll(dateEntities);https://stackoverflow.com/questions/70110823
复制相似问题