I want run a multi insert query but getting this error
org.postgresql.util.PSQLException: The column index is out of range: 1, number of columns: 0.
Table Schema
create table if not exists student
(
student_id bigserial primary key,
student_name text
);
create table if not exists favourite_color
(
student_id bigint,
color text,
foreign key (student_id) references student (student_id)
);
create table if not exists favourite_animal
(
student_id bigint,
animal text,
foreign key (student_id) references student (student_id)
);
Working SQL Query
do $$
declare s_id bigint;
declare fav_color text;
declare s_name text;
declare fav_animal text;
begin
fav_color := 'Red';
fav_animal := 'Horse';
s_name := 'jhon';
insert into student (student_name)
values(s_name)
returning student_id into s_id;
insert into favourite_color(student_id,color)
values (s_id, fav_color);
insert into favourite_animal (student_id,animal)
values (s_id, fav_animal);
end
$$;
Spring Boot Code [Not Working]
public void addStudent() {
String sql = """
do $$
declare s_id bigint; declare fav_color text;
declare s_name text; declare fav_animal text;
begin
fav_color := :color;
fav_animal := :animal;
s_name := :name;
insert into student (student_name)
values(s_name)
returning student_id into s_id;
insert into favourite_color(student_id,color)
values (s_id, fav_color);
insert into favourite_animal (student_id,animal)
values (s_id, fav_animal);
end
$$;
""";
MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("name", "Jhon");
parameters.addValue("animal", "Horse");
parameters.addValue("color", "Blue");
template.update(sql, parameters);
}
When I run the code, it should insert the values in designated tables.
Observation
When I am running the query with template placeholders its working as expected and errors are thrown.
Postgres Driver ‘org.postgresql:postgresql:42.3.8’