jpa+spring boot实现某年的天数
Entity层
@Entity
@Table(name=“date”)
@ApiModel(value=“date”,description = “日期记录对象”)
public class Month {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@ApiModelProperty(value="ID")
private Long id;
@ApiModelProperty(value="日期(yyyy-MM-dd)")
private String date;
@ApiModelProperty(value="是否节假日 0-不是节假日 1-节假日 ")
private int festival = 0;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public int getFestival() {
return festival;
}
public void setFestival(int festival) {
this.festival = festival;
}
}
Service层
@Service
public class MonthService {
@Autowired
private MonthDao monthDao;
public List<Month> getAllDate(){
List<String> dateList = new ArrayList<String>();
try {
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//起始日期
Date d1 = sdf.parse("2019-01-01");
//结束日期
Date d2 = sdf.parse("2019-12-30");
Date tmp = d1;
Calendar calendar = Calendar.getInstance();
calendar.setTime(d1);
//打印日期
while(tmp.getTime()<=d2.getTime()){
tmp = calendar.getTime();
System.out.println(sdf.format(tmp));
//天数加1
calendar.add(Calendar.DAY_OF_MONTH,1);
dateList.add(sdf.format(tmp));
}
}catch(Exception e){
e.printStackTrace();
}
List<Month> monthList = new ArrayList<>();
dateList.forEach(s -> {
Month month = new Month();
month.setDate(s);
month.setFestival(0);
monthList.add(month);
});
return monthDao.saveAll(monthList);
}
}
Dao层
public interface MonthDao extends JpaRepository<Month,Long> {
}
Controller层