0

My question is very concrete and I could not find any answers on Stackoverflow or wider internet.

I would like to use Spring repository to execute "DELETE FROM TABLE ... RETURNING *" type of query, which is specific to Postgresql.

Assume that I have following classes:


@Entity
@Getter // lombok annotations
@Setter
public class Item {

    @Id
    @GeneratedValue
    private Integer id;

    private String name;

}

then I would like to have something like following:


interface ItemRepository extends CrudRepository<Item, Integer> {

    // This is a Postgres specific query
    @Query("SELECT FROM Item where Item.id=?1 RETURNING *")
    Optional<Item> deleteByIdReturning(Integer id)

}

How can I do something like this?

Additional info:

In order to motivate my needs a bit better I would like to have a CRUD-y REST resource, which will return 200 HTTP status code together with deleted resource if something has been deleted, but will return HTTP status code 204 without body in case that nothing has actually been deleted on the server side.

I thank you in advance for your time

2
  • 2
    Use a @NativeQuery? Commented Jan 31, 2022 at 20:23
  • May I ask for an example? Commented Jan 31, 2022 at 20:25

1 Answer 1

2

If you are using Spring Data JPA you can try using native query this way:

 @Query("SELECT FROM Item where Item.id=?1 RETURNING *", nativeQuery = true)
 Optional<Item> deleteByIdReturning(Integer id)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.