您的位置:首頁技術文章
文章詳情頁

java - spring boot 集成mybatis 注解版查詢

瀏覽:106日期:2023-10-25 15:45:46

問題描述

-spring boot 集成 mybatis 使用注解實現 spring boot 和 mybatis已經正常集成,在使用查詢時使用的是注解,(項目沒有任何XML文件)

@Mapper@Table(name = 't_user')public interface UserMapper { @Select('select * from t_user where user_id = #{id}') public User findUserById(@Param('id') String id);}

這種方式是不知道為什么,只有幾個屬性會填充值,其他屬性查詢出來的結果都為null java - spring boot 集成mybatis 注解版查詢

但是我如果寫了

@Results({ @Result(column = 'user_id',property = 'userId'), @Result(column = 'username',property = 'username'), @Result(column = 'pass',property = 'pass'), @Result(column = 'phone_number',property = 'phoneNumber')})

就會完全正確,每個屬性都有值問題1: 為什么會出現有的屬性有值,有的屬性沒值?問題2:我不能每個查詢語句都這么寫,這樣會有很多的重復的@Result部分,有沒有注解將其在內部進行對應關系實現,不需要每次都寫@ Result?

問題解答

回答1:

問題1. 因為結果集的column和Bean的property不對應,當然就會null.

問題2. 你可以在sql中用別名,使得column和property對應,這樣就不會出現問題1.

回答2:

問題一的話,因為數據庫字段是你下劃線分隔,bean中的字段是駝峰命名的,如user_name和userName,導致無法匹配

如果是通過xml文件來配置的話,只需要開啟駝峰命名轉換

<setting name='mapUnderscoreToCamelCase' value='true'/>

yml中 大概是這樣

mybatis: configuration: map-underscore-to-camel-case: true

標簽: java
相關文章:
国产综合久久一区二区三区