简体   繁体   中英

spring boot migration from 1.5 to 2.1, hibernate errors

I migrated my spring boot version from 1.5 to 2.1. Now started using hibernate version 5.3.12 vs previously 5.0.12. And now I am seeing lot of previously uncaught hibernate exceptions like:

On @OneToOne mapping annotation because Cascade type was missing:

ERROR: update or delete on table violates foreign key constraint

On a @Test when I am trying to get a record by: repository.findById()

org.hibernate.LazyInitializationException: could not initialize proxy - no Session

on old project with hibernate 5.0.12 these errors don't appear, but as soon as I switch to new spring boot project, these start appearing with the only change factor being upgraded spring dependencies and hibernate version.

Tried to search on this but couldn't find anything specific about what changed in this hibernate version vs the previous ones. Has anyone encountered similar issues? any help or hint would be much appreciated since I am stuck on these.

So, the reason of all of them that you try to serialize your objects out of Service layer. (Transactional annotation)

@Entity
class A {

   @OneToOne(fetch = FetchType.LAZY)
   private B b;
}

If you try to serialize class A out of service layer, then hibernate session is already closed, and u have a mentioned exception

Check this one https://www.baeldung.com/hibernate-lazy-eager-loading

The correct way to fix it, is to assemble DTO (data transfer object) and return it from service layer to controller. And afterwards serialize DTO.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM