SpringBoot項目中遇到的BUG


1.啟動項目的時候報錯

1.Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled. 

解決方法:

在yml配置文件中加入debug: true,因為默認的話是false

2.在集成mybatis時mapper包中的類沒被掃描

org.springframework.beans.factory.NoSuchBeanDefinitionException:
 No qualifying bean of type 'com.app.mapper.UserMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {} 

解決方法:

在springboot的啟動類中加入@MapperScan("mapper類的路徑")
或者直接在Mapper類上面添加注解@Mapper,建議使用上面那種,不然每個mapper加個注解也挺麻煩的

3.在向數據庫插入數據時報錯

"\r\n### Error updating database.  Cause: 
com.mysql.jdbc.MysqlDataTruncation: 
Data truncation: Data too long for column 'password' at row 1\r\n###

數據庫表password這個字段太短了,應該設長點

java.lang.ClassCastException: com.app.entity.User cannot be cast to java.lang.Integer 

4.用mybatis查詢時報錯

org.mybatis.spring.MyBatisSystemException: 
nested exception is org.apache.ibatis.binding.BindingException: Parameter 'user_type' not found. Available parameters are [2, 1, 0, param1, param2, param3] 
原因:@Param注解缺失,當只有一個參數時,Mapper接口中可以不使用
public User getUser(String name); 

有多個參數時就必須使用

public User getUser(@Param("name") String name,@Param("password") String password); 

5.Mybatis查詢傳入一個字符串傳參數報錯

mapper接口:
PkRecord findByPkStudentNumber(String pkStudentNumber);
對應的mapper配置文件
<select id="findByPkStudentNumber" resultMap="recordMap" > SELECT * FROM pk_record <where> <if test="pkStudentNumber!=null"> pk_student_number=#{pkStudentNumber} </if> </where> </select> 

然后就會報如下錯誤

There is no getter for property named 'XXX' in 'class java.lang.String' 
原因:

Mybatis默認采用ONGL解析參數,所以會自動采用對象樹的形式取string.num值,引起報錯。

解決方法:

①在mapper配置文件中參數名,都要改成_parameter

<select id="findByPkStudentNumber" resultMap="recordMap" > SELECT * FROM pk_record <where> <if test="_parameter!=null"> pk_student_number=#{_parameter} </if> </where> </select> 

②在mapper接口中用@Param在相關方法說明參數值

PkRecord findByPkStudentNumber(@Param("pkStudentNumber") String pkStudentNumber); 

6.mybatis返回值報錯

org.apache.ibatis.binding.BindingException: Mapper method 'com.hoomsun.mybatis.dao.CostMapperDao.dongtaislq' has an unsupported return type: class java.lang.String 

dao接口類中對應的方法去掉返回值,用void,例如:

public void dongtaislq(Map map); 

7.mybatis中集合與Stirng類型的比較

報錯信息

invalid comparison: java.util.ArrayList and java.lang.String 
原因:無法比較這兩種類型
<if test="categoryIds!=null and categoryIds!=' ' "> AND category_id IN <foreach collection="categoryIds" item="categoryIds" open="(" separator="," close=")"> #{categoryIds} </foreach> </if> 

在接收list的時候加了判斷 list !=' ',引起了集合與Stirng類型的比較,所以報錯,將判斷條件改為 : list.size >0就可以了

<if test="categoryIds!=null and categoryIds.size>0" > AND category_id IN <foreach collection="categoryIds" item="categoryIds" open="(" separator="," close=")"> #{categoryIds} </foreach> </if> 

8.保存對象數據進數據庫后根據ID查詢並返回該對象時為null

