spring-boot接入mybatis

mybatis接入spring-boot

开发环境为idea,spring-boot项目,前期的准备就跳过了

pom.xml配置

    org.mybatis.spring.boot
    mybatis-spring-boot-starter
    1.3.0

首先是注解方式
application.yml配置

此处已配置完数据库

spring:
  profiles:
    active: dev
  datasource:
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/test
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
首先注册dao的接口

首先贴出bean

@Entity
public class Person {
    @Id
    @GeneratedValue
    private int id;
    private String name;
    @Min(value=10,message = "too young")
    private int age;
    public Person(){

    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

接下来是dao类

@Component
@Mapper
public interface PersonAnnotationDao {
    @Select("SELECT * FROM person")
    List findAll();
}

这里只是简单的做了一个查询方法

最后我们进行junit test

具体的spring 单元测试请自行搜索

   @Autowired
    private PersonAnnotationDao personAnnotationDao;


    @Test
    public void testMyBatisFindAllPersons() {
        Assert.assertEquals(1, personMapper.findAllPersons().size());
    }

这里可以调试调取具体的数据

接下来看看xml方式的调用
application.yml配置

此处已配置完数据库

mybatis:
mapper-locations: classpath:mybatis/mapper/*.xml
type-aliases-package: com.leo.domain
config-location: classpath:mybatis/mybatis-config.xml

注意路径resources的子目录为第一级目录

配置mybatis-config.xml

















相关属性及意义请参考官方文档

创建mapper接口
@Component
@Mapper
public interface PersonMapper {
    List findAllPersons();

    Person findById(int id);

    void insertPerson(int age,String name);

}

这@Component->注入到spring容器中,使用的时候就可以不手动初始化
@Mapper->声明这是一个Mybatis的操作类,会被扫描到

配置mapper.xml文件





    
        
        
        
    
    
    
    
        insert into person(age,name) values(#{age},#{name})
    

文件头可复制
mapper-namespace:与xml对应的java文件的全限定名
resultMapr:一个封装的结构,可以组合复杂的返回类型提供下面的sql调用