【发布时间】:2020-01-06 21:01:46
【问题描述】:
我有一个问题。使用 GetRequest,我想要一个 SQL 查询,在其中查询 2 个参数。 Sql 查询是
SELECT * FROM templates WHERE user_name=user_name AND template_id=template_id
User_name 和 template_id 应接管 GetRequest。
我想返回用户名是 user_name 并且 template_id = template_id 的所有内容。我的第一次尝试看起来像这样
public class SelectTemplate {
public void SelectExactTemplate(String user_name, int template_id)
{
try{
Connection conn=this.connect();
Statement stmt=conn.createStatement();
ResultSet rs;
rs = stmt.executeQuery("SELECT * FROM templates WHERE user_name=user_name AND template_id=template_id");
while ( rs.next() )
{
rs.getString(user_name);
rs.getInt(template_id);
}
conn.close();
}
catch (SQLException e)
{
System.out.println(e.getMessage());
}
}
private Connection connect() {
// SQLite connection string
String url = "xxxxxxx";
Connection conn = null;
try {
conn = DriverManager.getConnection(url,"xxxxx","xxxxxxx");
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return conn;
}
这是我连接到数据库并启动查询的类。 我的GetRequest
@GetMapping("/templates/user_name/template_id")
public Template retrieveUser(@RequestBody Template template)
{
SelectTemplate app=new SelectTemplate();
String user_name=template.getUserName();
int template_id=template.getTemplateId();
app.SelectExactTemplate(user_name, template_id);
return template;
}
还有我的仓库
public interface TemplateRepository extends JpaRepository<Template, Integer>{
}
当我在 POSTMAN 启动 GetRequest 时,我收到错误“Not Found”
谁能告诉我我做错了什么或如何更好地解决问题?
更新
public class SelectTemplate {
@Autowired
private TemplateRepository templateRepository;
public Template SelectExactTemplate(String user_name, int template_id) {
return templateRepository.findByIdAndUserName(template_id, user_name);
}
还有仓库
public interface TemplateRepository extends JpaRepository<Template, Integer>{
Template findByIdAndUserName(int template_id, String user_name);
Template findByUserName(String user_name);
}
我也尝试过一次只针对用户名的查询。我仍然收到“未找到”错误。
@GetMapping("/templates/user_name")
public Template retrieveTemplateByUsername(String user_name)
{
return templateRepository.findByUserName( user_name);
}
更新 2
@GetMapping("/templates/{user_name}")
public List<Template> retrieveTemplateByUsername(@PathVariable("user_name") String user_name)
{
return templateRepository.findByUserName(user_name);
}
现在可以了。我不得不更改存储库中的某些内容
List<Template> findByUserName(String user_name);
但如果我想找到由 template_id 和 user_name 选择的 1 个模板,我得到一个空值
@GetMapping("/templates/{user_name}/{template_id}")
public Template retrieveTemplate(@PathVariable("user_name") String user_name,@PathVariable("template_id") int template_id)
{
return templateRepository.findByIdAndUserName(template_id, user_name);
}
更新 3 问题解决了。查询查找 id 而不是 template_id
非常感谢
【问题讨论】:
标签: java sql microservices