Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert into db in spring-data?

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.

like image 978
que1326 Avatar asked Oct 07 '15 10:10

que1326


People also ask

What is the EntityManager method to insert data?

In JPA, we can easily insert data into database through entities. The EntityManager provides persist() method to insert records.

What is difference between JpaRepository and CrudRepository?

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.


Video Answer


1 Answers

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);
    }
like image 92
pezetem Avatar answered Sep 29 '22 01:09

pezetem