0

I am working on a Spring-MVC application where I am using PostgreSQL database with hibernate. I realize that Hibernate has its own trigger but using them involves a lot of overhead. For this reason, I would like to use a PostgreSQL trigger.

Have a look at the data-model pasted below.

Question :What should it do? Answer : After database gets updated(CRUD operations), there is a integer-column(noteorder) which defines ordering of the data. I would like to reset that and start it to 1 and increment until end of row.

There is a catch too: :-( Can I pass parameters like do use triggers when certain conditions like sectionid or canvasid is fulfilled?

Is this possible or do I have to Hibernate triggers. Kindly let me know, any ideas, link would be nice. If any question, please leave a comment. Thank you.

Below is the data-model :

CREATE TABLE note
(
  noteid integer NOT NULL,
  sectionid integer,
  canvasid integer,
  text character varying,
  notecolor character varying,
  noteheadline character varying,
  id integer NOT NULL,
  canvasname character varying,
  noteorder integer,
  CONSTRAINT noteid PRIMARY KEY (noteid),
  CONSTRAINT user_note_fk FOREIGN KEY (id)
      REFERENCES person (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
);

1 Answer 1

1

You can run an update query using the row_number window function

UPDATE note set note.noteorder = subquery.rn
FROM  
(
    SELECT id,row_number() over () AS rn
    FROM note
) subquery
WHERE note.id = subquery.id;

You can user a trigger but you cannot pass any arguments. From docs:

The trigger function must be declared as a function taking no arguments and returning type trigger. (The trigger function receives its input through a specially-passed TriggerData structure, not in the form of ordinary function arguments.)

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. I guess then I cannot use it, as I need to pass 2 parameters under any conditions. Thank you for your answer, I guess I will look into hibernate for some solutions.
And you probably want a order by noteorder in the over clause to preserve the current sort order. Otherwise this will just be a "random" order.

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.