Q: Transactional Code why does this work so well? - spring-boot

Hello my professionals I have a simple question here that I would like to beg to solve this..
this is an Entity of Member
#Entity
#Getter
#Builder
#NoArgsConstructor(access = AccessLevel.PROTECTED)
#AllArgsConstructor
/*#ToString(of = {"id", "username", "age"})*/
public class Member {
#Id
/*#GeneratedValue(strategy = GenerationType.IDENTITY)*/
#Column(name = "member_id")
private Long id;
private String username;
private int age;
#OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "member")
private List<Team> teams;
#OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "member")
private List<Coach> coachs;
}
And this is an Entity of Coach
#Entity
#AllArgsConstructor
#Getter
#Builder
#Setter
#NoArgsConstructor
#ToString(of = {"id","name","career"})
public class Coach {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name= "coach_id")
private Long id;
#Column
private String name;
#Column
private String career;
#ManyToOne(fetch = FetchType.LAZY,cascade = ALL)
#JoinColumn(name = "member_id")
private Member member;
#OneToOne(fetch = FetchType.LAZY,cascade = ALL)
#JoinColumn(name = "team_id")
private Team team;
}
and This is Controller Code
#GetMapping("/member")
public void createUser(){
Member m = memberService.createMember();
Coach c = m.getCoachs().get(0);
log.info(c.getName());
}
and This is Service Code
private final MemberRepository memberRepository;
#Transactional
public Member createMember(){
return memberRepository.findMemberById(3L);
}
and the last this is RepositoryCode
Member findMemberById(Long id);
So my question is that when i printed out Coach's name at the controller on console
it printed out so well.
but what I know the Transaction is over from the service So the persistence container is closed that means coach name can't be imported cause it's LAZY loading and persistence container is closed but it was printed out well
I want to know the reason why ...
here are the console results Thanks !!
[2022-01-10 23:27:46.835] [http-nio-9000-exec-2] [] INFO o.a.c.c.C.[.[.[/] - Initializing Spring DispatcherServlet 'dispatcherServlet'
[2022-01-10 23:27:46.835] [http-nio-9000-exec-2] [] INFO o.s.w.s.DispatcherServlet - Initializing Servlet 'dispatcherServlet'
[2022-01-10 23:27:46.855] [http-nio-9000-exec-2] [] INFO o.s.w.s.DispatcherServlet - Completed initialization in 19 ms
Hibernate:
/* select
generatedAlias0
from
Member as generatedAlias0
where
generatedAlias0.id=:param0 */ select
member0_.member_id as member_i1_1_,
member0_.age as age2_1_,
member0_.username as username3_1_
from
member member0_
where
member0_.member_id=?
[2022-01-10 23:27:47.007] [http-nio-9000-exec-2] [4c0222d3] INFO p6spy - #1641824867007 | took 15ms | statement | connection 1| url jdbc:mariadb://patrick-lab.cjeq2ffynlc2.ap-northeast-2.rds.amazonaws.com:3306/patricklab?characterEncoding=UTF-8&serverTimezone=UTC
/* select generatedAlias0 from Member as generatedAlias0 where generatedAlias0.id=:param0 */ select member0_.member_id as member_i1_1_, member0_.age as age2_1_, member0_.username as username3_1_ from member member0_ where member0_.member_id=?
/* select generatedAlias0 from Member as generatedAlias0 where generatedAlias0.id=:param0 */ select member0_.member_id as member_i1_1_, member0_.age as age2_1_, member0_.username as username3_1_ from member member0_ where member0_.member_id=3;
[2022-01-10 23:27:47.170] [http-nio-9000-exec-2] [4c0222d3] INFO p6spy - #1641824867170 | took 12ms | commit | connection 1| url jdbc:mariadb://patrick-lab.cjeq2ffynlc2.ap-northeast-2.rds.amazonaws.com:3306/patricklab?characterEncoding=UTF-8&serverTimezone=UTC
;
Hibernate:
select
coachs0_.member_id as member_i4_0_0_,
coachs0_.coach_id as coach_id1_0_0_,
coachs0_.coach_id as coach_id1_0_1_,
coachs0_.career as career2_0_1_,
coachs0_.member_id as member_i4_0_1_,
coachs0_.name as name3_0_1_,
coachs0_.team_id as team_id5_0_1_
from
coach coachs0_
where
coachs0_.member_id=?
[2022-01-10 23:27:47.200] [http-nio-9000-exec-2] [4c0222d3] INFO p6spy - #1641824867200 | took 12ms | statement | connection 1| url jdbc:mariadb://patrick-lab.cjeq2ffynlc2.ap-northeast-2.rds.amazonaws.com:3306/patricklab?characterEncoding=UTF-8&serverTimezone=UTC
select coachs0_.member_id as member_i4_0_0_, coachs0_.coach_id as coach_id1_0_0_, coachs0_.coach_id as coach_id1_0_1_, coachs0_.career as career2_0_1_, coachs0_.member_id as member_i4_0_1_, coachs0_.name as name3_0_1_, coachs0_.team_id as team_id5_0_1_ from coach coachs0_ where coachs0_.member_id=?
select coachs0_.member_id as member_i4_0_0_, coachs0_.coach_id as coach_id1_0_0_, coachs0_.coach_id as coach_id1_0_1_, coachs0_.career as career2_0_1_, coachs0_.member_id as member_i4_0_1_, coachs0_.name as name3_0_1_, coachs0_.team_id as team_id5_0_1_ from coach coachs0_ where coachs0_.member_id=3;
[2022-01-10 23:27:47.213] [http-nio-9000-exec-2] [4c0222d3] INFO m.p.l.m.c.MemberController - Coach1

I believe it is because you are using the spring-boot default setting which the spring.jpa.open-in-view is set to true .
This property enables OpenSessionInView pattern which you can simply think that a transaction will be opened automatically for you at the very first beginning when processing any HTTP request (e.g. in the Servlet Filter etc). Because of this , a transaction is actually already open before your service method executes and it is still active after your service method completes. Hence you will not experience any LazyInitializationException even after you access non-initialized properties outside the service method as the transaction is still active.
There is a strong debate about whether or not spring-boot should enable it by default in the past . You can refer this for more details if you are interested. I personally would recommend to turn it off.

Related

Spring Data JPA - Lazy loading and #Fetch( FetchMode.JOIN)

2 Entity ProductMaster and Category
#Entity
#Table(name = "product_master")
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
#NamedQuery(name = "ProductMaster.findAll", query = "SELECT p FROM ProductMaster p")
public class ProductMaster implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String description;
//Many Product will have one categoary
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="category_id")
private Category category;
//get and set fn
}
#Entity
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
#Table(name = "category")
public class Category {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "category_name")
private String categoryName;
#JsonIgnore
#OneToMany(cascade = CascadeType.ALL, mappedBy = "category")
#Fetch( FetchMode.JOIN)
private Set<ProductMaster> products = new HashSet<ProductMaster>();
//get and set fn
}
while fetchAll in JPA repository of Product. Join is performed and its expected
Hibernate:
select
productmas0_.id as id1_1_,
productmas0_.category_id as categor11_1_,
productmas0_.created_by as created_2_1_,
productmas0_.created_dt as created_3_1_,
productmas0_.description as descript4_1_,
productmas0_.image as image5_1_,
productmas0_.is_favorite as is_favor6_1_,
productmas0_.price as price7_1_,
productmas0_.title as title8_1_,
productmas0_.updated_by as updated_9_1_,
productmas0_.updated_dt as updated10_1_
from
product_master productmas0_ limit ?
Hibernate:
select
category0_.id as id1_0_0_,
category0_.category_name as category2_0_0_,
category0_.created_by as created_3_0_0_,
category0_.created_dt as created_4_0_0_,
category0_.category_desc as category5_0_0_,
category0_.updated_by as updated_6_0_0_,
category0_.updated_dt as updated_7_0_0_,
products1_.category_id as categor11_1_1_,
products1_.id as id1_1_1_,
products1_.id as id1_1_2_,
products1_.category_id as categor11_1_2_,
products1_.created_by as created_2_1_2_,
products1_.created_dt as created_3_1_2_,
products1_.description as descript4_1_2_,
products1_.image as image5_1_2_,
products1_.is_favorite as is_favor6_1_2_,
products1_.price as price7_1_2_,
products1_.title as title8_1_2_,
products1_.updated_by as updated_9_1_2_,
products1_.updated_dt as updated10_1_2_
from
category category0_
left outer join
product_master products1_
on category0_.id=products1_.category_id
where
category0_.id=?
but while fetchAll in JPA repository of category multiple query for product are fired. I want lazy loading behavior here for product while fetch all in Category
select
category0_.id as id1_0_,
category0_.category_name as category2_0_,
category0_.created_by as created_3_0_,
category0_.created_dt as created_4_0_,
category0_.category_desc as category5_0_,
category0_.updated_by as updated_6_0_,
category0_.updated_dt as updated_7_0_
from
category category0_ Hibernate:
select
products0_.category_id as categor11_1_0_,
products0_.id as id1_1_0_,
products0_.id as id1_1_1_,
products0_.category_id as categor11_1_1_,
products0_.created_by as created_2_1_1_,
products0_.created_dt as created_3_1_1_,
products0_.description as descript4_1_1_,
products0_.image as image5_1_1_,
products0_.is_favorite as is_favor6_1_1_,
products0_.price as price7_1_1_,
products0_.title as title8_1_1_,
products0_.updated_by as updated_9_1_1_,
products0_.updated_dt as updated10_1_1_
from
product_master products0_
where
products0_.category_id=? 2022-09-25 13:39:56.507 TRACE 14160 --- [nio-8080-exec-5] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [BIGINT] - [2] Hibernate:
select
products0_.category_id as categor11_1_0_,
products0_.id as id1_1_0_,
products0_.id as id1_1_1_,
products0_.category_id as categor11_1_1_,
products0_.created_by as created_2_1_1_,
products0_.created_dt as created_3_1_1_,
products0_.description as descript4_1_1_,
products0_.image as image5_1_1_,
products0_.is_favorite as is_favor6_1_1_,
products0_.price as price7_1_1_,
products0_.title as title8_1_1_,
products0_.updated_by as updated_9_1_1_,
products0_.updated_dt as updated10_1_1_
from
product_master products0_
where
products0_.category_id=?
Problem statement to resolved here is that Number of Product query will be number of row in category table. We want this to be lazy load and don't want to perform multiple query for product while selecting category.
If you want a single query you should use left join fetch :
select c from Category c left join fetch c.products
And for the problem of multiple categories read this article
https://vladmihalcea.com/jpql-distinct-jpa-hibernate/
OneToMany relationships are inherently lazy but setting Fetch( FetchMode.JOIN) will override this lazy behaviour so should be removed if you want lazy fetching of products

