Spring Boot學習總結三
阿新 • • 發佈:2018-11-01
() 無配置文件 select 就會 配置文件 配置 模式 mysq pre
1,mybatis在spring boot下的2種使用模式
無配置文件註解版
application.properties添加相關配置
mybatis.type-aliases-package=com.neo.entity spring.datasource.driverClassName = com.mysql.jdbc.Driver spring.datasource.url = jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8 spring.datasource.username = root spring.datasource.password = root
springboot會自動加載spring.datasource.*相關配置,數據源就會自動註入到sqlSessionFactory中,sqlSessionFactory會自動註入到Mapper中,對了你一切都不用管了,直接拿起來使用就行了。
在啟動類中添加對mapper包掃描@MapperScan
@SpringBootApplication @MapperScan("com.neo.mapper") public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
或者直接在Mapper類上面添加註解@Mapper,建議使用上面那種,不然每個mapper加個註解也挺麻煩的
開發Mapper,第三步是最關鍵的一塊,sql生產都在這裏
public interface UserMapper { @Select("SELECT * FROM users") @Results({ @Result(property = "userSex", column = "user_sex", javaType = UserSexEnum.class), @Result(property = "nickName", column = "nick_name") }) List<UserEntity> getAll(); @Select("SELECT * FROM users WHERE id = #{id}") @Results({ @Result(property = "userSex", column = "user_sex", javaType = UserSexEnum.class), @Result(property = "nickName", column = "nick_name") }) UserEntity getOne(Long id); @Insert("INSERT INTO users(userName,passWord,user_sex) VALUES(#{userName}, #{passWord}, #{userSex})") void insert(UserEntity user); @Update("UPDATE users SET userName=#{userName},nick_name=#{nickName} WHERE id =#{id}") void update(UserEntity user); @Delete("DELETE FROM users WHERE id =#{id}") void delete(Long id); }
Spring Boot學習總結三