如何在spring-data中插入db? [英] How to insert into db in spring-data?

查看:25
本文介绍了如何在spring-data中插入db?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想发出一个将数据插入到我的数据库中的请求.该表有 4 列:ID_DOCUMENT (PK)、ID_TASK、DESCRIPTION、FILEPATH

I want to make a request that inserts data into my database. The table has 4 columns: 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:期望打开,在第 1 行第 32 列附近找到c"[插入到 TaskDocumentEntity c (c.idTask, c.descriere, c.filepath) 值 (:id,:descriere,:filepath)]我尝试删除别名 c,但仍然不起作用.

When I run my test, I get this error: Caused by: org.hibernate.hql.ast.QuerySyntaxException: expecting OPEN, found 'c' near line 1, column 32 [insert into TaskDocumentEntity c (c.idTask, c.descriere, c.filepath) values (:id,:descriere,:filepath)] I tried to remove the alias c, and still doesn`t work.

推荐答案

Spring 数据提供了开箱即用的 save 方法,用于插入数据库 - 无需使用 @Query.看看springData的核心概念(http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.core-concepts)

Spring data provides out of the box save method used for insertion to database - no need to use @Query. Take a look at core concepts of springData (http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.core-concepts)

因此在您的控制器中只需创建对象 TaskDocumentEntity 并将其传递给存储库

thus in your controller just create object TaskDocumentEntity and pass it to repository

@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);
    }

这篇关于如何在spring-data中插入db?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