Duplicate or Null error when trying to send POST request for JSON Object with Foreign Key using Spring JPA

Here's my parent entity:
#Entity(name = "DrivingInstructor")
#Table(name = "driving_instructor")
#Getter
#Setter
#NoArgsConstructor
public class DrivingInstructor {
#Id
#Column(name = "driving_instructor_id")
private long drivingInstructorId;
#Column(name = "driving_instructor_name")
#Size(max = 128)
private String drivingInstructorName;
#Column(name = "specialization")
#Size(max = 200)
private String specialisation;
}
And here's my supposed child entity:
#Entity(name = "DrivingStudent")
#Table(name = "driving_student")
#Getter
#Setter
#NoArgsConstructor
public class DrivingStudent {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "driving_student_id")
private long drivingStudentId;
#Column(name = "driving_student_name")
#Size(max = 128)
private String drivingStudentName;
#ManyToOne(cascade = CascadeType.ALL, targetEntity = DrivingInstructor.class)
#JoinColumn(name = "driving_instructor_id", referencedColumnName = "driving_instructor_name", insertable = false, updatable = false)
private DrivingInstructor drivingInstructor;
}
Here's the relevant chunk of my service class for inserting/saving an instance of a DrivingStudent into the database:
#RequestMapping(path = "api/v0/driving-school")
#RestController
#AllArgsConstructor
public class DrivingStudentRestController {
private final DrivingStudentServiceImpl drivingStudentServiceImpl;
#PostMapping
Long insertOrUpdateDrivingStudent(#Valid #RequestBody DrivingStudent drivingStudent) {
return drivingStudentServiceImpl.insertOrUpdateDrivingStudent(drivingStudent);
}
}
DrivingStudentServiceImpl is just an abstraction layer for Repository class that extends JpaRepository<DrivingStudent, Long>, so insertOrUpdateDrivingStudent() is practically just using the save() method from CrudRepository.
An instance of DrivingInstructor is already pre-inserted with drivingInstructorId of 1, and so I tried to execute a POST request via Postman using this JSON object:
{
"drivingStudentName": "Peter Parker",
"drivingInstructor": {"drivingInstructorId": 1}
}
And I'm getting this exception:
2021-08-27 20:03:37.554 ERROR 16108 --- [nio-8080-exec-3] o.h.engine.jdbc.spi.SqlExceptionHelper :
ERROR: duplicate key value violates unique constraint "driving_instructor_pkey"
Detail: Key (driving_instructor_id)=(1) already exists.
2021-08-27 20:03:37.590 ERROR 16108 --- [nio-8080-exec-3] 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 [driving_instructor_pkey];
nested exception is org.hibernate.exception.ConstraintViolationException:
could not execute statement] with root cause
org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "driving_instructor_pkey"
Detail: Key (driving_instructor_id)=(1) already exists.
I also tried revising my RestController's PostMapping to look like this, but still nothing changes:
#RequestMapping(path = "api/v0/driving-school")
#RestController
#AllArgsConstructor
public class DrivingStudentRestController {
private final DrivingInstructorRepository drivingInstructorRepository;
private final DrivingStudentServiceImpl drivingStudentServiceImpl;
#PostMapping
Long insertOrUpdateDrivingStudent(#Valid #RequestBody DrivingStudent drivingStudent) {
Optional<DrivingInstructor> drivingInstructor = drivingInstructorRepository.findById(drivingStudent.getDrivingInstructor().getDrivingInstructorId());
if (drivingInstructor.isPresent()) {
drivingStudent.setDrivingInstructor(drivingInstructor.get());
return drivingStudentServiceImpl.insertOrDrivingStudent(drivingStudent);
}
return null;
}
}
The error I am getting then changed to:
2021-08-27 21:36:58.622 ERROR 11388 --- [nio-8080-exec-4] o.h.engine.jdbc.spi.SqlExceptionHelper :
ERROR: null value in column "driving_instructor_number" of relation "driving_student" violates not-null constraint
Detail: Failing row contains (Peter Parker, null).
2021-08-27 21:36:58.632 ERROR 11388 --- [nio-8080-exec-4] 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 [driving_instructor_number" of relation "driving_student];
nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause
org.postgresql.util.PSQLException: ERROR: null value in column "driving_instructor_number" of relation "driving_student" violates not-null constraint
Detail: Failing row contains (Peter Parker, null).
There are stuff I've tried but most exceptions simply end up with either of those two. All I really wanted to do was insert an instance of DrivingStudent into the database using POST request, with a foreign key connecting it to a DrivingInstructor instance, and then of course, be able to retrieve those data.
I am able to do insert data manually into the database using the statement:
INSERT INTO driving_student VALUES ('Peter Parker', 1);
And I am able to retrieve that data in JSON format using GET method. So far, my only problem really is how to deal with the POST method.
Ok, I just changed/simplified the annotations in DrivingStudent's drivingInstructor JoinColumn field from this:
#ManyToOne(cascade = CascadeType.ALL, targetEntity = DrivingInstructor.class)
#JoinColumn(name = "driving_instructor_id", referencedColumnName = "driving_instructor_name", insertable = false, updatable = false)
private DrivingInstructor drivingInstructor;
to this:
#ManyToOne
#JoinColumn(name = "driving_instructor_id")
private DrivingInstructor drivingInstructor;
and it somehow worked... I have no idea why though.

