generator-jhipster icon indicating copy to clipboard operation
generator-jhipster copied to clipboard

Sql and Redis fails with LazyInitializationException

Open aniplayIt opened this issue 2 years ago • 7 comments

Overview of the issue

As fresh created project:

  1. The app can't start:
Task :openApiGenerate
Error snake-parsing yaml content
java.lang.NoSuchMethodError: org.yaml.snakeyaml.constructor.SafeConstructor: method 'void <init>()' not found

Adding validateSpec = false skipValidateSpec = true in swagger.gradle let the app start but it's not a valid fix.

  1. The ApiUtil from OpenApi generated files requires the import javax.servlet.http.HttpServletResponse;. Adding the dependency javax.servlet:javax.servlet-api fixes the issue but it's not a valid fix.
  2. After running Redis container with redis.yml or redis-cluster.yml the app can't connect to the redis instance. Running the command redis-cli --cluster fix localhost:6379 inside the redis container fixed the issue. Don't know if it's the proper way to use this.
  3. After running the app I cannot execute more than one api call. Let's say I authenticate myself receiving the bearer token correctly, if I ask then for my account data (passing the token) I get the following error:
Unable to decode data. channel: [id: 0xda2a185f, L:/127.0.0.1:63567 - R:localhost/127.0.0.1:6379], reply: ReplayingDecoderByteBuf(ridx=288, widx=288), command: (EVAL), promise: java.util.concurrent.CompletableFuture@70e7940b[Not completed, 1 dependents], params: [local value = redis.call('hget', KEYS[1], ARGV[3]); if value == false then return nil; end; local expireDateScore = redis.call('zscore', KEYS[2], ARGV[3]); if expireDateScore ~= false and tonumber(expireDateScore) <= tonumber(ARGV[2]) then return nil; end; return value; , 3, usersByLogin, jcache_timeout_set:{usersByLogin}, jcache_removed_channel:{usersByLogin}, -1, 1689606938561, PooledUnsafeDirectByteBuf(ridx: 0, widx: 6, cap: 256)] 

com.esotericsoftware.kryo.KryoException: org.hibernate.LazyInitializationException: failed to lazily initialize a collection: could not initialize proxy - no Session
Serialization trace:
authorities (it.app.my_service.domain.User)
	at com.esotericsoftware.kryo.serializers.ReflectField.read(ReflectField.java:146)
	at com.esotericsoftware.kryo.serializers.FieldSerializer.read(FieldSerializer.java:129)
	at com.esotericsoftware.kryo.Kryo.readClassAndObject(Kryo.java:880)
	at org.redisson.codec.Kryo5Codec$4.decode(Kryo5Codec.java:144)
	at org.redisson.client.handler.CommandDecoder.decode(CommandDecoder.java:393)
	at org.redisson.client.handler.CommandDecoder.decodeCommand(CommandDecoder.java:205)
	at org.redisson.client.handler.CommandDecoder.decode(CommandDecoder.java:144)
	at org.redisson.client.handler.CommandDecoder.decode(CommandDecoder.java:120)
	at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:529)
	at io.netty.handler.codec.ReplayingDecoder.callDecode(ReplayingDecoder.java:366)
	at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:290)
	at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:444)
	at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:420)
	at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:412)
	at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1410)
	at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:440)
	at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:420)
	at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:919)
	at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:166)
	at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:788)
	at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:724)
	at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:650)
	at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:562)
	at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:997)
	at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
	at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
	at java.base/java.lang.Thread.run(Thread.java:833)
Caused by: org.hibernate.LazyInitializationException: failed to lazily initialize a collection: could not initialize proxy - no Session
	at org.hibernate.collection.spi.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:635)
	at org.hibernate.collection.spi.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:218)
	at org.hibernate.collection.spi.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:615)
	at org.hibernate.collection.spi.PersistentSet.add(PersistentSet.java:184)
	at com.esotericsoftware.kryo.serializers.CollectionSerializer.read(CollectionSerializer.java:241)
	at com.esotericsoftware.kryo.serializers.CollectionSerializer.read(CollectionSerializer.java:44)
	at com.esotericsoftware.kryo.Kryo.readObject(Kryo.java:799)
	at com.esotericsoftware.kryo.serializers.ReflectField.read(ReflectField.java:124)
	... 26 common frames omitted
