我有一個執行方法的類,并且出現這樣的問題,即在更改組態檔時,我意識到 hsqldb 無法使用 Java 8 Time API,所以我想使用 Profile 與 Postgres 共享執行,我想知道怎么做 這是有方法的類
@Repository
public class JdbcMealRepository implements MealRepository {
private static final RowMapper<Meal> ROW_MAPPER = BeanPropertyRowMapper.newInstance(Meal.class);
private final JdbcTemplate jdbcTemplate;
private final NamedParameterJdbcTemplate namedParameterJdbcTemplate;
private final SimpleJdbcInsert insertMeal;
@Autowired
public JdbcMealRepository(JdbcTemplate jdbcTemplate, NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
this.insertMeal = new SimpleJdbcInsert(jdbcTemplate)
.withTableName("meals")
.usingGeneratedKeyColumns("id");
this.jdbcTemplate = jdbcTemplate;
this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
}
@Override
public Meal save(Meal meal, int userId) {
MapSqlParameterSource map = new MapSqlParameterSource()
.addValue("id", meal.getId())
.addValue("description", meal.getDescription())
.addValue("calories", meal.getCalories())
.addValue("date_time", meal.getDateTime())
.addValue("user_id", userId);
if (meal.isNew()) {
Number newId = insertMeal.executeAndReturnKey(map);
meal.setId(newId.intValue());
} else {
if (namedParameterJdbcTemplate.update(""
"UPDATE meals "
" SET description=:description, calories=:calories, date_time=:date_time "
" WHERE id=:id AND user_id=:user_id", map) == 0) {
return null;
}
}
return meal;
}
@Override
public boolean delete(int id, int userId) {
return jdbcTemplate.update("DELETE FROM meals WHERE id=? AND user_id=?", id, userId) != 0;
}
@Override
public Meal get(int id, int userId) {
List<Meal> meals = jdbcTemplate.query(
"SELECT * FROM meals WHERE id = ? AND user_id = ?", ROW_MAPPER, id, userId);
return DataAccessUtils.singleResult(meals);
}
@Override
public List<Meal> getAll(int userId) {
return jdbcTemplate.query(
"SELECT * FROM meals WHERE user_id=? ORDER BY date_time DESC", ROW_MAPPER, userId);
}
@Override
@Profile(Profiles.POSTGRES_DB)
public List<Meal> getBetweenHalfOpen(LocalDateTime startDateTime, LocalDateTime endDateTime, int userId) {
return jdbcTemplate.query(
"SELECT * FROM meals WHERE user_id=? AND date_time >= ? AND date_time < ? ORDER BY date_time DESC",
ROW_MAPPER, userId, startDateTime, endDateTime);
}
}
uj5u.com熱心網友回復:
根據https://docs.spring.io/spring-boot/docs/current/reference/html/application-properties.html更改您的 application.properties并將 postgresql 添加到您的 maven/gradle 依賴項中。
或者干脆從 hsqldb 更改為 h2。請注意,h2 至少在 jdbc 中支持 OffsetDateTime 但不支持 ZonedDateTime,如果您嘗試將帶有 ZonedDateTime 的記錄保存到 Timestamp 列,我不知道 Spring 會執行的所有轉換。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/439764.html
標籤:爪哇 春天 PostgreSQL 数据库
上一篇:查詢電話記錄