EntityNotFoundException on OneToOne Mapping, even though entity exists

I have two classes:
public class Account {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "accountId")
private Long id;
#OneToOne(optional = true)
#JoinColumn(name = "informationId")
private Information information;
}
public class Information {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "informationId")
private Long id;
#OneToOne(mappedBy = "information", cascade = CascadeType.ALL, optional = true)
private Account account;
}
When I make a call that retrieves an Account, I get this exception:
WARN o.h.e.loading.internal.LoadContexts - HHH000100: Fail-safe cleanup (collections) : org.hibernate.engine.loading.internal.CollectionLoadContext#2ecc21a
WARN o.h.e.l.i.CollectionLoadContext - HHH000160: On CollectionLoadContext#cleanup, localLoadingCollectionKeys contained [1] entries
WARN Unable to find Information with id 114; nested exception is javax.persistence.EntityNotFoundException: Unable to find Information with id 114
However, the database shows that there is an Information object with informationId 114, and an Account with a informationId foreign key of 114.
How come I am getting this exception?
EDIT
This is the call that causes the exception:
List<Following> following = followingService.findFollowingByUserId(userId);
In followingService, this is just a call to the dao. A Following object has a User object, and the User owns an Account. The following object populates just fine if I remove the Account mapping
Can you post complete code where this entity is being persisted and fetched?
This information is not sufficient to answer this query.
Could it be that you have a table with 1 entity and the other table with 0?
For me it seems like this:
Account
ID | Name | InformationID
-------------------------
1 | Acc | 114
-------------------------
Information
ID | Name | Account
-------------------
-------------------

