Springboot+MyBatis

1.集成MyBatis

  1)引入依赖

    基本依赖,jdk版本号;

    <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>

    <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>最新版</version> </dependency>

    <!-- MyBatis提供了拦截器接口,我们可以实现自己的拦截器, 将其作为一个plugin装入到SqlSessionFactory中。 Github上有位开发者写了一个分页插件,项目地址: https://github.com/pagehelper/Mybatis-PageHelper -->

    <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>4.1.0</version> </dependency>

  2)application.properties 添加数据源配置文件

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: ***
    url: jdbc:mysql://ip:3306/***?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8&useSSL=false

#别名扫描包

mybitis:
  type-aliases-package: 实体包名
  mapper-location: classpath:mapper/*Mapper.xml

  3)启动类:

    @SpringBootApplication

    public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } } //这里和以往不一样的地方就是MapperScan的注解,这个是会扫描该包下的接口

  4)Dao中mapper编写

@Mapper

public interface DemoMappper {
@Select("select *from Demo where name = #{name}")
  public List<Demo> likeName(String name);
}

  5)service、mapper对象用@Autowired注解

2.使用PageHelper分页

  加入pagehelper

@Configuration
public class MyBatisConfiguration {
  @Bean
  public PageInfo pageHelper() {
    PageHelper pageHelper = new PageHelper();

    PageHelper.startPage(dto.getPageNo(), dto.getPageSize());

    List<Role> roleList = roleMapper.queryByPage(dto.getName(),dto.getIsValidate());

    PageInfo pageInfo = new PageInfo(list);

    return  pageInfo ;

  }
}

  controller层:

  @RequestMapping("/likeName")

   public List<Demo> likeName(String name){

  PageHelper.startPage(1,1);//第一个参数页数,第二个每页多少条

   return demoService.likeName(name); }

3.获取自增长ID

mapper中:

@Insert("insert into Demo(name,password) values(#{name},#{password})")

public long save(Demo demo);

service中@Autowired、@Service、@Transaction

 

posted @ 2018-04-16 16:22  袋子里的袋鼠  阅读(115)  评论(0编辑  收藏  举报