Spring Boot 的簡單教程(四)數據庫連接之Mybatis的使用

Mybatis的使用

MyBatis 是一款優秀的持久層框架,它支持定製化 SQL、存儲過程以及高級映射。MyBatis 避免了幾乎所有的 JDBC 代碼和手動設置參數以及獲取結果集。MyBatis 可以使用簡單的 XML 或註解來配置和映射原生信息,將接口和 Java 的POJOs(Plain Old Java Objects,普通的 Java對象)映射成數據庫中的記錄。

怎麼在Spring Boot裏面使用Mybatis呢?就繼續看吧。

第一,在pom.xml裏面導入配置文件。

    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>1.1.1</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>

第二,添加相關配置 application.yml。

    #配置數據源
    spring:
      datasource:
      #這裏可以不寫,會根據url自動判斷,如果mybatis裏面配置了version那麼這裏寫了就會報錯。
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://localhost:3306/springboot
        username: root
        password: password
    
    #這是在控制檯打印mybatis的sql語句
    logging:
      level:
        com:
          springboot:       
            mybatis:
              mepper: debug   #這是mapper放置的地址。
    #開啓駝峯命名法,這樣後面的開發Mapper就可以省掉@Results的註解,當然,不是駝峯命名法的還是不能省略。
    mybatis:
      configuration:
        map-underscore-to-camel-case: true

第三,在啓動類中添加對mapper包掃描@MapperScan。

    @SpringBootApplication
    @MapperScan("com.springboot.mybatis.mapper")    //mapper文件的存放地址
    public class Application {
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    }

第四,開發Mapper就可以了。

public interface GirlMapper {

    //這裏沒有使用@Results註解,是因爲前面在application.yml已經進行相關配置了。
    @Select("select * from girl")
    @Results({
        @Result(column="cup_size", property="cupSize", jdbcType=JdbcType.VARCHAR)
    })
    List<Girl> findAll();

    @Select("select * from girl where id = #{id}")
    Girl findOne(Integer id);

}
@Select 是查詢類的註解,所有的查詢均使用這個
@Result修飾返回的結果集,關聯實體類屬性和數據庫字段一一對應,如果實體類屬性和數據庫屬性名保持一致,就不需要這個屬性來修飾。
@Insert插入數據庫使用,直接傳入實體類會自動解析屬性到對應的值
@Update 負責修改,也可以直接傳入對象
@delete 負責刪除

第五,使用就可以了。

//如果想使用@RestController和@RequestMapping就必須在pom.xml裏面導入WEB支持(spring-boot-starter-web)
@RestController
public class GirlController {

    //注入GirlMapper
    @Autowired
    GirlMapper girlMapper;

    @RequestMapping("/girls")
    public List<Girl> findAll(){
        return girlMapper.findAll();
    }

    @RequestMapping("/girl/{id}")
    public Girl findOne(@PathVariable("id") Integer id){
        return girlMapper.findOne(id);
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章