How is jackson serializing object outside of transition

This is a bit bizarre for me. My understanding is if you try to access entity outside of Hibernate session you should get an LazyInitializationException - no session, but I am not getting this exception. In fact it seems like I still have session continue to my controller outside of my service layer which has #Transactional annotation.
Question
Is this the way it should be? or there is something I didn't set up correctly?
Structure
User
|
Profile { hierarchies entity }
|
+-----+-----+
| |
Teacher Student
User
#Entity
#Table(name="user")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstname;
private String lastname;
#OneToMany(fetch = FetchType.LAZY , mappedBy = "user")
#JsonManagedReference
#JsonInclude(JsonInclude.Include.NON_EMPTY)
private List<Profile> profiles = new ArrayList<>();
Service
#Override
#Transactional
public User getUserById(Long id) {
Optional<User> optionalUser = userRepo.findById(id);
User user = optionalUser.get();
logger.info("\n User -> {}", user);
return user;
}
Controller :: Instead of thow Exception, or should return empty array. Hibernate perform a left join
#GetMapping(value="/{userId}", produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
public User getUser(#PathVariable("userId") Long userId) {
logger.info("User Controller is called");
User user = userService.getUserById(userId);
logger.info("User is returned -> {}", user);
logger.info("Profiles -> {}", user.getProfiles()); // <-- Expecting this to throw LazyInitializationException
return user;
}
Console
018-05-31 15:17:35.462 INFO 15599 --- [nio-8080-exec-1] c.d.c.controller.UserController : User Controller is called
Hibernate:
select
user0_.id as id1_4_0_,
user0_.firstname as firstnam2_4_0_,
user0_.lastname as lastname3_4_0_
from
user user0_
where
user0_.id=?
2018-05-31 15:17:35.467 INFO 15599 --- [nio-8080-exec-1] c.d.c.services.UserServiceImpl :
User ->
User [id=1, firstname=Hendric, lastname=Rosenberg]
2018-05-31 15:17:35.467 INFO 15599 --- [nio-8080-exec-1] c.d.c.controller.UserController : User is returned ->
User [id=1, firstname=Hendric, lastname=Rosenberg]
Hibernate:
select
profiles0_.user_id as user_id2_3_0_,
profiles0_.id as id1_3_0_,
profiles0_.id as id1_3_1_,
profiles0_.user_id as user_id2_3_1_,
profiles0_1_.citizent_id as citizent1_2_1_,
profiles0_1_.profile_type as profile_2_2_1_,
profiles0_2_.license as license1_1_1_,
profiles0_2_.practitioner_type as practiti2_1_1_,
profiles0_2_.profile_type as profile_3_1_1_,
profiles0_2_.specialized as speciali4_1_1_,
case
when profiles0_1_.id is not null then 1
when profiles0_2_.id is not null then 2
when profiles0_.id is not null then 0
end as clazz_1_
from
profile profiles0_
left outer join
patient profiles0_1_
on profiles0_.id=profiles0_1_.id
left outer join
medical_profession profiles0_2_
on profiles0_.id=profiles0_2_.id
where
profiles0_.user_id=?
c.d.c.controller.UserController : User is returned -> [
Student [profileType=STUDENT, id=A1236578889],
Teacher [profileType=TEACHER, license=234SFLLWEKD32342]]
spring.jpa.open-in-view = true is set by default. So you won't get a LazyInitializationException
This property will register an OpenEntityManagerInViewInterceptor
Spring web request interceptor that binds a JPA EntityManager to the thread for the entire processing of the request. Intended for the "Open EntityManager in View" pattern, i.e. to allow for lazy loading in web views despite the original transactions already being completed.
This interceptor makes JPA EntityManagers available via the current thread, which will be autodetected by transaction managers. It is suitable for service layer transactions via JpaTransactionManager or JtaTransactionManager as well as for non-transactional read-only execution.
In contrast to OpenEntityManagerInViewFilter, this interceptor is set up in a Spring application context and can thus take advantage of bean wiring.

