I want to make a request that inserts data into my database. The table has 4 columns: ID_DOCUMENT (PK), ID_TASK, DESCRIPTION, FILEPATH
Entity
...
@Column(name = "ID_TASK")
private Long idTask;
@Column(name = "DESCRIPTION")
private String description;
@Column(name = "FILEPATH")
private String filepath;
...
Repository
@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);
Controller
@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);
}
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.
In JPA, we can easily insert data into database through entities. The EntityManager provides persist() method to insert records.
Each of these defines its own functionality: CrudRepository provides CRUD functions. PagingAndSortingRepository provides methods to do pagination and sort records. JpaRepository provides JPA related methods such as flushing the persistence context and delete records in a batch.
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)
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With