Skip to main content

Java Related Problem Handling

SpringBoot startup error org.springframework.boot does not exist

It is recommended to use method 2 to enter mvn idea:idea in the terminal. Method 1 will restart the SpringBoot project when running other Main method test classes in Spring Boot projects. If you also get from ApplicationContext, you will receive an error that the container has been closed. See blog

Spring boot source code running SpringApplication error

Could not find artifact lifecycle-mapping:lifecycle-mapping:jar:sources:1.0.0 See blog - now requires payment to view! Speechless

gradle spring boot 3.0 import error

Invalid source release: 17

Ensure that the gradle version JDK 17 and JDK version are correct.

image-20230728021351697

  • Startup console log has no color

Include in spring-logback.xml

    <include resource="org/springframework/boot/logging/logback/base.xml"/>
<logger name="org.springframework.web" level="INFO"/>
<logger name="org.springboot.sample" level="TRACE"/>
  • logback modify log print content

Code: extends ThrowableHandlingConverter impl convert method

logback configuration

<conversionRule convertionWord="someKeyMsg" convertClass="com.xxx.xxx.Xclass"/>

Always use unmappedTargetPolicy Error, which can avoid many problems.

Handling Maven remote repository unable to download jar packages

First go to Maven Repository to find the corresponding dependency and download it.

Go to the download directory and execute the following command, note to replace -DgroupId, -DartifactId, -Dversion, -Dfile

mvn install:install-file -DgroupId=io.confluent -DartifactId=kafka-schema-registry-client -Dversion=4.1.0 -Dpackaging=jar  -Dfile=kafka-schema-registry-client-4.1.0.jar

Using Tomcat to start service dependency conflict issues

  1. Solution: Check error information, find conflicting classes according to prompts, locate to corresponding jar (directly search class name, including no-project items)
  2. Go to tomcat lib directory to check related jars; find jars in project imported dependencies.
  3. First determine whether the jar version matches the current project related things. If it matches, you can remove one side's jar package for testing. Generally can solve the problem

after run the packaged jar occurs this unable to find main class

Method 1. Replace plugin

<!--<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>none</mainClass> &lt;!&ndash; Cancel finding Main method in this project: to solve Unable to find main class problem &ndash;&gt;
<classifier>execute</classifier> &lt;!&ndash; To solve dependency modules cannot find classes or properties in this module &ndash;&gt;
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.0.1</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>

Method 2: Remove spring-boot parent, then use spring boot plugin to package

mvnw clean occurs Some Enforcer rules have failed.

Failed to execute goal org.apache.maven.plugins:maven-enforcer-plugin:1.4.1:enforce
(enforce-versions) on project SIMI: Some Enforcer rules have failed. Look above for
specific messages explaining why the rule failed. -> [Help 1]

not solved! stackoverflow website

To skip enforcer (not always working)

mvn clean install -Denforcer.skip=true

To continue the build if error

mvn clean install -Denforcer.fail=false
./mvnw clean install -DskipDistribution=true  -Denforcer.skip=true

SQL query null value encapsulation back to int type reports UncategorizedSQLException

Change BO property from int to Integer type

rg.springframework.jdbc.UncategorizedSQLException: SqlMapClient operation; 
uncategorized SQLException for SQL []; SQL state [null]; error code [0];

Mysql tinyint is problematic

mysql do not use field type tinyint, your updated 1 might become 49

See blog

MybatisPlus Invalid bound statement (not found) exception

See article

idea terminal Chinese garbled characters issue

Reference article

# solve idea terminal Chinese garbled
export LANG="zh_CN.UTF-8"
export LC_ALL="zh_CN.UTF-8"

mojibake chinese characters in Resttemplate

When you use Spring Boot mvc, provide a api endpoint,

maybe confront mojibake chinese characters.

It's not the problem of Spring Boot, but what the client you use.

result form is below.

server receive content-typeclient Content-Typeclient Accept-Charsetlib useworked?
application/json; charset=UTF-8application/jsoncharset=UTF-8RestTemplateYes
application/json; charset=UTF-8application/json; charset=UTF-8RestTemplateYes
application/json; charset=UTF-8application/jsoncharset=UTF-8HttpClientYes
application/json; charset=UTF-8application/json; charset=UTF-8HttpClientYes
text/plain; charset=UTF-8application/jsoncharset=UTF-8RestTemplateNo
text/plain; charset=UTF-8application/json; charset=UTF-8RestTemplateYes
text/plain; charset=UTF-8application/jsoncharset=UTF-8HttpClientYes
text/plain; charset=UTF-8application/json; charset=UTF-8HttpClientYes

finally conclusion about the form , only when you use RestTemplate, and separately set the Content-Type

and Accept-Charset, the problem will occur.

thanks for your reading.

If you have any problem, feel free to contact with me.

Others (difficult to categorize)

jasper backend, if the print template needs too many dynamic areas, the previously encapsulated framework is not enough, what to do?

At this time rewriting the framework might be too f**king annoying. Of course you can also find new versions of POI framework to see if there are corresponding extension points.

This does not discuss the content of new POI framework; adopt the solution of only modifying jasper files:

  1. The text box must be text field, not static text
  2. Write ternary expressions in the box, then check remove line when blank and blank when null
  3. Preview effect. Here is the effect of expression 1==2?"a":null

How to configure generating log files

 <!--Log file main directory: here ${user.home} is the current server user home directory-->
<property name="LOG_HOME" value="log"/>


