1、引入依赖
pom.xml:
<!--引入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.、配置数据库
application.properties:
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
3、Mybatis文本:
UserMapper.xml:
<?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>
4、App启动类
App.class:
@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..." ); } }
5、interface
UserMapper.class
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); }
注意:
1、如果接口文件名UserMapper和配置文件名UserMapper.xml名称不同时,会出现
org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.springboot.mapper.UserMapper.getUserList
2、@MapperScan配置成com.springboot.*,会出现以下异常:
org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.springboot.service.userService.getUserList
3、接口和配置文件在同一个文件夹下且名称一致