Hibernate delete #OneToMany child directly form child object - java

I have a ReST API developed with Spring Boot that exposes resources. Using Spring Data JPA CrudRepository
One of this this resources contains a collection of another resource. I'd like to delete a child directly from its repository.
I have tried to use CascadeType = Remove but it still doesn't work.
Parent object :
#Entity
public class Subject{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String name;
private String icon;
private String image;
#OneToMany( targetEntity=Ability.class, orphanRemoval = true, cascade = CascadeType.REMOVE)
private List<Ability> abilities;
}
Child object :
#Entity
public class Ability {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String name;
private String color;
private String image;
#OneToMany(targetEntity=Technology.class, orphanRemoval = true, cascade = CascadeType.REMOVE)
private List<Technology> technologies;
But when I tried to delete an ability that is bound to a subject using :
abailityRepository.deleteById(id);
I get following error message :
2019-08-04T13:34:27.987258+00:00 app[web.1]: 2019-08-04 13:34:27.986 WARN 4 --- [io-40382-exec-5] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 23503
2019-08-04T13:34:27.987393+00:00 app[web.1]: 2019-08-04 13:34:27.987 ERROR 4 --- [io-40382-exec-5] o.h.engine.jdbc.spi.SqlExceptionHelper : ERROR: update or delete on table "ability" violates foreign key constraint "fkb019eiy6xjwsyxuukgmr9iid6" on table "subject_abilities"
2019-08-04T13:34:27.987397+00:00 app[web.1]: Detail: Key (id)=(100) is still referenced from table "subject_abilities".
2019-08-04T13:34:27.987588+00:00 app[web.1]: 2019-08-04 13:34:27.987 INFO 4 --- [io-40382-exec-5] o.h.e.j.b.internal.AbstractBatchImpl : HHH000010: On release of batch it still contained JDBC statements
2019-08-04T13:34:27.987877+00:00 app[web.1]: 2019-08-04 13:34:27.987 ERROR 4 --- [io-40382-exec-5] o.h.i.ExceptionMapperStandardImpl : HHH000346: Error during managed flush [org.hibernate.exception.ConstraintViolationException: could not execute statement]
2019-08-04T13:34:27.993333+00:00 app[web.1]: 2019-08-04 13:34:27.992 ERROR 4 --- [io-40382-exec-5] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [fkb019eiy6xjwsyxuukgmr9iid6]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause
2019-08-04T13:34:27.993338+00:00 app[web.1]: org.postgresql.util.PSQLException: ERROR: update or delete on table "ability" violates foreign key constraint "fkb019eiy6xjwsyxuukgmr9iid6" on table "subject_abilities"
2019-08-04T13:34:27.993340+00:00 app[web.1]: Detail: Key (id)=(100) is still referenced from table "subject_abilities".
2019-08-04T13:34:27.993342+00:00 app[web.1]: at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2440) ~[postgresql-42.2.5.jar!/:42.2.5]
.......

Related

Hibernate mapping error while inserting child record

