【发布时间】:2022-08-03 14:37:43
【问题描述】:
我对 Spring boot 比较陌生,我正在尝试编写一个非常简单的程序,可以在 postgreSQL 数据库上执行 post、get 和 delete。数据库名为 \"recipes\" 架构 \"public\" 和表 \"recipe\" 我遇到的问题是,当我通过邮递员发出 get 请求时,尽管数据库已用数据初始化,但它只是返回 null。
我尽我所能尝试缩小问题范围,我得到的最远的是服务层的线路在评估时没有返回任何内容
jdbcTemplate.query(sql, new RecipeRowMapper())
使用以下 SQL 初始化数据库
INSERT INTO recipe(id, name, ingredients, instructions, date_added)
values (1, \'ini test1\', \'10 cows 20 rabbits\', \'cook ingredients with salt\', \'2004-01-02\'),
(2, \'ini test2\', \'30 apples 20 pears\', \'peel then boil\', \'2004-01-13\');
我知道数据库不是空的,因为当我运行以下 SQL 时
SELECT * from recipe
我明白了
并且数据库连接如下所示(我觉得奇怪的一件事是表格 \"recipe\" 没有显示在 DB 浏览器中,但我不知道该怎么做)
应用程序.yml
app:
datasource:
main:
driver-class-name: org.postgresql.Driver
jdbc-url: jdbc:postgresql://localhost:5432/recipes?currentSchema=public
username: postgres
password: password
server:
error:
include-binding-errors: always
include-message: always
spring.jpa:
database: POSTGRESQL
hibernate.ddl-auto: create
show-sql: true
dialect: org.hibernate.dialect.PostgreSQL9Dialect
format_sql: true
spring.flyway:
baseline-on-migrate: true
这是服务层
public List<Recipe> getRecipes(){
var sql = \"\"\"
SELECT id, name, ingredients, instructions, date_added
FROM public.recipe
LIMIT 50
\"\"\";
return jdbcTemplate.query(sql, new RecipeRowMapper());
}
这是控制器
@GetMapping(path = \"/test\")
public String testRecipe(){
return recipeService.test();
}
和行映射器
public class RecipeRowMapper implements RowMapper<Recipe> {
@Override
public Recipe mapRow(ResultSet rs, int rowNum) throws SQLException {
return new Recipe(
rs.getLong(\"id\"),
rs.getString(\"name\"),
rs.getString(\"ingredients\"),
rs.getString(\"instructions\"),
LocalDate.parse(rs.getString(\"date_added\"))
);
}
}
最后配方实体看起来像这样
@Data
@Entity
@Table
public class Recipe {
@Id
@GeneratedValue(
strategy = GenerationType.IDENTITY
)
@Column(name = \"id\", updatable = false, nullable = false)
private long id;
@Column(name = \"name\")
private String name;
@Column(name = \"ingredients\")
private String ingredients;
@Column(name = \"instructions\")
private String instructions;
@Column(name = \"date_added\")
private LocalDate dateAdded;
public Recipe(){};
public Recipe(long id, String name, String ingredients, String instructions, LocalDate date){}
public Recipe(String name,
String ingredients,
String instructions,
LocalDate dateAdded
) {
this.name = name;
this.ingredients = ingredients;
this.instructions = instructions;
this.dateAdded = dateAdded;
}
}