Spring Data REST getting exception when trying to save the data

I new to using Spring data rest , so even though this might be a very basic thing I would appreciate it if someone could point what is the mistake that i made or point me in the right direction .
I have an EmployeeRepository which contains the employee entities.
public interface EmployeeRepository extends CrudRepository<Employee,Long>{
#Query("select emp from Employee emp where emp.employeeId=?1")
Employee findById(String employeeId);
#Query("select emp from Employee emp where emp.officialEmailId = ?1")
Employee findByOfficialEmailId(String officialEmailId);
}
Below is a part of the employee entity delcaration .
public class Employee extends AbstractAuditingEntity{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Version
private Long version;
#Size(min = 3, max = 30)
#NotBlank
#Column(unique=true,nullable=false)
private String employeeId;
#Size(min=3,max = 25)
#NotBlank
#Field(index=Index.YES, analyze=Analyze.NO, store=Store.YES)
private String lastName;
#Size(min=3,max = 25)
#Field(index=Index.YES, analyze=Analyze.NO, store=Store.YES)
#NotBlank
private String firstName;
#Size(min=3,max = 25)
#Field(index=Index.YES, analyze=Analyze.NO, store=Store.YES)
private String middleName;
}
In my service class I needed to get list of employee entities based on a condition and set a common property to all those .I tried it and it did not work so I tried something much simpler , I'm trying to set the middle name of all employees to a common value and save it to the db . Here is the code for it
#Transactional
public void tempFunction(){
Iterable<Employee> empList = employeeRepository.findAll();
for(Employee e : empList){
e.setMiddleName("newMiddleName");
employeeRepository.save(e);
}
}
I'm getting the below exception 2016-02-20 17:59:08.545 ERROR 533 --- [nio-8080-exec-1] 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.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction] with root cause
java.lang.NullPointerException: null
And the stack trace shows the root cause to be a NullPointerException which I know is not present anywhere near where I'm invoking this code from either in my controller or service . Could someone point if there is any mistake in my code , thanks in advance .

Resources