'Postgresql rule on insert to do nothing and return the given instence

I am trying to write a rule that on insert if there is conflict to do nothing. The hard part is that I am using java code for interacting with the db and the save method expects an instance to be returned. So the goal I am trying to achieve is, a rule that triggers on conflict when inserting, does nothing and returns the given instance. I have tried to do something like that :

CREATE RULE "my_rule" AS ON INSERT TO "table_x"
WHERE EXISTS(SELECT 1 FROM table_x WHERE id = NEW.id)
DO INSTEAD
Select * from table_x WHERE(id=NEW.id);


Solution 1:[1]

You don't need a rule for that, use instead :

INSERT ... ON CONFLICT DO NOTHING

see the manual

Solution 2:[2]

I never use Postgresqls rules, but I'd expect that you could combine it with the idea of Edouards answer.

CREATE RULE "my_rule" AS ON INSERT TO "table_x"
DO INSTEAD
INSERT ... ON CONFLICT DO NOTHING;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Edouard
Solution 2 Jens Schauder