I have two entity class as below -
public class Parent {
#Id
private Integer parentId;
private String name;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "parent", cascade = CascadeType.ALL)
private List<Child> children;
}
public class Child {
#Id
private Integer childId;
private String name;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "parentId", insertable = false, updatable = true, nullable = false)
private Parent parent;
}
#RestController
public class ParentController {
#Autowired
private ParentRepo repo;
#GetMapping("/parent")
public void get() {
Child c1 = Child.builder().childId(1).name("s1").build();
Child c2 = Child.builder().childId(2).name("s2").build();
List<Child> children = new ArrayList<>();
children.add(c1);
children.add(c2);
Parent parent = Parent.builder().parentId(1).name("PARENT")
.children(children)
.build();
Parent savedParent = repo.save(parent);
}
}
Tables -
CREATE TABLE public.parent
(
parent_id integer NOT NULL,
name character varying(255) COLLATE pg_catalog."default",
CONSTRAINT parent_pkey PRIMARY KEY (parent_id)
)WITH (
OIDS = FALSE
)
TABLESPACE pg_default;
CREATE TABLE public.child
(
child_id integer NOT NULL,
name character varying(255) COLLATE pg_catalog."default",
parent_id integer NOT NULL,
CONSTRAINT child_pkey PRIMARY KEY (child_id),
CONSTRAINT fk7dag1cncltpyhoc2mbwka356h FOREIGN KEY (parent_id)
REFERENCES public.parent (parent_id) MATCH SIMPLE
ON UPDATE NO ACTION
ON DELETE NO ACTION
)
WITH (
OIDS = FALSE
)
TABLESPACE pg_default;
I'm getting error while persisting child record.
Error -
Hibernate:
insert
into
child
(name, child_id)
values
(?, ?)
2022-07-19 23:12:31.727 WARN 20940 --- [nio-8080-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 23502
2022-07-19 23:12:31.727 ERROR 20940 --- [nio-8080-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : ERROR: null value in column "parent_id" violates not-null constraint
Detail: Failing row contains (1, s1, null).
2022-07-19 23:12:31.728 INFO 20940 --- [nio-8080-exec-2] o.h.e.j.b.internal.AbstractBatchImpl : HHH000010: On release of batch it still contained JDBC statements
2022-07-19 23:12:31.754 ERROR 20940 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [parent_id]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause
org.postgresql.util.PSQLException: ERROR: null value in column "parent_id" violates not-null constraint
Detail: Failing row contains (1, s1, null).
Not sure how hibernate will pick and assign the foreign key to child.
You have to set the bidirectional relationship first
public class Parent {
#Id
private Integer parentId;
private String name;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "parent", cascade = CascadeType.ALL)
private List<Child> children;
public void addChild(Child child) {
this.children.add(child);
child.setParent(this);
}
}
and add the children via that method.

Unknown column 'clientproj0_.clienthours_id' in 'field list (JPA #OneToMany(mappedBy = "clienthours"))

I have 2 views
"client_hours_view"
(ClientHoursInfo.java) and
"client_project_hours_view"
(ClientProjectHoursInfo.java)
The first view already existed in the application and :
Retrieves all the clients in the work hours in total
The second view is the new pne and:
Retrieves all the clients with a list of projects for each client and their hours
Anyways, I just want to find a way to retrieve all the clients (first view) with a list of their respective projects (second view), and the best I could figure out is by adding a field list in the ClientHoursInfo.java :
private List clientProjectList which will contain a list of projects for each client.
I have extracted below the code to show only the relation needed against these 2 views
However I am not able to succesfully run it, since it is showing the below error in the console.
Unknown column 'clientproj0_.clienthours_id'
I would like to get guidance to solve this or find a different approach to meet the requirement.
ClientHoursInfo.java
#Entity
#Table(name = "client_hours_view")
public class ClientHoursInfo {
#Id
#Column(name = "unique_id")
private String uniqueId;
private Long id;
private String client;
#Column(name = "week_ending")
private String weekEnding;
#Column(name = "total_hours")
private Double totalHours;
#OneToMany(mappedBy = "clienthours")
private List<ClientProjectHoursInfo> clientProjectList;
}
ClientProjectHoursInfo.java
#Entity
#Table(name = "client_project_hours_view")
public class ClientProjectHoursInfo {
#ManyToOne(fetch = FetchType.LAZY)
private Employee clienthours;
#Id
#Column(name = "id")
private String Id;
}
FinanceManagerReports.java
clientHours = clientHoursInfoViewRepository.findByWeekEndingBetween(from, to);
for (ClientHoursInfo clientHoursInfo : clientHours) {
clientProjectHours = clientProjectHoursInfoViewRepository
.findByClientIdAndWeekEnding(clientHoursInfo.getId(), clientHoursInfo.getWeekEnding());
clientHoursInfo.setClientProjectList(clientProjectHours);
}
Error Console
[2019-10-02 17:21:57.887] boot - 9656 ERROR [http-nio-8080-exec-3] --- SqlExceptionHelper: Unknown column 'clientproj0_.clienthours_id' in 'field list'
[2019-10-02 17:21:57.888] boot - 9656 ERROR [http-nio-8080-exec-3] --- [dispatcherServlet]: Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet] with root cause
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'clientproj0_.clienthours_id' in 'field list'

JPA update record is failing due to #OneToMany

