Mybatis三剑客(一)在springboot中手动使用Mybatis

1、pom.xml中引入依赖【注意根据自己的spring boot版本选择对应的mysql和mybatis版本】

		
			mysql
			mysql-connector-java
		

		
			org.mybatis.spring.boot
			mybatis-spring-boot-starter
			2.1.0
		

2、resources/application.xml配置

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password:
    url: jdbc:mysql://127.0.0.1:3306/mall?characterEncoding=utf-8&useSSL=false
mybatis:
  configuration:
    map-underscore-to-camel-case: true
  mapper-locations: classpath:mappers/*.xml

3、pojo/Category

@Data
public class Category {
    private Integer id;

    private Integer parentId;

    private String name;

    private Boolean status;

    private Integer sortOrder;

    private Date createTime;

    private Date updateTime;
}

4、dao/CategoryMapper.java

@Mapper
public interface CategoryMapper {
    Category queryById(Integer id);
}

5、建立同名xml文件

resources/mappers/CategoryMapper.xml




    
        id, parent_id, name, status, sort_order, create_time, update_time
    
    

注意点:

        namespace对应mapper.java地址

        id对应的是mapper中的方法

        resultType对应的是pojo

        Base_Column_List是公共字段提取

6、application.java注入

@SpringBootApplication
@MapperScan(basePackages = "com.imooc.mall.dao")
public class MallApplication {

	public static void main(String[] args) {
		SpringApplication.run(MallApplication.class, args);
	}

}

7、使用

package com.imooc.mall;

import com.imooc.mall.dao.CategoryMapper;
import com.imooc.mall.pojo.Category;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MallApplicationTests {

	@Autowired
	private CategoryMapper categoryMapper;

	@Test
	public void contextLoads() {

	}

	@Test
	public void queryByIdTest() {

		Category category = categoryMapper.queryById(100001);
		System.out.println(category.toString());
	}

}

你可能感兴趣的:(spring,boot,mybatis,后端)