mybatis简易项目配置

1.pom

    
    
      org.mybatis.spring.boot
      mybatis-spring-boot-starter
      1.3.2
    
    
    
      tk.mybatis
      mapper-spring-boot-starter
      2.1.5
    
    
      org.projectlombok
      lombok
    

2.application.yaml

mybatis:
  configuration:
#    开启驼峰
    map-underscore-to-camel-case: true
#  让mybatis自动扫描到自定义POJO
  type-aliases-package: com.livesxu.pojo
#  配置mapper  **:任意多级目录
  mapper-locations: classpath:mappers/**/*.xml

3.配置pojo

//lombok库 帮助主动生成set、get等
@Data
public class MyPojo {

    int id;

    String location;

    int worktime;
}

4.App配置扫描mapper的包

支持通用mapper需要使用对应库下的MapperScan
import tk.mybatis.spring.annotation.MapperScan;

@SpringBootApplication
@MapperScan(value = {"com.livesxu.mapper","com.livesxu.hello.myBatisTest"})
public class App 
{
    public static void main( String[] args )
    {
        SpringApplication.run(App.class,args);
    }
}

5.创建mapper接口

public interface MyMapper {

    List findAll();

    MyPojo findOne();
}
  • -- 通用mapper示例
    {
    通用mapper不需要配置xml,但是pojo需多一些注解标识::比如
    1.对类标识表名@Table(name = "tb_user");
    2.标识主键
    3.标识不持久化
    @Id
    @KeySql(useGeneratedKeys = true)//作为主键自增长
    private int id;

    //瞬时,不作为sql字段持久化
    @Transient
    private String note;

}

import tk.mybatis.mapper.common.Mapper;

public interface UserMapper extends Mapper {
}

6.resources下配置mapper需要的xml




    
    



7.测试调用:

@RestController
@RequestMapping("mybt")
public class BatisTest {

    @Autowired
    MyMapper myMapper;

    @RequestMapping("findAll")
    public List findAllTest() {

        return myMapper.findAll();
    }

    @RequestMapping("findOne")
    public MyPojo findOne() {

        return myMapper.findOne();
    }
}
  • -- 通用mapper可以使用定义好的一些api
@Repository
public class RegisterDaoImpl implements RegisterDao {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void registerUser(User user) {

        userMapper.insert(user);
        //delete...
    }
}

https://mybatis.org/mybatis-3/zh/index.html
https://apidoc.gitee.com/free/Mapper/

你可能感兴趣的:(mybatis简易项目配置)