Springboot整合Mybatis

作者: smallmartial | 来源:发表于2019-04-07 19:52 被阅读1次

title: springboot一
date: 2019-04-07 19:16:20
tags:


Springboot整合Mybatis

SpringBoot官方并没有提供Mybatis的启动器,不过Mybatis官网自己实现了:

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>

配置

mybatis:
 # configuration:
    #map-underscore-to-camel-case: true
  #mapper-locations: mapper/*.xml
type-aliases-package: cn.smallmartial.springbootdemo.pojo
# mapper.xml文件位置,如果没有映射文件,请注释掉
mybatis.mapper-locations=classpath:mappers/*.xml

关于配置文件中华mybaits的configuration中 如果没有内容,需要注释掉否则会报错,笔者太菜,查阅很长时间才找到错误所在。

通用mapper配置

<dependency>
    <groupId>tk.mybatis</groupId>
    <artifactId>mapper-spring-boot-starter</artifactId>
    <version>2.0.2</version>
</dependency>

通用Mapper都可以极大的方便开发人员。可以随意的按照自己的需要选择通用方法,还可以很方便的开发自己的通用方法。
极其方便的使用MyBatis单表的增删改查。支持单表操作,
不支持通用的多表联合查询。

使用方式

继承通用的Mapper<T>,必须指定泛型<T>,导包需要导入tk.mybaits中的包。

import tk.mybatis.mapper.common.Mapper;
public interface UserMapper extends Mapper<User> {
}

通用mapper中含有单表的增删改查

//根据T对象中的属性名称查询,类似于select * from table where t.username=xxx and t.mobile = xxxx

List<T> select(T t)

//如果断定T对象的查询条件是一个,可以调用此方法,返回单个对象
T selectOne(T t)

//根据主键查询
T selectByPrimaryKey(Object id)

//根据主键更新数据,T对象里面有什么属性就更新什么属性,如果T对象没有主键,抛出异常
int updateByPrimaryKeySelective(T t)

//根据主键更新数据,需要把对象中所有的字段全部填充才能调用此方法,一般不常用!
int updateByPrimaryKey(T t)
//根据主键更新数据,T对象里面有什么属性就更新什么属性,如果T对象没有主键,抛出异常
int updateByPrimaryKeySelective(T t)
//插入数据,需要有主键,有什么属性插入什么属性
int insertSelective(T t)
//插入数据,需要有主键,需要数据库表中的所有字段全都存在,否则插入失败,此方法不常用
int insert(T t)
//根据条件删除数据,原理同select(T)
int delete(T t)
//根据主键删除
int deleteByPrimaryKey(T t)

测试类

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
    @Autowired
    private UserMapper userMapper;
    @Test
    public void testQuery(){
        User user = userMapper.selectByPrimaryKey(1L);
        System.out.println("user = "+ user);
    }
}

使用的是springboot开发,导入测试方法选择springboot中所集成的测试类,在需要测测试方法中使用@SpringBootTest。
service层实现方法

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public User queryById(Integer id){
        return userMapper.selectByPrimaryKey(id);
    }
    public void insertUser(User user){
        userMapper.insert(user);
    }
}

controller层实现

@RestController
@RequestMapping("user")
public class HelloController {

    @Autowired
    private UserService userService;
    @GetMapping("{id}")
    public User hello(@PathVariable("id") Integer id){
       // System.out.println("hello methd is running");
        return userService.queryById(id);
    }
}

项目运行结果:


a.png

相关文章

网友评论

    本文标题:Springboot整合Mybatis

    本文链接:https://www.haomeiwen.com/subject/bhceiqtx.html