<!--Configure log file (File)-->
<appender name="rollingFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!--Set strategy-->
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<!--Log file path: here %d{yyyyMMdd} means classify logs by day-->
<FileNamePattern>${LOG_HOME}/%d{yyyyMMdd}.%i.log</FileNamePattern>
<maxFileSize>30MB</maxFileSize>
<!--<maxHistory>100</maxHistory>-->
<!--<totalSizeCap>5GB</totalSizeCap>-->
</rollingPolicy>
<!--Set format-->
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<!--Format output: %d represents date, %thread represents thread name, %-5level: level displays 5 character width from left %msg: log message, %n is newline-->
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<!-- Or use default configuration -->
<!--<pattern>${FILE_LOG_PATTERN}</pattern>-->
<charset>utf8</charset>
</encoder>

<!--Maximum size of log file-->
<!--<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">-->
<!--<MaxFileSize>1KB</MaxFileSize>-->
<!--</triggeringPolicy>-->
</appender>
<root level="info">
<appender-ref ref="rollingFile" />
</root>

MockBean usage issues

When using MockBean, String input parameter, int return value, when the input parameter is the actual called method, thenReturn is the expected value, otherwise when passing string it is always 0;

lombok usage pitfalls

@Data annotation generated getters, setters inconsistent with jackson-databind causes object properties to have no values during deserialization.

Dynamic data source issues

If the operations used have transactions, the data source needs to be set before the Dao layer. Data source switching will be ineffective in Dao or service with dao in Mybatis-plus.

override by no-compatible bean instance of type[com.sun.Proxy.$Proxy227

Reason: JDK proxy and CGlib proxy mixed use issue

Solution: Inject interface, not a specific implementation class

netty response speed issues

When closing resources, group.shutdownGracefully().sync(), remove .sync() call will not block.

Shield logs in a certain method

Configure logging.level.com.xxx.xx, com.xxx.xx is the full class path name

Using mybatis-plus primary key auto-increment issues

select SEQUENCE_NAME.nextval from dual;
insert into xxx() values (xx.nextval, #{tssnbr, jdbcType=CHAR})

notes:

  1. Field case must be consistent
  2. Fields should specify jdbcType

Problems that may be encountered when changing boolean to Boolean

When optimizing code, when changing primitive types to wrapper types, if using Spring injection method, note that default values will change. boolean default value is false, wrapper class is null, may cause null pointer exception

boolean changed to Boolean value, some scenarios (netty not responding to requests) will have problems

Problem: boolean changed to Boolean value, some scenarios (netty not responding to requests) will have problems

Solution: Assign false value to Boolean class

@Value default value can't be present on annotations @ConditionalOnExpression or @ConditionalOnProperty.

Solution: Configure corresponding parameters in yml

Hutool ExcelUtil, write type handling

When using cn.hutool.poi.excel.ExcelUtil in Hutool, if you want to output what type to corresponding cells, you need to define corresponding content as corresponding type;

  1. Basic data types:

    • Java's int, long, float, double and other basic data types correspond to number type in Excel.
  2. String type:

    • Java's String type corresponds to text type in Excel.
  3. Date type:

    • Java's java.util.Date type usually corresponds to date type in Excel.
    • In Hutool, you can use DateTime type, which is more flexible in handling dates and times.
  4. Boolean type:

    • Java's boolean type usually corresponds to boolean type in Excel.
  5. Other special types:

    • Hutool provides some conversion methods, for example cn.hutool.core.convert.Convert.toStr(obj) can convert objects to strings, then write to Excel.

If using styles defined in templates, cell content can be used, but specific cell formats will be overridden.

If Hutool's ExcelUtil is not sufficient, please use POI's native API.

org.springframework.jdbc.UncategorizedSQLException

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.jdbc.UncategorizedSQLException: x.xx.x.insert (batch index #1) failed. Cause: java.sql.BatchUpdateException: The MySQL server is running with the --read-only option so it cannot execute this statement; uncategorized SQLException; SQL state [HY000]; error code [1290]; The MySQL server is running with the --read-only option so it cannot execute this statement; nested exception is java.sql.BatchUpdateException:

solution:

the error configuration, the url miss connect port, mislead phonomenone sometimes maybe right, sometimes occurs error above.

fetch all the data once but not paginate.

the relative code below,

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class DataMigrationService {
@Autowired
private SourceEntityMapper sourceEntityMapper;
@Autowired
private TargetEntityMapper targetEntityMapper;
public void migrateData() {
int pageSize = 100; // Adjust the page size according to your needs
int currentPage = 1;
while (true) {
// Fetch data from the source database in chunks using MyBatis Plus
List<SourceEntity> sourceEntities = sourceEntityMapper.selectPage(
new Page<>(currentPage, pageSize),
new QueryWrapper<>()
).getRecords();

if (sourceEntities.isEmpty()) {
break; // No more data to fetch
}
// Process and insert data into the target database
processAndInsertData(sourceEntities);
currentPage++;
}
}

private void processAndInsertData(List<SourceEntity> sourceEntities) {
List<TargetEntity> targetEntities = convertToTargetEntities(sourceEntities);
// Batch insert into the target database using MyBatis Plus
targetEntityMapper.insertBatchSomeColumn(targetEntities);
}



private List<TargetEntity> convertToTargetEntities(List<SourceEntity> sourceEntities) {
// Implement logic to convert SourceEntity to TargetEntity
// ...
return targetEntities;
}

}

solution:

when you want migrate the data paginate and you need config this bean.

@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.ORACLE));
return interceptor;
}

validated not work in groups

solution

  1. write check annotation in entity
  2. write @Validated(Group1.class)
  3. write @Valid before the parameter which you wanna check

Do not use one more check in one class