快速在数据库添加一年的日期,区分休息日和工作日
- 1.数据库
- 建表
CREATE TABLE `year_date_all` (
`repDate` date DEFAULT NULL,
`repYear` int(8) DEFAULT NULL,
`repMonth` int(8) DEFAULT NULL,
`repDay` int(8) DEFAULT NULL,
`repWeek` int(8) DEFAULT NULL,
`db_status` int(8) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8
- 2.Java代码
- 实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Holiday {
private Date repDate;
private int repYear;// 年
private int repMonth;// 月
private int repDay;// 日
private int repWeek;// 第几周
private int dbStatus;// 0 工作日 1休息日 2 法定假期
}
- mapper语句
<insert id="insertHoliday" parameterType="List">
insert into year_date_all (repDate,repYear,repMonth,repDay,repWeek,db_status)
values
<foreach collection="holidays" item="holiday" separator=",">
(#{holiday.repDate},#{holiday.repYear},#{holiday.repMonth},#{holiday.repDay},#{holiday.repWeek},#{holiday.dbStatus})
</foreach>
</insert>
- 测试代码
@Test
void insertHoliday(){
// 设置初始时间
LocalDate dateOfBirth = LocalDate.of(2021, 12, 31);
ArrayList<Holiday> holidays = new ArrayList<>();
// 当前为第几周
int w = 2;
// 2020 366天
// 循环 添加接下来一年的时间
for(int i = 1;i<= 365 ; i++) {
Period of = Period.of(0, 0, i);
LocalDate DateTime = dateOfBirth.plus(of);
// 获取年份
int Year = DateTime.getYear();
// 获取月份
int Month = DateTime.getMonthValue();
// 获取日分
int day = DateTime.getDayOfMonth();
// 获取周
String Week = DateTime.getDayOfWeek().toString();
// 默认0 当为休息日时 1
int temp = 0;
// 日期实体类
Holiday holiday = new Holiday();
holiday.setRepDate(Date.from(DateTime.atStartOfDay(ZoneOffset.ofHours(8)).toInstant()));
holiday.setRepYear(Year);
holiday.setRepMonth(Month);
holiday.setRepDay(day);
holiday.setRepWeek((int)(w/2));
// 记录 周六周日
if( Week.equals("SATURDAY") || Week.equals("SUNDAY")) {
temp = 1;
w++;
}
holiday.setDbStatus(temp);
holidays.add(holiday);
}
int i = tablesMapper.insertHoliday(holidays);
if( i > 0 ) {
System.out.println("添加成功,添加了"+i+"条!");
} else {
System.out.println("添加失败!");
}
}
结果展示: