jhipster / generator-jhipster

JHipster is a development platform to quickly generate, develop, & deploy modern web applications & microservice architectures.
https://www.jhipster.tech
Apache License 2.0
21.47k stars 4.02k forks source link

Sql and Redis fails with LazyInitializationException #22889

Closed aniplayIt closed 4 months ago

aniplayIt commented 1 year ago
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.

  2. 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.

  3. 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.

  4. 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**

<!-- Has a similar issue been reported before? Please search both closed & open issues -->

##### **Suggest a Fix**

<!-- If you can't fix the bug yourself, perhaps you can point to what might be
  causing the problem (line of code or commit) -->

##### **JHipster Version(s)**

8.0.0-beta.2

##### **JHipster configuration**

-- generator-jhipster@8.0.0-beta.2

JHipster configuration, a .yo-rc.json file generated in the root folder
.yo-rc.json file
{
  "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
}
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
JDL entity definitions

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

Congratulations, JHipster execution is complete!


<!--
To provide all information we need, you should run `jhipster info` in the project root folder, and
copy/paste the result here.
The `.yo-rc.json` file generated in the root folder is mandatory for bug reports. This will help us to replicate the scenario.
You should remove any sensitive information like the rememberMe key or the jwtSecretKey key.
---
If you have a JDL please wrap it in below structure
  <details>
  <summary>JDL definitions</summary>
  <pre>
     JDL content here
  </pre>
  </details>
-->

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

<!--
If the error is during an entity creation or associated with a specific entity.
If you are using JDL, please share that configuration as well.
-->

##### **Browsers and Operating System**

Windows 11 Pro
<!-- What OS are you on? is this a problem with all browsers or only IE8? -->

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

<!-- Love JHipster? Please consider supporting our collective:
👉  https://opencollective.com/generator-jhipster/donate -->
mshima commented 1 year ago

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

Every redis test is passing:

May be related to windows?

aniplayIt commented 1 year ago

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

github-actions[bot] commented 1 year ago

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.

mluckenbill commented 9 months ago

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

mluckenbill commented 9 months ago

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);

}`
greenpulsar commented 9 months ago

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?

raghu777 commented 7 months ago

Facing the same issue with 8.1.0.

ikomangmahendra commented 6 months ago

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

solnone commented 4 months ago

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

mshima commented 4 months ago

@solnone can you provide a PR?

solnone commented 4 months ago

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

mshima commented 4 months ago

@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?