question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

LazyInitializationException on an entity with ManyToMany, pagination and mapstruct

See original GitHub issue
Overview of the issue

Hibernate throws an exception when trying to get all Job entities after creating a Job entity.

Exception in com.jhipster.web.rest.JobResource.getAllJobs() with cause = 'NULL' and exception = 'failed to lazily initialize a collection of role: com.jhipster.domain.Job.tasks, could not initialize proxy - no Session'

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.jhipster.domain.Job.tasks, could not initialize proxy - no Session
	at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:582)
	at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:201)
	at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:561)
	at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:132)
	at org.hibernate.collection.internal.PersistentSet.iterator(PersistentSet.java:163)
	at com.jhipster.service.mapper.JobMapperImpl.taskSetToTaskDTOSet(JobMapperImpl.java:140)
	at com.jhipster.service.mapper.JobMapperImpl.jobToJobDTO(JobMapperImpl.java:58)
	at com.jhipster.service.mapper.JobMapperImpl.jobsToJobDTOs(JobMapperImpl.java:81)
Motivation for or Use Case

This issue only appears when having an entity with a ManyToMany relationship, being paginated (pager, pagination or infinite-scroll) and dto generated with mapstruct. It’s a little specific but if you use the default JDL from JDL Studio you will have the issue.

Reproduce the error

Use the JDL below to generate entities. Create a Job entity with no Task. An exception will be thrown when displaying all Job.

Related issues

Found nothing related.

Suggest a Fix

Maybe by doing an eager load on the ManyToMany relationship like it’s done when Job is not paginated.

JHipster Version(s)

4.3.0

JHipster configuration
JHipster Version(s)
jhipster@0.0.0 /Users/Theo/Documents/perso/jhipster-issues
└── generator-jhipster@4.3.0

JHipster configuration, a .yo-rc.json file generated in the root folder
{
  "generator-jhipster": {
    "promptValues": {
      "packageName": "com.jhipster"
    },
    "jhipsterVersion": "4.3.0",
    "baseName": "jhipster",
    "packageName": "com.jhipster",
    "packageFolder": "com/jhipster",
    "serverPort": "8080",
    "authenticationType": "session",
    "hibernateCache": "ehcache",
    "clusteredHttpSession": false,
    "websocket": false,
    "databaseType": "sql",
    "devDatabaseType": "h2Disk",
    "prodDatabaseType": "mysql",
    "searchEngine": false,
    "messageBroker": false,
    "serviceDiscoveryType": false,
    "buildTool": "maven",
    "enableSocialSignIn": false,
    "rememberMeKey": "2b4523900caffa3f139b0240dc516cfd9735ba18",
    "clientFramework": "angular1",
    "useSass": false,
    "clientPackageManager": "yarn",
    "applicationType": "monolith",
    "testFrameworks": [],
    "jhiPrefix": "jhi",
    "enableTranslation": false
  }
}
Entity configuration(s) entityName.json files generated in the .jhipster directory

Job.json

{
    "fluentMethods": true,
    "relationships": [
        {
            "relationshipType": "many-to-many",
            "otherEntityRelationshipName": "job",
            "relationshipName": "task",
            "otherEntityName": "task",
            "otherEntityField": "id",
            "ownerSide": true
        }
    ],
    "fields": [
        {
            "fieldName": "jobTitle",
            "fieldType": "String"
        }
    ],
    "changelogDate": "20170420032832",
    "entityTableName": "job",
    "dto": "mapstruct",
    "pagination": "pagination",
    "service": "no"
}

Task.json

{
    "fluentMethods": true,
    "relationships": [
        {
            "relationshipType": "many-to-many",
            "relationshipName": "job",
            "otherEntityName": "job",
            "ownerSide": false,
            "otherEntityRelationshipName": "task"
        }
    ],
    "fields": [
        {
            "fieldName": "title",
            "fieldType": "String"
        }
    ],
    "changelogDate": "20170420032831",
    "entityTableName": "task",
    "dto": "mapstruct",
    "pagination": "no",
    "service": "no"
}
Browsers and Operating System

java version “1.8.0_92” Java™ SE Runtime Environment (build 1.8.0_92-b14) Java HotSpot™ 64-Bit Server VM (build 25.92-b14, mixed mode)

git version 2.10.1 (Apple Git-78)

node: v7.8.0

npm: 4.2.0

bower: 1.8.0

gulp: [23:47:04] CLI version 1.2.2 [23:47:04] Local version 3.9.1

yeoman: 1.8.5

yarn: 0.22.0

Docker version 17.03.1-ce, build c6d412e

docker-compose version 1.11.2, build dfed245

Entity configuration(s) entityName.json files generated in the .jhipster directory

JDL

entity Task {
	title String
}

entity Job {
	jobTitle String
}

relationship ManyToMany {
	Job{task} to Task{job}
}

paginate Job with pagination
dto * with mapstruct
Browsers and Operating System

Chrome 57 on OS X El Capitan

  • Checking this box is mandatory (this is just to show you read everything)

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:48 (43 by maintainers)

github_iconTop GitHub Comments

3reactions
deepu105commented, Nov 30, 2017

@gzsombor @jdubois what you think of showing DTO and Filter option only when Service is selected? it will atleast solve these kind of issues

3reactions
gzsomborcommented, Nov 30, 2017

The better solution is to fix the transaction handling :

  • either put the mapper code inside the service (which already has @Transactional annotation)
  • or if you insist on not using services, put @Transactional annotation on your rest methods.

Basically, you need to access your database from a code block, which is in a ‘JPA/hibernate session’

Read more comments on GitHub >

github_iconTop Results From Across the Web

LazyInitializationException on an entity with ManyToMany ...
This issue only appears when having an entity with a ManyToMany relationship, being paginated (pager, pagination or infinite-scroll) and dto ...
Read more >
LazyInitializationException with Mapstruct because of cyclic ...
The problem is that when the code returns from findAll the entities are not managed anymore. So you have a LazyInitializationException ...
Read more >
LazyInitializationException - What it is and the best way to fix it
The LazyInitializationException is one of the most common exceptions when working with Hibernate. There are a few easy ways to fix it.
Read more >
Spring Data JPA pitfalls and modern alternatives
LazyInitializationException when serializing associations with FetchType.LAZY; there's 99% chance that entity or DTO structure will change and ...
Read more >
Baeldung Author
Learn to use a UUID as an entity ID in MongoDB. Read More → ... LazyInitializationException : could not initialize proxy – no...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found