Spring boot中使用JPA查询时间段内的数据
笔记1、实体类,定义好实体类和数据库中的字段一一对应@Entity//实体类@Table(name = "identifyinginformation")//数据表@JsonIgnoreProperties({"handler", "hibernateLazyInitializer"})public class BottleIdentify {@Id@GeneratedValue(strategy
·
笔记
1、实体类,定义好实体类和数据库中的字段一一对应
@Entity //实体类
@Table(name = "identifyinginformation") //数据表
@JsonIgnoreProperties({"handler", "hibernateLazyInitializer"})
public class BottleIdentify {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
int id;
String label;
String name;
String price;
String total;
Timestamp date;
String user;
2、DAO层自定义使用自定义的sql语句查询
public interface BottleIdentifyDAO extends JpaRepository<BottleIdentify, Integer> {
@Modifying
@Query(value = "SELECT * FROM `identifyinginformation` WHERE `date`>=? AND `date` <=?" ,nativeQuery = true)
List<BottleIdentify> findAll(String now, String todayOfLastWeek);
}
3、业务层调用dao层,并传入时间段
@Service
public class BottleIdentifyService {
@Autowired
BottleIdentifyDAO bottleIdentifyDAO;
// 1、df:时间格式 2、now:获取当前时间 3、todayOfLastWeek : 当前时间七天前的时间 时间段可以自定义
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
LocalDateTime todayOfLastWeek = now.minusDays(7);
// 格式化时间
String nowTime = df.format(now);
String TodayTime = df.format(todayOfLastWeek);
//实现dao层的查询方法,返回的是一个列表,类型是实体类
public List<BottleIdentify> getTodayOfLastWeekBottleIdentify(){
return bottleIdentifyDAO.findAll(TodayTime,nowTime);
}
}
4、控制层实现业务层的查询方法
@RestController
public class BottleIdentifyController {
@Autowired
BottleIdentifyService bottleIdentifyService;
@CrossOrigin
@GetMapping(value = "/api/bottleindentify")
public List<BottleIdentify> getTodayOfLastWeekBottleIdentify() throws Exception{
return bottleIdentifyService.getTodayOfLastWeekBottleIdentify();
}
}
更多推荐
已为社区贡献2条内容
所有评论(0)