Motivation for or Use Case

Well, I can't use the app :D

Reproduce the error
? What is the base name of your application? prova2
? Which *type* of application would you like to create? Monolithic application (recommended for simple projects)
? Would you like to enable internationalization support? Yes
? Please choose the native language of the application English
? Please choose additional languages to install Italian
? Do you want to make it reactive with Spring WebFlux? No
? What is your default Java package name? com.mycompany.myapp
? Which *type* of authentication would you like to use? JWT authentication (stateless, with a token)
? Which *type* of database would you like to use? SQL (H2, PostgreSQL, MySQL, MariaDB, Oracle, MSSQL)
? Which *production* database would you like to use? PostgreSQL
? Which *development* database would you like to use? PostgreSQL
? Which cache do you want to use? (Spring cache abstraction) Redis (distributed cache)
? Do you want to use Hibernate 2nd level cache? Yes
? Would you like to use Maven or Gradle for building the backend? Gradle
? Which other technologies would you like to use? Elasticsearch as search engine, WebSockets using Spring Websocket, API first development using OpenAPI-generator
? Which *Framework* would you like to use for the client? No client
? Besides JUnit and Jest, which testing frameworks would you like to use? Cucumber
Related issues
Suggest a Fix
JHipster Version(s)

8.0.0-beta.2

JHipster configuration
-- [email protected]
##### **JHipster configuration, a `.yo-rc.json` file generated in the root folder**
<details>
<summary>.yo-rc.json file</summary>
<pre>
{
  "applicationType": "monolith",
  "authenticationType": "jwt",
  "baseName": "my-service",
  "buildTool": "gradle",
  "cacheProvider": "redis",
  "clientFramework": "angular",
  "creationTimestamp": 1689588057666,
  "databaseType": "sql",
  "devDatabaseType": "postgresql",
  "dtoSuffix": "DTO",
  "enableGradleEnterprise": null,
  "enableHibernateCache": true,
  "enableSwaggerCodegen": true,
  "enableTranslation": true,
  "entities": [],
  "entitySuffix": "",
  "gradleEnterpriseHost": null,
  "jhiPrefix": "jhi",
  "jhipsterVersion": "8.0.0-beta.2",
  "languages": [
    "en",
    "fr",
    "it"
  ],
  "messageBroker": false,
  "microfrontend": false,
  "microfrontends": [],
  "nativeLanguage": "en",
  "packageFolder": "it/app/my_service",
  "packageName": "it.app.my_service",
  "pages": [],
  "prodDatabaseType": "postgresql",
  "reactive": false,
  "searchEngine": "elasticsearch",
  "serverPort": null,
  "serverSideOptions": [
    "searchEngine:elasticsearch",
    "websocket:spring-websocket",
    "enableSwaggerCodegen:true"
  ],
  "serviceDiscoveryType": false,
  "skipCheckLengthOfIdentifier": false,
  "skipFakeData": false,
  "skipUserManagement": false,
  "testFrameworks": [
    "cucumber",
    "cypress"
  ],
  "websocket": "spring-websocket",
  "withAdminUi": true
}
</pre>
</details>


##### **Environment and Tools**

java version "17.0.7" 2023-04-18 LTS
Java(TM) SE Runtime Environment (build 17.0.7+8-LTS-224)
Java HotSpot(TM) 64-Bit Server VM (build 17.0.7+8-LTS-224, mixed mode, sharing)

git version 2.39.1.windows.1

node: v18.16.1
npm: 9.7.2

Docker version 24.0.2, build cb74dfc

##### **JDL for the Entity configuration(s) `entityName.json` files generated in the `.jhipster` directory**

<details>
<summary>JDL entity definitions</summary>

<pre>

</pre>
</details>