<insert id="saveUser" useGeneratedKeys="true" keyColumn="id" > insert into user(username,password,nickname) values (#{username},#{password},#{nickname}) </insert> 

這樣寫的話數據可以保存到數據庫,沒問題,ID也可以自動增長,不過保存后立刻根據ID查詢時返回會為null
解決的方法是把keyColumn換成keyProperty就可以了

<insert id="saveUser" useGeneratedKeys="true" keyProperty="id" > insert into user(username,password,nickname) values (#{username},#{password},#{nickname}) </insert> 

9.idea運行項目時報錯

//子容器啟動失敗 ERROR 8760 --- [cat-startStop-1] org.apache.catalina.core.ContainerBase : A child container failed during start //未能啟動Tomcat組件 java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost].TomcatEmbeddedContext[]] 

這里的問題主要是jre環境沒選好,可能是由於你之前項目要求改變jre,然后導致之前的項目jre環境也改變了。

idea具有內置tomcat,所以可以不用額外配置tomcat

在idea中點擊運行→編輯結構→在配置中選擇jre環境

我這里是選用1.8的環境


 
Paste_Image.png

再次啟動項目:


 
Paste_Image.png

啟動成功了

10.mybatis插入數據時默認值不生效

插入語句

<insert id="insert" useGeneratedKeys="true" keyProperty="id"> insert into mmall_category (id, name, status) values (#{id}, #{name},#{status}) </insert> 

對應的mapper

void insert(Category category); 

需要傳入的是一個對象,假如你在數據庫設計時把status設置默認值
在傳入對象時只賦值給name,結果你可以發現數據庫中status的值是null

這是因為這個對象的其他屬性成員你不賦值的話默認為null,並且你在sql語句中#{status},也就是把null賦給了status,但是有時候有需要傳status,不能把#{status}去掉,那該怎么辦呢?
解決方法:

<insert id="insert" useGeneratedKeys="true" keyProperty="id"> insert into mmall_category (id, name <if test="status != null"> ,status </if>) values (#{id}, #{name} <if test="status != null"> ,#{status} </if>) </insert> 

使用mybatis的if test進行值的判斷,如果是null的話就不賦值

mybatis的高級結果映射

association – 一個復雜的類型關聯;許多結果將包成這種類型
嵌入結果映射 – 結果映射自身的關聯,或者參考一個

看起來挺難懂的,看下實例
在resultMap中,有這樣的一個映射

<association property="user" column="user_id" select="com.mapper.UserMapper.selectByPrimaryKey"/> 

當你用select查詢出來對象時想獲取userId的值要先獲取映射的對象再獲取其ID,不然直接獲取userId會為空

11.InterlliJ Debug方式啟動特別慢

Method breakpoints may dramatically slow down debugging

不管你是重啟服務器和重啟idea還是報這個問題。由該提示語我們可以知道要把方法斷點給關掉,查看斷點的快捷方式是Ctrl + Shift +F8

 
image.png

Java Method Breakpoints去掉即可

 

錯誤Caused by: java.lang.IllegalStateException: In the composition of all global method configuration, no annotation support was actually activated

原因:在所有全局方法配置的組合中,實際上沒有激活注釋支持

解決方法:

在啟動類中加入@EnableGlobalMethodSecurity(securedEnabled = true)

@SpringBootApplication @EnableGlobalMethodSecurity(securedEnabled = true) public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } 

12.MyBatis綁定錯誤

Invalid bound statement (not found)

這個錯誤主要是因為mapper接口與mapper.xml的路徑沒有一一對應,並且mapper.xml不能放在src目錄里,配置文件必須放resources里,src目錄下的xml文件默認不會編譯到target

13.使用請求轉發或者重定向出現異常

java.lang.IllegalStateException: Cannot forward after response has been committed

原因:

報異常的原因是重復轉發或者重定向了請求

解決方法:

如果有多個轉發或者重定向,需要在每個轉發或者重定向請求之后加上return語句(最后一個請求轉發或者重定向可以不加)

14.SpringBoot配置數據庫連接池,但日志卻每次都新建連接

Mybatis中動態打印SQL語句到控制台,只需要在SpringBoot配置文件中添加如下配置即可
mybatis: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl 

但是如果沒有用到任何連接池的話,是不會打印的

Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@2a5ca7d7] was not registered for synchronization because synchronization is not active JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@9a51d74] will not be managed by Spring Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@2a5ca7d7] 

解決方法:

確保有可用的連接池被使用,引入第三方連接池要做好配置

15.SpringBoot項目中service層互相引用

Description: The dependencies of some of the beans in the application context form a cycle: xxxController (field private aaaService xxxController.aaaService) ┌─────┐ | aaaImpl defined in file [aaaImpl.class] ↑ ↓ | bbbImpl (field private aaaService bbbImpl.orderService) └─────┘ 

解決方法:

注入方式用的是@RequiredArgsConstructor 注解final方式注入報錯
將注入方式改為@Autowired成功解決

16.SpringBoot配置文件中使用了過時的配置項

Caused by: org.springframework.boot.context.properties.bind.UnboundConfigurationPropertiesException: The elements [spring.resources.chain.gzipped] were left unbound. 

已廢棄的配置項

spring:
  resources:
      chain:
        gzipped: true 

解決方法:刪掉過期的配置項即可



作者:意識流丶
鏈接:https://www.jianshu.com/p/217017b2e73d
來源:簡書
簡書著作權歸作者所有,任何形式的轉載都請聯系作者獲得授權並注明出處。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM