# Spring Boot 3.x Migration

This is a guide for services based on the app framework for migration to Spring Boot 3.x.

<div class="docs-note"><span class="docs-admonitions-text">note</span>

The App Framework provided in this documentation is exclusively designed for use within the specific application referenced herein. It is not intended for the development of new tenant applications. Any attempt to extend or modify the framework for use in other projects or environments is not recommended.Please ensure that the framework is only utilized for its intended purpose within the specified application.

</div>

## Overview  

Spring Boot 3.0 requires Java 17 or a later version, alongside Spring Framework 6.0.

See the following migration reference links:

- [Spring Boot 3.0 Migration Guide](https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-3.0-Migration-Guide)

- [Upgrading to Spring Framework 6.x](https://github.com/spring-projects/spring-framework/wiki/Upgrading-to-Spring-Framework-6.x)

- [Hibernate 6.4 Migration Guide](https://docs.jboss.org/hibernate/orm/6.4/migration-guide/migration-guide.html)

- [Spring Batch 5.0 Migration Guide](https://github.com/spring-projects/spring-batch/wiki/Spring-Batch-5.0-Migration-Guide)

### Major Changes in the App Framework

#### Upgrade

- Update to JDK 17 (17.0.10+7 or higher)

- SpringBoot 3.2 (3.2.11 or higher)
  - Hibernate 6 (6.5.1.Final or higher)
  - Spring Framework 6 (6.1.14 or higher)

- Spring Batch 5 (5.1.2 or higher)

#### Remove

- Remove the vela-security-auth.

- Remove Spring Security for simplicity and the API gateway is responsible for the authorization.

- Remove Spring Cloud for simplicity based on the insureMO architecture.

  - Properties configuration is based on insureMO Config Center.
  - Service register/routing is based on k8s.
  - API gateway has been switched to insureMO API gateway.

- Remove `bootstrap.properties` and migrate properties to `application.properties`.

- Remove vela-zipkin-support.

#### Replacement

- Jakarta EE changes, replace related artifacts and packages of **javax** with **jakarta**.

- Provide vela-trace-support as a replacement for vela-zipkin-support.
  
  Change tracing from sleuth/brave + zipkin to micrometer + opentelemetry.

  <div class="docs-note"><span class="docs-admonitions-text">note</span>

  The micrometer serves as an observation facade, similar to SLF4J (Simple Logging Facade for Java) for logging.
  
  </div>

### Major Changes in Platform Services

- Upgrade Activiti to 8.1.0.
- Remove Camel for simplicity, in flavor of pure coding logic.

    <div class="docs-note"><span class="docs-admonitions-text">note</span>

    Camel was engaged in service orchestration for a core-system-oriented architecture.

    </div>
- New version of boot-admin.

## Preparation

### Install JDK 17

**[Archive | Adoptium](https://adoptium.net/temurin/archive/?version=17)**

<div class="docs-note"><span class="docs-admonitions-text">note</span>

Don’t forget to apply JDK 17 to your projects in your IDE, such as IntelliJ, Eclipse.

</div>

### Upgrade the App Framework Version

There are several options for BFF to use the app framework. Please upgrade the version according to your choice.

Option 1: Use vela parent as maven parent.

<div class="docs-note"><span class="docs-admonitions-text">note</span>

It will inherit the app framework build and deployment approach. Then artifacts can be built as `-db.zip`, `-dbasset.zip`, `-release.zip`, etc.

</div>

```java
<!-- update the version of parent -->
<parent>
 <groupId>com.ebao.vela</groupId>
 <artifactId>vela-parent</artifactId>
 <version>98.03.001</version> <!-- may be changed due to AppFramework's speciality -->
</parent>
```

Option 2: Import bom of the app framework in maven dependency management.

<div class="docs-note"><span class="docs-admonitions-text">note</span>

 This option is for external development.

</div>

```java
<parent>
    <groupId>com.insuremo.appframework</groupId>
    <artifactId>insuremo-maven-parent-ext</artifactId>
    <version>2.0.13</version> <!-- may be changed due to AppFramework's speciality -->
</parent>

<!-- update the vela.all.version -->
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <vela.all.version>25.02.295</vela.all.version> <!-- may be changed due to AppFramework's speciality -->
</properties>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.ebao.vela</groupId>
            <artifactId>vela-all-dependency</artifactId>
            <version>${vela.all.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>

        <!-- other dependencies -->
    </dependencies>
</dependencyManagement>
```

## Changes in Maven pom.xml

### Specify Java Language Level to 17

If you have the following properties, change the value of Java language level to 17, or just remove it and inherit from the app framework.

```java
<java.version>17</java.version>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<compile.version>17</compile.version>
```

### Change javax Artifacts to jakarta

Search the following keywords in `pom.xml` and change `javax` to `jakarta`:

- javax.activation
- javax.annotation
- javax.jms
- javax.mail
- javax.servlet
- javax.persistence
- javax.validation
- javax.inject
- javax.transaction
- javax.websocket
- javax.xml.bind
- javax.ws

### Change Common Maven Artifacts

- Change sleuth to micrometer
  
  Search `sleuth` in `pom.xml`, and make changes as follows:

```java
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-sleuth-api</artifactId>
</dependency>

// to
<dependency>
    <groupId>io.micrometer</groupId>
    <artifactId>micrometer-tracing</artifactId>
</dependency>
```

- Change groupId of hibernate

  Search `org.hibernate` in `pom.xml`. Change groupId of `org.hibernate` to `org.hibernate.orm`.

```java
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
</dependency>

// to
<dependency>
    <groupId>org.hibernate.orm</groupId>
    <artifactId>hibernate-core</artifactId>
</dependency>

// remove below artifact 
<dependency>
 <groupId>org.hibernate</groupId>
 <artifactId>hibernate-entitymanager</artifactId>
</dependency>
```

- Add classifier for ehcache

```java
// add classifier
<dependency>
    <groupId>org.ehcache</groupId>
    <artifactId>ehcache</artifactId>
    <classifier>jakarta</classifier>
</dependency>
```

- MySQL artifact

```java
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
</dependency>

// to 
<dependency>
  <groupId>com.mysql</groupId>
  <artifactId>mysql-connector-j</artifactId>
</dependency>
```

- Jackson

```java
<dependency>
 <groupId>com.fasterxml.jackson.jaxrs</groupId>
 <artifactId>jackson-jaxrs-json-provider</artifactId>
</dependency>

// to 

<dependency>
 <groupId>com.fasterxml.jackson.jakarta.rs</groupId>
 <artifactId>jackson-jakarta-rs-json-provider</artifactId>
</dependency>
```

- Groovy

  Search `org.codehaus.groovy` in `pom.xml`. Change groupId of `org.codehaus.groovy` to `org.apache.groovy`.

```java
<dependency>
    <groupId>org.codehaus.groovy</groupId>
    <artifactId>groovy</artifactId>
</dependency>

// to 

<dependency>
    <groupId>org.apache.groovy</groupId>
    <artifactId>groovy</artifactId>
</dependency>
```

- Remove spring-cloud

  Search `spring-cloud` in `pom.xml`. Remove the spring-cloud related artifacts except the following:

  <div class="docs-note"><span class="docs-admonitions-text">note</span>
  
  The following are needed for feign but can be dependent from the app framework. So, do not exclude them in maven `pom.xml`.
  
  </div>
  - spring-cloud-starter-openfeign
  - spring-cloud-starter
  - spring-cloud-openfeign-core
  - spring-cloud-commons
  - spring-cloud-context

### Update Third Party Artifacts Version

Step 1:  Remove the third party artifacts version.

<div class="docs-note"><span class="docs-admonitions-text">note</span>

This step is to avoid incompatibility. Either the artifacts version can inherit from the app framework, or you will face issues and need to manually specify the version after checking the compatibility with JDK 17.

</div>

Search `</version>` in `pom.xml`, and go through listed artifacts. If there is any third party artifact, please remove the version.

Step 2:  Fix third party artifact dependency issues.

Iterate the following action items until all maven dependency issues are resolved:

1. Reload the maven projects to make maven refresh the dependencies.
2. You may face issues that artifacts – whose versions are unknown – cannot be downloaded.
3. Search and determine the corresponding version which supports JDK 17. Update it in maven `pom.xml`.
4. Try the #1 again.

## Changes in Configuration Files

### Migrate

Migrate `bootstrap.properties` to `application.properties`.

Move the configuration properties in `boostrap.properties` to `application.properties`, then remove the ~~bootstrap.properties~~.

<div class="docs-note"><span class="docs-admonitions-text">note</span>

The `bootstrap.properties` is for spring cloud, and spring cloud is removed in the latest app framework. Also, service routing has been switched to k8s (local development is based on the URL rewrite approach).

</div>

During the migration process, you can also remove legacy configurations. The following are important configurations needed to be moved into the `application.properties`:

```java
server.port=${SERVER_PORT:80}
spring.application.name=appframework-bff-app
ebao.tenant.code=${TENANT_CODE:ebaogi}
ebao.config.center.profile=${ebao.tenant.code}
```

### Search

Search `spring.cloud` in configuration properties and remove.

This action is to avoid issues of spring cloud (dependent on the Spring Feign) caused by incorrect settings.

<div class="docs-note"><span class="docs-admonitions-text">note</span>

The following properties are required for feign, and have been declared in the app framework. Don’t declare them in your service again.

</div>

```java
-Dspring.cloud.refresh.enabled=false
-Dmanagement.health.refresh.enabled=false
```

### Move EnableAutoConfiguration

Move `EnableAutoConfiguration` from `spring.factories` into the dedicated imports file.

If you have created your own auto-configurations, you should move the registration from `spring.factories` under the `org.springframework.boot.autoconfigure.EnableAutoConfiguration` key, to a new file named `META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports`. Rather than a single comma-separate list, each line contains the fully qualified name of an auto-configuration class.

<div class="docs-note"><span class="docs-admonitions-text">note</span>

 Other entries in `spring.factories` under other keys are unaffected.

</div>

**Example**:

```java
// from: resources/META-INF/spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.ebao.unicorn.platform.context.ContextApiAutoConfig,\
  com.ebao.unicorn.platform.message.PubMessageApiAutoConfig,\
  com.ebao.unicorn.platform.dsl.PubDslScriptApiAutoConfig,\
  com.ebao.unicorn.platform.snippet.PubConfigSnippetApiAutoConfig

// to: resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports

com.ebao.unicorn.platform.context.ContextApiAutoConfig
com.ebao.unicorn.platform.message.PubMessageApiAutoConfig
com.ebao.unicorn.platform.dsl.PubDslScriptApiAutoConfig
com.ebao.unicorn.platform.snippet.PubConfigSnippetApiAutoConfig
```

## Changes in Code

### Change javax to jakarta

Search the following keywords in Java/Groovy code, change `javax` to `jakarta`:

- javax.activation
- javax.annotation
- javax.jms
- javax.mail
- javax.servlet
- javax.persistence
- javax.validation
- javax.inject
- javax.transaction
- javax.websocket
- javax.xml.bind
- javax.ws

### Spring Batch

Some interfaces have been changed in spring batch, and you can simply update your code to adapt the new version:

```java
// ItemWriter

public void write(List<? extends T> list)

// to 

public void write(Chunk<? extends T> list)
```

#### Bean declaration of batch job

```java
@Autowired
private JobBuilderFactory jobBuilderFactory;
@Autowired
private StepBuilderFactory stepBuilderFactory;

@Bean
public Step ruleTrackingDeleteExpiredDataStep() {
    return stepBuilderFactory.get("ruleTrackingDeleteExpiredDataStep")
            .tasklet(ruleTrackingDeleteExpiredDataTasklet())
            .build();
}

@Bean
public Job ruleTrackingDeleteExpiredDataJob() {
    return jobBuilderFactory.get("ruleTrackingDeleteExpiredDataJob")
            .start(ruleTrackingDeleteExpiredDataStep())
            .build();
}

// to

@Autowired
private JobRepository jobRepository;
@Autowired
@Qualifier("batchTransactionManager")
private PlatformTransactionManager batchTransactionManager;

@Bean
public Step ruleTrackingDeleteExpiredDataStep() {
    return new StepBuilder("ruleTrackingDeleteExpiredDataStep", jobRepository)
            .tasklet(ruleTrackingDeleteExpiredDataTasklet(), batchTransactionManager)
            .build();
}

@Bean
public Job ruleTrackingDeleteExpiredDataJob() {
    return new JobBuilder("ruleTrackingDeleteExpiredDataJob", jobRepository)
            .start(ruleTrackingDeleteExpiredDataStep())
            .build();
}
```

Another example:

```java
// from
@Configuration
public class AgentESSyncJobConfig {

    @Resource(name="taskExecutor")
    public ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Bean
    public Job agentESSyncJob(JobBuilderFactory jobBuilderFactory, @Qualifier("agentESSyncStep") Step agentESSyncStep) {
        return jobBuilderFactory.get("agentESSyncJob")
                .start(agentESSyncStep)
                .build();
    }

    @Bean
    public Step agentESSyncStep(StepBuilderFactory stepBuilderFactory, AgentESSyncWriter syncWriter) {
        return stepBuilderFactory.get("agentESSyncStep")
                .<Agent, Agent>chunk(100)
                .reader(agentReader(null))
                .writer(syncWriter)
                .faultTolerant()
                .skip(Exception.class)
                .skipLimit(1000)
                .taskExecutor(threadPoolTaskExecutor)
                .build();
    }
    ...
}
// to 
@Configuration
public class AgentESSyncJobConfig {

    @Autowired
    private JobRepository jobRepository;

    @Autowired
    private PlatformTransactionManager batchTransactionManager;

    @Resource(name="taskExecutor")
    public ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Bean
    public Job agentESSyncJob(@Qualifier("agentESSyncStep") Step agentESSyncStep) {
        return new JobBuilder("agentESSyncJob", jobRepository)
                .start(agentESSyncStep)
                .build();
    }

    @Bean
    public Step agentESSyncStep(AgentESSyncWriter syncWriter) {
        return new StepBuilder("agentESSyncStep", jobRepository)
                .<Agent, Agent>chunk(100, batchTransactionManager)
                .reader(agentReader(null))
                .writer(syncWriter)
                .faultTolerant()
                .skip(Exception.class)
                .skipLimit(1000)
                .taskExecutor(threadPoolTaskExecutor)
                .transactionManager(batchTransactionManager)
                .build();
    }
    ...
}
```

#### @EnableBatchProcessing removed

```java
// from
@Configuration
@EnableBatchProcessing
public class AgentESSyncJobConfig {
    ...
}
// to 
@Configuration
public class AgentESSyncJobConfig {
    ...
}
```

### Trace

You may have code to customize trace programmatically, and then you need to update for Micrometer tracing:

```java
import org.springframework.cloud.sleuth.Tracer;
// to
import io.micrometer.tracing.Tracer;

import brave.Span;
import brave.Tracer;
// to
import io.micrometer.tracing.Span;
import io.micrometer.tracing.Tracer;

@Autowired
private Tracer tracer;

// Example: start a new span for the request
// You can set the spanName as per requirement
String spanName = request.httpMethod().name() + " " + request.url();
Span span = TracingContextUtils.startClientSpan(tracer, spanName); // start a new span in current context 
try (Tracer.SpanInScope scope = tracer.withSpan(span)) { // ensure the trace span in scope
    try {
        // Add any necessary attributes to the span
        span.tag("http.method",request.httpMethod().name());
        span.tag("http.url",request.url());

        Map<String, Collection<String>> headers = new HashMap<>(request.headers());
        headers.putIfAbsent(RequestHeaderConstant.X_B3_TRACE_ID, Collections.singletonList(span.context().traceId()));
        headers.putIfAbsent(RequestHeaderConstant.X_B3_SPAN_ID, Collections.singletonList(span.context().spanId()));
        headers.putIfAbsent(RequestHeaderConstant.X_B3_PARENTSPAN_ID, Collections.singletonList(span.context().parentId()));

        request = Request.create(request.httpMethod(),
                request.url(), headers,
                request.body(),
                request.charset(),
                request.requestTemplate());

        // Execute the request
        return delegate.execute(request, options);
    } catch (Exception e) {
        if (span != null) {
            span.tag("error", "true");
        }
        throw new RuntimeException(e);
    } finally {
        if (span != null) {
            span.end(); // End the span
        }
    }
}

// Inside the vela-trace-support, there is TracingContextUtils provided for tracing

// Example1: bind trace into context for http request inbound, please refer to the TracingWebListener
TraceContext traceContext = TracingContextUtils.bindTraceContext(tracer, request.getHeader(RequestHeaderConstant.X_B3_TRACE_ID), request.getHeader(RequestHeaderConstant.X_B3_SPAN_ID));

String spanName = request.getMethod() + " " + request.getRequestURI();
Span span = TracingContextUtils.startServerSpan(tracer, traceContext, spanName);
Tracer.SpanInScope spanInScope = tracer.withSpan(span);
// ... logics

// End span and close scope
Span span = (Span) request.getAttribute(SpanCustomizer.class.getName());
if (span != null) {
    span.end();
}

Tracer.SpanInScope spanInScope = (Tracer.SpanInScope) request.getAttribute(Tracer.SpanInScope.class.getName());
if (spanInScope != null) {
    spanInScope.close();
}

// Example2: start new server span in new trace
Span span = TracingContextUtils.startServerSpanInNewContext(tracer, spanName);
Tracer.SpanInScope spanInScope = tracer.withSpan(span);
// ... logics

// End span and close scope
if (span != null) {
    span.end();
}
if (spanInScope != null) {
    spanInScope.close();
}

// Example3: start new server span in existing trace
Span span = TracingContextUtils.startServerSpan(tracer, spanName);
Tracer.SpanInScope spanInScope = tracer.withSpan(span);
// ... logics

// End span and close scope
if (span != null) {
    span.end();
}
if (spanInScope != null) {
    spanInScope.close();
}

// Example3: start new client span in existing trace
Span span = TracingContextUtils.startClientSpan(tracer, spanName);
Tracer.SpanInScope spanInScope = tracer.withSpan(span);
// ... logics

// End span and close scope
if (span != null) {
    span.end();
}
if (spanInScope != null) {
    spanInScope.close();
}


```

Trace ability has been injected in following places:

- Inbound http requests: com.ebao.unicorn.platform.trace.enhance.TracingWebListener
- Feign Client: com.ebao.unicorn.platform.trace.enhance.TracingFeignClient
- RestTemplate: com.ebao.unicorn.platform.trace.enhance.TracingRestTemplateInterceptor
- TaskDecorator: com.ebao.unicorn.platform.trace.enhance.TracingTaskDecorator

### Don't use the @AutoConfiguration annotation

A new `@AutoConfiguration` annotation has been introduced as a replacement for for `@Configuration`.

But don't use (or use it carefully) the `@AutoConfiguration` annotation, it sets proxyBeanMethods = false, this will cause injection issue in below cases:

```java
@AutoConfiguration
public class MyAutoConfiguration {

    @Bean
    public MyService myService() {
        return new MyService();
    }
}


public class MyService {

    @Autowired
    private OtherService otherService; // this bean cannot be injected
}

```

### FeignClient

Because the spring cloud is removed, the URL is required. If your FeignClient has URL property, you can skip this step.

<div class="docs-note"><span class="docs-admonitions-text">note</span>

You can combine the original name (used as the service in spring cloud) with the path, and set the value as URL.

</div>

```java
@FeignClient(name = "${dd.app.name}", path = "/datatable/client/management", primary = false)

// to 
@FeignClient(name = "platform", url = "${dd.app.name}/datatable/client/management", primary = false)
```

If you want to customize FeignClientConfiguration, please refer to below example:

```java
// Please DO NOT put @Configuration annotation here, otherwise, feign client configuration would be mixed.
public class CustomFeignConfiguration {

    private static final Logger LOGGER = LoggerFactory.getLogger(CustomFeignConfiguration.class);

    @Bean
    public Decoder customFeignDecoder(ObjectFactory<HttpMessageConverters> messageConverters) {
        return new ResponseEntityDecoder(new SpringDecoder(messageConverters));
    }

    @Bean
    public FeignClientConfigurer feignClientConfigurer() {
        return new FeignClientConfigurer() {
            @Override
            public boolean inheritParentConfiguration() {
                // don't inherit default configuration
                return false;
            }
        };
    }

    @Bean
    FeignBuilderCustomizer customFeignBuilderCustomizer() {
        return builder -> {
            builder.requestInterceptors(new ArrayList<>()); // clear all request interceptors
        };
    }
}

// specify it in FeignClient

@FeignClient(name = "platform", url = "http://url/api", configuration = CustomFeignConfiguration.class)

```

### TaskExecutor

The app framework has built-in `ThreadPoolTaskExecutor`, and you can just keep using it as it is, by annotate with `@Async("taskExecutor")` on your method. In case for some reason you need to create `ThreadPoolTaskExecutor` in your service, please see the following code snippet to set the `TaskDecorator`. It will add context propagation for tracing and app user/tenant.

```java

// Composite task decorator for tracing & app context/tenant
@Bean("your-bean-name")
public ThreadPoolTaskExecutor serviceTaskExecutor(@Qualifier("taskDecorator") TaskDecorator taskDecorator) {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    //... setup the executor
    executor.setTaskDecorator(taskDecorator);
    executor.initialize();
    
    return executor;
}

// If you only need tracing decorator, please refer to below code snippets
// tracing task decorator
@Autowired
@Qualifier("tracingTaskDecorator")
private TaskDecorator tracingTaskDecorator;

ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//... setup the executor
executor.setTaskDecorator(tracingTaskDecorator);
executor.initialize();
```

### ScheduledExecutorService

If you need add tracing context propagation for `ScheduledExectorService`, please see the following code snippets.

```java
@Autowired
@Qualifier("tracingTaskDecorator")
private TaskDecorator tracingTaskDecorator;

@Autowired
private ContextSnapshotFactory contextSnapshotFactory;

// existing code to create ScheduledExecutorService
ScheduledExecutorService delegate = Executors.newScheduledThreadPool(1,
                new ThreadFactoryBuilder().setNameFormat("DeploySchedule-%d").build());

// with tracing propagation
ScheduledExecutorService  scheduler = ContextScheduledExecutorService.wrap(delegate, () -> contextSnapshotFactory.captureAll());

ThreadPoolTaskExecutor deployExecutor = new ThreadPoolTaskExecutor();
// ...
deployExecutor.setTaskDecorator(tracingTaskDecorator);
// ...

```

See the code change examples as follows:

- Before

    ```java
    ExecutorService delegate = Executors.newScheduledThreadPool(1,
                    new ThreadFactoryBuilder().setNameFormat("DeploySchedule-%d").build());

    TraceableScheduledExecutorService scheduler = new TraceableScheduledExecutorService(applicationContext, delegate);

    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    // ...

    LazyTraceThreadPoolTaskExecutor deployExecutor =  new LazyTraceThreadPoolTaskExecutor(applicationContext,executor);

    ```

- After

    ```java
    ScheduledExecutorService delegate = Executors.newScheduledThreadPool(1,
                    new ThreadFactoryBuilder().setNameFormat("DeploySchedule-%d").build());

    ScheduledExecutorService scheduler = ContextScheduledExecutorService.wrap(delegate, () -> contextSnapshotFactory.captureAll());

    ThreadPoolTaskExecutor deployExecutor = new ThreadPoolTaskExecutor();
    // ...
    deployExecutor.setTaskDecorator(tracingTaskDecorator);
    // ...

    ```

### Hibernate

#### Count

In Hibernate 6, it is no longer possible to reuse objects across different CriteriaQueries.

You may face the following issue.

Already registered a copy: `SqmBasicValuedSimplePath(com.ebao.unicorn.platform.data.code.domain.BusinessDataTable(34298849899580022).name`

The issue arises because you use expressions in a count query, but the paths upon which the expressions are based are from a different query.

See the following links:

- [Already Registered A Copy](https://discourse.hibernate.org/t/java-lang-illegalargumentexception-already-registered-a-copy-sqmbasicvaluedsimplepath/8485/4)

- [Support Creating Count Query from Existing Query](https://hibernate.atlassian.net/browse/HHH-17410)

You can simply call `query.createCountQuery()` to create count query.

```java
TypedQuery<Long> countQuery = getEntityManager().createQuery(((JpaCriteriaQuery<?>)criteria).createCountQuery());
Long count = countQuery.getSingleResult();
```

<div class="docs-note"><span class="docs-admonitions-text">note</span>

You can also use the app framework build-in utilities `com.ebao.unicorn.platform.data.helper.StaticDataHelper.getTotalCounts(EntityManager em, final CriteriaQuery<?> criteria, final Root<?> root, Class<?> clazz)`.

</div>

#### Hibernate query of type matching

- Exception stack

    ```java
    Caused by: java.lang.IllegalArgumentException: org.hibernate.query.SemanticException: Cannot compare left expression of type 'java.lang.String' with right expression of type 'java.lang.Integer'
        at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:143)
        at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:167)
        at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:173)
    ```

- Query

    ```java
    sql.append(" from Role where tempFlag = 0 and status <> 3 ");
    ```

- Declare entity

    ```java
    @Column(name ="TEMP_FLAG")
    private String tempFlag=null;

    @Column(name ="STATUS")
    private String status=null;

    @Column(name ="ROLE_GROUP_TYPE")
    private String roleGroupType=null;
    ```

- Fix and change the query

    ```java
    sql.append(" from Role where tempFlag = '0' and status <> '3' ");
    ```

#### Hibernate @BatchSize annotation validation

In hibernate 6, there is validation logic that will block the application startup if you apply the @BatchSize annotation on non-collection field.

#### JPA Entity Column annotation removed scale

```java
// from
    @Column(name = "CASH_COST", precision = 18, scale = 3)
    private BigDecimal cashCost = new java.math.BigDecimal(0);
// to
    @Column(name = "CASH_COST", precision = 18)
    private BigDecimal cashCost = BigDecimal.valueOf(0);
```

#### Predicate.getExpressions() removed

```java
// from
        Specification<PolicyChange> specification = (root, query, cb) -> {
            Join<PolicyChange, CsApplication> join = root.join("csApplication");
            Predicate predicate = cb.conjunction();
            List<Expression<Boolean>> exprList = predicate.getExpressions();
            //change id
            exprList.add(cb.equal(join.get("changeId").as(Long.class), changeId));
            //policy change completed/inforce
            CriteriaBuilder.In<Integer> policyChgStatusInCause = cb.in(root.get("policyChgStatus"));
            policyChgStatusInCause.value(PolicyChangeStatus.COMPLETED);
            policyChgStatusInCause.value(PolicyChangeStatus.IN_FORCE);
            exprList.add(policyChgStatusInCause);
            return predicate;
        };
// to 
        Specification<PolicyChange> specification = (root, query, cb) -> {
            Join<PolicyChange, CsApplication> join = root.join("csApplication");
            List<Predicate> exprList = new ArrayList<>();
            //change id
            exprList.add(cb.equal(join.get("changeId").as(Long.class), changeId));
            //policy change completed/inforce
            CriteriaBuilder.In<Integer> policyChgStatusInCause = cb.in(root.get("policyChgStatus"));
            policyChgStatusInCause.value(PolicyChangeStatus.COMPLETED);
            policyChgStatusInCause.value(PolicyChangeStatus.IN_FORCE);
            exprList.add(policyChgStatusInCause);
            return cb.and(exprList.toArray(new Predicate[0]));
        };
```

## Build and Deploy

### Jenkins Build Configuration Properties

Update Jenkinsfile as follows：

```java
export JAVA_HOME="/home/tools/openlogic-openjdk-17.0.10+7-linux-x64"
```

Update properties.json as follows：

```java
"build_jdk" : "openjdk17.0.10"
```

### Dockerfile

You need to update the base image of OpenJDK.

```java
FROM docker-all.repo.ebaotech.com/base/openjdk:11.0.24

// to 
FROM docker-all.repo.ebaotech.com/base/openjdk:17.0.15
```

### Update in Jenkins or Build Tool for JDK17

You may need to contact with your CM to adjust the build configuration to support JDK17.

## Troubleshooting

### Tomcat access log latency unit is not MS(milliseconds)

In this upgrade, the tomcat is also upgraded from 9 to 10, the %D is changed from milliseconds to microsdeconds (behavior in httpd).

Solution:

```java
// tomcat <= 9
"latency":"%D" 

// tomcat >= 10
"latency":"%{ms}T" 

```

### Error in Java Lang Reflect

```java
// error
module java.base does not "opens java.lang.reflect" to unnamed module

// add java options
--add-opens java.base/java.lang=ALL-UNNAMED
--add-opens java.base/java.io=ALL-UNNAMED
--add-opens java.base/java.lang.reflect=ALL-UNNAMED
--add-opens java.base/java.time=ALL-UNNAMED
--add-opens java.base/java.util=ALL-UNNAMED
--add-opens java.base/java.nio=ALL-UNNAMED
--add-opens java.sql/java.sql=ALL-UNNAMED
--add-opens java.base/java.math=ALL-UNNAMED
--add-opens java.base/java.net=ALL-UNNAMED
--add-opens java.base/java.util.concurrent=ALL-UNNAMED
--add-opens java.base/sun.nio.ch=ALL-UNNAMED
--add-opens java.base/sun.net.www.protocol.http=ALL-UNNAMED
--add-opens java.xml/com.sun.org.apache.xerces.internal.parsers=ALL-UNNAMED
--add-opens jdk.unsupported/sun.misc=ALL-UNNAMED
```

### No such host is known

In your local development env, you can disable the tracing collector by setting below configure either in application-local.properties or in VM options:

```java
otel.tracing.enabled=false
```

### Don't wont to connect to RabbitMQ

In your local development env, if you're not using RabbitMQ for application message, you can disable the RabbitMQ auto-configuration by setting below configure either in application-local.properties or in VM options:

```java
mq.disabled=true
```