我想发出一个将数据插入数据库的请求。该表有4列:ID_DOCUMENT(PK),ID_TASK,DESCRIPTION,FILEPATH
实体
...
@Column(name = "ID_TASK")
private Long idTask;
@Column(name = "DESCRIPTION")
private String description;
@Column(name = "FILEPATH")
private String filepath;
...
存储库
@Modifying
@Query("insert into TaskDocumentEntity c (c.idTask, c.description, c.filepath) values (:id,:description,:filepath)")
public void insertDocumentByTaskId(@Param("id") Long id,@Param("description") String description,@Param("filepath") String filepath);
控制器
@RequestMapping(value = "/services/tasks/addDocument", method = RequestMethod.POST)
@ResponseBody
public void set(@RequestParam("idTask") Long idTask,@RequestParam("description") String description,@RequestParam("filepath") String filepath){
//TaskDocumentEntity document = new TaskDocumentEntity();
taskDocumentRepository.insertDocumentByTaskId(idTask,descriere,filepath);
}
当我运行测试时,我收到此错误: 引起:org.hibernate.hql.ast.QuerySyntaxException:期待OPEN,在第1行第32列附近找到'c'[插入TaskDocumentEntity c(c.idTask,c.descriere,c.filepath)值(: ID,:descriere,:文件路径)] 我试图删除别名c,但仍然无法正常工作。
答案 0 :(得分:7)
Spring数据提供了用于插入数据库的现成save
方法 - 无需使用@Query
。看一下springData(http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.core-concepts)
因此在您的控制器中只需创建对象TaskDocumentEntity
并将其传递给存储库
@RequestMapping(value = "/services/tasks/addDocument", method = RequestMethod.POST)
@ResponseBody
public void set(@RequestParam("idTask") Long idTask,@RequestParam("description") String description,@RequestParam("filepath") String filepath){
// assign parameters to taskDocumentEntity by constructor args or setters
TaskDocumentEntity document = new TaskDocumentEntity(idTask,descriere,filepath);
taskDocumentRepository.save(document);
}
答案 1 :(得分:3)
有一种方法可以做到这一点但它取决于你正在使用的数据库。以下在Oracle中使用(使用双表):
@Repository
public interface DualRepository extends JpaRepository<Dual,Long> {
@Modifying
@Query("insert into Person (id,name,age) select :id,:name,:age from Dual")
public int modifyingQueryInsertPerson(@Param("id")Long id, @Param("name")String name, @Param("age")Integer age);
}
所以在你的情况下,它将是(如果是甲骨文):
@Modifying
@Query("insert into TaskDocumentEntity (idTask,description,filepath) select :idTask,:description,:filepath from Dual")
public void insertDocumentByTaskId(@Param("idTask") Long id,@Param("description") String description,@Param("filepath") String filepath)
我不确定你正在使用哪个数据库,这里是一个链接,它显示了db的支持选择没有from子句的stmts:http://modern-sql.com/use-case/select-without-from