✔ applying multi-step templates
     info Multiple customCommitTask tasks found (...#jhipster:info, jhipster:bootstrap). Using the first.

Congratulations, JHipster execution is complete!
Entity configuration(s) entityName.json files generated in the .jhipster directory
Browsers and Operating System

Windows 11 Pro

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

aniplayIt avatar Jul 17 '23 15:07 aniplayIt

Open api generator is known to be broken: https://github.com/jhipster/generator-jhipster/pull/22658

Every redis test is passing:

  • https://github.com/hipster-labs/jhipster-daily-builds/actions/runs/5584163763/jobs/10205262014
  • https://github.com/jhipster/generator-jhipster/actions/runs/5585972785/jobs/10209524514
  • others.

May be related to windows?

mshima avatar Jul 18 '23 13:07 mshima

Just tested on Mac with both redis and redis cluster but got the exact same exception

aniplayIt avatar Jul 18 '23 14:07 aniplayIt

JHipster has completed the sample check .yo-rc.json: valid Entities JDL: blank Application: successfully generated Frontend check: success Backend check: failure E2E check: failure

This check uses jhipster info output from the issue description to generate the sample. Bug report that does not contain this information will be marked as invalid.

github-actions[bot] avatar Aug 25 '23 13:08 github-actions[bot]

I was able to reproduce this error using Maven + Redis + MySQL + Elasticsearch on a M1 MacBook Pro.

mluckenbill avatar Nov 26 '23 19:11 mluckenbill

As I was able to replicate the issue. I was able to pass the test by doing the following modification in the DomainUserDetailsService class.

New Code: ` public UserDetails loadUserByUsername(final String login) { log.debug("Authenticating {}", login);

    if (new EmailValidator().isValid(login, null)) {

        Optional<User> userByEmailFromDatabase = userRepository.findOneByEmailIgnoreCase(login);

        User user = userByEmailFromDatabase.orElseThrow(() -> new UsernameNotFoundException("User with email " + login + " was not found in the database"));

        return createSpringSecurityUser(login, user);
    }

    String lowercaseLogin = login.toLowerCase(Locale.ENGLISH);
    Optional<User> userByLoginFromDatabase = userRepository.findOneByLogin(lowercaseLogin);

    User user = userByLoginFromDatabase.orElseThrow(() -> new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the database"));

    return createSpringSecurityUser(lowercaseLogin, user);

}`

mluckenbill avatar Nov 26 '23 20:11 mluckenbill

Any new about this issue? I tried to use the code posted by @mluckenbill , but I'm receiving the same issue. jhipsterInfo.txt

Error log: logRedisError.txt

Can you help me?

greenpulsar avatar Dec 12 '23 17:12 greenpulsar

Facing the same issue with 8.1.0.

raghu777 avatar Jan 23 '24 10:01 raghu777

I faced the same issue: javax.cache.CacheException: com.esotericsoftware.kryo.KryoException: org.hibernate.LazyInitializationException: failed to lazily initialize a collection: could not initialize proxy - no Session

jHipster Version: 8.1.0 Generated by Jhipster web: Monolith, JWT, Postgres DB (Prod&Dev), Redis, Hibernate 2nd Cache, Angular and Gradle Node: v20.11.1 NPM: 10.2.4 OS: Windows 11

ikomangmahendra avatar Feb 28 '24 16:02 ikomangmahendra

redisson-3.19.0 Breaking change - default codec changed to Kryo5Codec

java - Tomcat with RedissonSessionManager cannot deserialize SecurityContextImpl - Stack Overflow

CacheConfiguration.java

Config config = new Config();
// config.setCodec(new org.redisson.codec.MarshallingCodec());
config.setCodec(new org.redisson.codec.SerializationCodec());
if (jHipsterProperties.getCache().getRedis().isCluster()) {

https://youtu.be/C--Fqj0_9AQ?t=305

solnone avatar Apr 26 '24 17:04 solnone

@solnone can you provide a PR?

mshima avatar Apr 26 '24 19:04 mshima

Codec Update: SerializationCodec for Redis Fix https://github.com/jhipster/generator-jhipster/pull/25988

solnone avatar Apr 29 '24 08:04 solnone

@solnone micronaut needs the same fix: https://github.com/jhipster/generator-jhipster-micronaut/blob/8884f9341521ccb69631913f04c2b05f7616ee9f/generators/micronaut-cache/templates/src/main/java/package/config/CacheConfiguration.java.ejs#L70

Do you want to provide a PR?

mshima avatar Apr 29 '24 12:04 mshima