Взаимодействие MySQL и SpringBoot
Хочу написать простое crud приложение, но возникли вопросы
- через http запрос контроллер должен найти значение в базе, но что то идет не так
- как вернуть второе связанное значение из базы
Исходники База
create table weather_history
(
id bigint auto_increment
primary key,
weather_date date not null,
weather_value varchar(100) not null
);
Класс для взаимодействия с базой
@Data
@Entity
@Table(name="weather_history")
public class Weather
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name="weather_date")
private String weatherDate;
@Column(name="weather_value")
private String weatherValue;
}
Репозиторий
public interface UserRepository extends JpaRepository<Weather,Long>
{
List<Weather> findByWeatherDate(Date weatherDate);
}
Сервис
@Service
public class UserService
{
private final UserRepository userRepository;
@Autowired
public UserService(UserRepository userRepository)
{
this.userRepository=userRepository;
}
public Weather findById(Long Id)
{
return userRepository.getOne(Id);
}
public List<Weather> findAll()
{
return userRepository.findAll();
}
public Weather saveUser(Weather user)
{
return userRepository.save(user);
}
public void deleteById(Long Id)
{
userRepository.deleteById(Id);
}
public List<Weather> findByWeatherDate(Date weatherDate)
{
return userRepository.findByWeatherDate(weatherDate);
}
}
Ну и сам контроллер
public class UserController
{
private final UserService userService;
@Autowired
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping("/check")
public String check(@RequestParam String date) throws Exception
{
SimpleDateFormat format = new SimpleDateFormat();
format.applyPattern("yyyy.MM.dd");
Date docDate= format.parse(date);
List<Weather> users=userService.findByWeatherDate(docDate);
if (users.contains(date))
return ???? вернуть weather_value из базы;
else return "incorrect";
}
}
Ответы (2 шт):
Автор решения: Alex Rudenko
→ Ссылка
Данный код users.contains(date) следует переписать.
- Переименовать
List<Weather> users, чтобы было какое-то корректное название, хотя быweatherList - Проверка
containsв данном случае бессмысленна, так как проверяется наличие объектаDateв списке объектовWeather, кроме того, репозиторий сам отфильтрует объектыWeather, если дата не будет найдена, вернется пустой список. - Поскольку репозиторий может вернуть список из нескольких элементов, нужно решить, объединить ли эти несколько ответов, используя к примеру Stream API
Collectors::joining, или вернуть первый элемент.
@GetMapping("/check")
public String check(@RequestParam String date) throws Exception {
SimpleDateFormat format = new SimpleDateFormat();
format.applyPattern("yyyy.MM.dd");
Date docDate = format.parse(date);
List<Weather> weatherList = userService.findByWeatherDate(docDate);
if (weatherList.isEmpty()) {
return "incorrect: no weather found for date " + date + " / " + docDate;
}
return weatherList
.stream() // Stream<Weather>
.map(Weather::getWeatherValue) // Stream<String> поток weather_value
.collect(Collectors.joining("; ")); // объединить в строку с делимитером "; "
}
Вернуть первое подходящее значение weatherValue:
@GetMapping("/check")
public String check(@RequestParam String date) throws Exception {
SimpleDateFormat format = new SimpleDateFormat();
format.applyPattern("yyyy.MM.dd");
Date docDate = format.parse(date);
List<Weather> weatherList = userService.findByWeatherDate(docDate);
if (weatherList.isEmpty()) {
return "incorrect: no weather found for date " + date + " / " + docDate;
}
return weatherList.get(0).getWeatherValue();
}
Автор решения: amala
→ Ссылка
Просто используйtтеь для weatherDate тип java.sql.Date. Не следует путать с java.util.Date, который соответствует типу Date в MySQL).
Чтобы конвертировать String в java.sql.Date достаточно вызвать статический метод Date.valueOf(String).