一、引入依賴java
pom.xml:mysql
<!--引入mybatis依賴(使用mybatis時配置)--> <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> 。。。。。。 <!-- maven項目中src源代碼下的xml等資源文件編譯進classes文件夾, 注意:若是沒有這個,它會自動搜索resources下是否有mapper.xml文件, 若是沒有就會報org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.pet.mapper.PetMapper.selectByPrimaryKey--> <build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> </resources> </build>
2.、配置數據庫spring
application.properties:sql
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mysql-boot
spring.datasource.username=root
spring.datasource.password=123123
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
三、Mybatis文本:數據庫
UserMapper.xml:apache
<?xml version="1.0" encoding="utf-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <!--在MyBatis中,Mapper中的namespace用於綁定Dao接口的,即面向接口編程。 它的好處在於當使用了namespace以後就能夠不用寫接口實現類,業務邏輯會直接經過這個綁定尋找到相對應的SQL語句進行對應的數據處理--> <mapper namespace="com.springboot.mapper.UserMapper"> <select id="getUserList" parameterType="com.springboot.model.User" resultType="com.springboot.model.User"> select id,name,passWord from tb_user where 1=1 order by ranking asc </select> <select id="getUserInfo" parameterType="string" resultType="com.springboot.model.User"> select id,name,passWord from tb_user where id=#{id} </select> </mapper>
四、App啓動類編程
App.class:springboot
@EnableAutoConfiguration @MapperScan(basePackages = {"com.springboot.mapper"})//注意:@MapperScan配置成com.springboot.*,會出現如下異常: //org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.springboot.service.userService.getUserList @ComponentScan(basePackages = {"com.springboot.*","com.springboot.*.*"})//組件掃描,配置掃描的包 public class App { public static void main( String[] args ) { System.out.println( "Hello World!" ); //啓動springboot項目 SpringApplication.run(App.class,args); System.out.println( "success..." ); } }
五、interfacemybatis
UserMapper.classapp
package com.springboot.mapper; import com.springboot.model.User; import java.util.List; public interface UserMapper { public List<User> getUserList(User user); public User getUserInfo(String id); }
注意:
一、若是接口文件名UserMapper和配置文件名UserMapper.xml名稱不一樣時,會出現
org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.springboot.mapper.UserMapper.getUserList
二、@MapperScan配置成com.springboot.*,會出現如下異常:
org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.springboot.service.userService.getUserList
三、接口和配置文件在同一個文件夾下且名稱一致