I have a very small doubt regarding #OneToMany mapping.
I have a model student and another model attendance.
A student can have multiple attendance. but student model should only be able to retrieve the attendance info.
But when I am trying to change some student info I am getting below error as it is trying to update attendance record.
here is my mapping
#Entity
#Table(name="student_detail")
#Getter #Setter
public class StudentDetailsModel {
#Id
#Column(name="reg_no",updatable = false, nullable = false)
private String regNo;
#OneToMany(fetch = FetchType.LAZY, cascade = { CascadeType.ALL })
#JoinColumn(name = "reg_no")
private List<AttendanceModel> attendances;
}
and the exception I a getting.
update
student_detail
set
address=?,
alt_contact_number=?,
blood_group=?,
contact_number=?,
dob=?,
father_name=?,
first_name=?,
gender=?,
last_name=?,
middle_name=?,
mother_name=?,
photo_url=?,
school_id=?
where
reg_no=?
Hibernate:
update
attendance
set
reg_no=null
where
reg_no=?
2019-01-13 12:12:52.922 WARN 10708 --- [nio-8081-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 23502
2019-01-13 12:12:52.923 ERROR 10708 --- [nio-8081-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : ERROR: null value in column "reg_no" violates not-null constraint
Detail: Failing row contains (null, 1, 2019-01-05, t, 2).
2019-01-13 12:12:52.926 INFO 10708 --- [nio-8081-exec-1] o.h.e.j.b.internal.AbstractBatchImpl : HHH000010: On release of batch it still contained JDBC statements
org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [reg_no]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
my attenance model is as follows
#Entity
#Table(name="attendance")
#Getter #Setter
public class AttendanceModel {
//#EmbeddedId
//private AttendanceId attendanceId;
#Id
#Column(name="attendance_id")
private long id;
#Column(name="reg_no")
private String regNo;
#Column(name="subject_id")
private long subjectId;
#Column(name="class_date")
private Date classDate;
#Column(name="present")
private boolean present;
}
Could you show me Student Model.If i look your code post : You using Unidirectional relationship.
I think it must :
#OneToMany(fetch = FetchType.LAZY , cascade = CascedeType.ALL)
#JoinColumn(name="attendance_id")
private List<AttendanceModel> attendances = new ArrayList<>();

Hibernate Annotation relations does not work with spring.jpa.generate-ddl=true

I am creating some simple Spring Boot project with Hibernate JPA.
I created some data model which consists 5 tables for now and created entities reflecting tables. I have set spring.jpa.generate-ddl=true and my entities was correctly reflected by schema created in PostgreSQL.
Next step was to start adding relations.
Part of my assumed datamodel is (paron my UML)
Very simple one to many relation.
My entities look that way (getters and setters omitted below, exist in code):
#Entity
public class AppUser {
#Id
#GeneratedValue
private long id;
private String name;
private String secondName;
private String email;
private java.util.Date joinDate;
#ManyToOne
#JoinColumn(name = "user_role_id")
private UserRole userRole;
}
#Entity
public class UserRole {
#Id
#GeneratedValue
private long id;
private String roleName;
}
I launch my application with spring.jpa.generate-ddl=true and column user_role_id gets created in AppUser table but application fails to start due errors:
2018-10-11 19:41:35.435 INFO 45564 --- [ main] org.hibernate.tool.hbm2ddl.SchemaUpdate : HHH000228: Running hbm2ddl schema update
2018-10-11 19:41:35.466 WARN 45564 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 42703
2018-10-11 19:41:35.466 ERROR 45564 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : ERROR: column t1.tgconstrname does not exist
There is full stacktrace (please advise if should paste it here instead of pastebin:
https://pastebin.com/x4qNJkK9
When I set spring.jpa.generate-ddl=false application starts succesfully.
Any ideas why is that happening?

Column does not exist in spring boot Postgres app

Hi in my spring boot postgresql application, when i retrieve all record using DAO it show column does not exists.
ERROR
WARN : org.hibernate.engine.jdbc.spi.SqlExceptionHelper - SQL Error: 0, SQLState: 42703
ERROR: org.hibernate.engine.jdbc.spi.SqlExceptionHelper - ERROR: column merchantit0_.id does not exist
Position: 8
ERROR: org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/customerplus].[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [/customerplus] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet] with root cause
org.postgresql.util.PSQLException: ERROR: column merchantit0_.id does not exist
Position: 8
Entity Domain
#Entity
#Table(name = "merchant_item_category")
public class MerchantItemCategory{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id", nullable = false, length = 11)
private long id;
#ManyToOne
#JoinColumn(name = "merchant_id", nullable = false)
private Merchant merchant;
// getters and setters
}
DAO
public List<MerchantItemCategory> getAllMerchantItemCategoryByMerchantId(long id) {
Session session=getSession();
List<MerchantItemCategory>itemCategories=session.createQuery("from MerchantItemCategory where merchant.id=:merchantId and isDelete='0' order by categoryName asc")
.setParameter("merchantId", id)
.list();
return itemCategories;
}
I just checked every object and it is correct, But how this error occurring..!
A potential cause of this error is when you haven't defined the hibernate "default schema" property.
I fixed this issue by adding line below to my application.properties:
spring.jpa.properties.hibernate.default_schema=${your-default-schema-name}

Categories

Resources