美文网首页
spring-boot-mybatis基于注解

spring-boot-mybatis基于注解

作者: ___简爱 | 来源:发表于2018-09-19 18:36 被阅读9次

    今天看了springboot-mybatis基于注解来编码,总结下来,以便以后查看。有不好嘚嘚地方多多指教。

    1.新建一张简单的表

    CREATE TABLE `demo` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `NAME` varchar(100) DEFAULT NULL
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    

    可以随便出入几条数据,方便测试。

    2.新建maven项目

    工程新建完成,加入pom.xml依赖

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>com.kfit</groupId>
        <artifactId>spring-boot-mybatis</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <packaging>jar</packaging>
    
        <name>spring-boot-mybatis</name>
        <url>http://maven.apache.org</url>
    
        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        </properties>
    
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>1.4.1.RELEASE</version>
        </parent>
    
        <dependencies>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <scope>test</scope>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <!-- mysql 数据库驱动. -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
            </dependency>
    
            <!-- spring-boot mybatis依赖: 请不要使用1.0.0版本,因为还不支持拦截器插件, PageHelper 无法支持... -->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>1.3.0</version>
            </dependency>
    
            <!-- 分页插件. 最低是4.1.5 -->
            <dependency>
                <groupId>com.github.pagehelper</groupId>
                <artifactId>pagehelper</artifactId>
                <version>4.2.1</version>
            </dependency>
    
    
            <dependency>
                <groupId>org.scala-lang</groupId>
                <artifactId>scala-library</artifactId>
                <version>2.11.0</version>
            </dependency>
        </dependencies>
    </project>
    
    

    3.编辑mybatis分页配置类,设置分页属性

    import java.util.Properties;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    import com.github.pagehelper.PageHelper;
    
    @Configuration
    public class MyBatisConfiguration {
        @Bean
        public PageHelper pageHelper() {
            System.out.println("配置mybatis分页!");
            PageHelper pageHelper = new PageHelper();
            Properties properties = new Properties();
            properties.setProperty("offsetAsPageNum", "true");
            properties.setProperty("rowBoundsWithCount", "true");
            properties.setProperty("reasonable", "true");
            pageHelper.setProperties(properties);
            return pageHelper;
        }
    }
    

    4.在application.properties文件配置数据源

    配置数据源 连接驱动、账户、密码、最大最小线程

    #mysql数据库配置
    spring.datasource.url=jdbc:mysql://localhost:3306/test
    spring.datasource.username = root
    spring.datasource.password = 123
    spring.datasource.driverClassName = com.mysql.jdbc.Driver
    spring.datasource.max-active = 20
    spring.datasource.max-idle = 8
    spring.datasource.min-idle = 8
    spring.dayasource.initial-size = 10
    

    5.编辑实体类Demo

    属性和表字段对应

    public class Demo {
        
        private int id;
        private String name;
        //省略方法
    
    }
    

    6.编写SQL和javabean映射接口,DemoMapper

    *使用@Ptions配置返回主键信息

    import java.util.List;
    
    import org.apache.ibatis.annotations.Delete;
    import org.apache.ibatis.annotations.Insert;
    import org.apache.ibatis.annotations.Options;
    import org.apache.ibatis.annotations.Select;
    import org.apache.ibatis.annotations.SelectProvider;
    import org.apache.ibatis.annotations.Update;
    
    import com.kfit.demo.bean.Demo;
    
    public interface DemoMapper {
    
        @Insert("insert into demo(name) values(#{name})")
        @Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
        public int save(Demo demo);
    
        @Update("update demo name=#{name} where id=#{id}")
        public int update(Demo demo);
    
        @Delete("delete from demo where id=#{id}")
        public int delete(int id);
    
        @Select("select * from demo")
        public List<Demo> selectAll();
    
    }
    

    7.编写服务类,DemoService

    使用@Transaction开启事务

    import java.util.List;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    
    import com.kfit.demo.bean.Demo;
    import com.kfit.demo.mapper.DemoMapper;
    
    @Service
    public class DemoService {
    
        @Autowired
        private DemoMapper demoMapper;
    
        @Transactional
        public int save(Demo demo) {
            return demoMapper.save(demo);
        }
    
        @Transactional
        public int update(Demo demo) {
            return demoMapper.update(demo);
        }
    
        @Transactional
        public int delete(int id) {
            return demoMapper.delete(id);
        }
        
        public List<Demo> selectAll(){
            return demoMapper.selectAll();
        }
    }
    

    8.编写控制器,提供访问,DemoController

    import java.util.List;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import com.github.pagehelper.Page;
    import com.github.pagehelper.PageHelper;
    import com.kfit.demo.bean.Demo;
    import com.kfit.demo.mapper.DemoMapper;
    import com.kfit.demo.service.DemoService;
    
    @RestController
    public class DemoController {
    
        @Autowired
        private DemoService demoService;
        
        @GetMapping("/save")
        public Demo save(Demo demo) {
            int res = demoService.save(demo);
            System.out.println("res-->" + res + "-->id=" + demo.getId());
            return demo;
        }
    
        @GetMapping("/update")
        public int uodate(Demo demo) {
            return demoService.update(demo);
        }
    
        @GetMapping("/delete")
        public int delete(int id) {
            return demoService.delete(id);
        }
    
        @GetMapping("/selectAll")
        public List<Demo> selectAll(int pageNum, int pageSize) {
            PageHelper.startPage(pageNum, pageSize);
            return demoService.selectAll();
        }
    
    }
    

    9.编写启动类,进行测试

    需要添加@MapperScan--指定mybatis持久类的位置

    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    @MapperScan("com.kfit.*.mapper")
    public class App {
        public static void main(String[] args) {
            SpringApplication.run(App.class, args);
        }
    }
    

    正常情况启动,访问应该是正常。


    mappper类的sql还可以通过另写一个类来实现
    编写DemoSqlProvider

    import java.util.Map;
    
    import org.apache.ibatis.jdbc.SQL;
    
    import com.kfit.demo.bean.Demo;
    
    public class DemoSqlProvider {
    
        public String select7(Demo demo){
            StringBuffer sql = new StringBuffer("select *from demo where 1=1 ");
            if(demo.getName() != null){
                sql.append("and name=#{name} ");
            }
            if(demo.getEmail() != null){
                sql.append("and email=#{email} ");
            }
            return sql.toString();
        }
        
        public String select8(final Demo demo){
            return new SQL(){{
                SELECT("id,name");
                FROM("demo");
                //不需要where 1=1的代码,底层会自动判断.
                //WHERE()方法  ==  XML 使用<where>标签的有等同的效果.
                if(demo.getName() != null){
                    WHERE("name=#{name}");
                }
                if(demo.getEmail() != null){
                    WHERE("email=#{email}");
                }
            }}.toString();
        }
    }
    

    直接在DemoMapper调用

        @SelectProvider(type=DemoSqlProvider.class,method="select7")
        public List<Demo> select7(Demo demo);
        
        @SelectProvider(type=DemoSqlProvider.class,method="select8")
        public List<Demo> select8(Demo demo);
    

    以上就是简单的springboot集成mybatis基于注解的方式。

    相关文章

      网友评论

          本文标题:spring-boot-mybatis基于注解

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