• DEMO: springboot 与 mybatis 集成


    之前一直在用springMVC,接触到springboot之后,感觉使用起来方便多了,没那多xml需要配置。

    先来看看整个项目结构,当然是maven项目。

    1、测试数据

    DROP TABLE IF EXISTS `student`;
    CREATE TABLE `student` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `name` varchar(100) NOT NULL,
      `sex` varchar(100) NOT NULL,
      `no` int(100) NOT NULL,
      `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
      `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;
    
    -- ----------------------------
    -- Records of student
    -- ----------------------------
    INSERT INTO `student` VALUES ('1', 'danny', 'male', '10000001', '2017-06-12 11:12:30', '2017-06-12 13:21:12');
    INSERT INTO `student` VALUES ('2', 'ellen', 'female', '10000002', '2017-06-12 11:12:50', '2017-06-12 13:21:19');
    View Code

    2、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>learn.danny.yao</groupId>
        <artifactId>springboot-demo</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.0.0.M1</version>
        </parent>
    
        <properties>
            <java.version>1.8</java.version>
            <mybatis.version>3.4.4</mybatis.version>
            <druid.version>1.0.18</druid.version>
            <mybatisSpring.version>1.3.0</mybatisSpring.version>
        </properties>
    
        <dependencies>
            <!--Spring Boot -->
            <!--支持 Web 应用开发,包含 Tomcat 和 spring-mvc。 -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <!--支持使用 JDBC 访问数据库 -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-jdbc</artifactId>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>${druid.version}</version>
            </dependency>
            <!--Mybatis -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>${mybatisSpring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>${mybatis.version}</version>
            </dependency>
            <!--Mysql / DataSource -->
            <dependency>
                <groupId>org.apache.tomcat</groupId>
                <artifactId>tomcat-jdbc</artifactId>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
            </dependency>
            <!--Json Support -->
            <!-- <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> 
                <version>1.1.43</version> </dependency> -->
            <!--Swagger support -->
            <!-- <dependency> <groupId>com.mangofactory</groupId> <artifactId>swagger-springmvc</artifactId> 
                <version>0.9.5</version> </dependency> -->
    
            <!-- 热部署 -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>springloaded</artifactId>
                <version>1.2.5.RELEASE</version>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    </project>
    View Code

    3、springboot入口类 Application.java

    package demo.springboot;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class Application {
    
        private static final Logger LOGGER = LoggerFactory.getLogger(Application.class);
        
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
            LOGGER.info("Springboot started successfully!");
        }
    }
    View Code

    4、Model类 Student.java

    package demo.springboot.model;
    
    import java.util.Date;
    
    public class Student {
        private Integer id;
    
        private String name;
    
        private String sex;
        
        private Integer no;
        
        private Date createTime;
    
        private Date updateTime;
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getSex() {
            return sex;
        }
    
        public void setSex(String sex) {
            this.sex = sex;
        }
    
        public Integer getNo() {
            return no;
        }
    
        public void setNo(Integer no) {
            this.no = no;
        }
    
        public Date getCreateTime() {
            return createTime;
        }
    
        public void setCreateTime(Date createTime) {
            this.createTime = createTime;
        }
    
        public Date getUpdateTime() {
            return updateTime;
        }
    
        public void setUpdateTime(Date updateTime) {
            this.updateTime = updateTime;
        }
    
    }
    View Code

    5、mapper类,StudentMapper.java

    package demo.springboot.mapper;
    
    import java.util.List;
    
    import demo.springboot.model.Student;
    
    public interface StudentMapper {
        
        public List<Student> listStudents();
    
    }
    View Code

    6、src/main/resources/mybatis/mapper/StudentMapper.xml

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
    <mapper namespace="demo.springboot.mapper.StudentMapper" >
      <resultMap id="BaseResultMap" type="demo.springboot.model.Student" >
        <id column="id" property="id" jdbcType="INTEGER" />
        <result column="name" property="name" jdbcType="VARCHAR" />
        <result column="sex" property="sex" jdbcType="VARCHAR" />
        <result column="no" property="no" jdbcType="INTEGER" />
        <result column="create_time" property="createTime" jdbcType="TIMESTAMP" />
        <result column="update_time" property="updateTime" jdbcType="TIMESTAMP" />
      </resultMap>
      <sql id="Base_Column_List" >
        id, name, sex, no, create_time, update_time
      </sql>
      <select id="listStudents" resultMap="BaseResultMap">
        select 
        <include refid="Base_Column_List" />
        from student
      </select>
    </mapper>
    View Code

    7、service类,StudentService.java

    package demo.springboot.service;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import demo.springboot.mapper.StudentMapper;
    import demo.springboot.model.Student;
    
    @Service
    public class StudentService {
        
        @Autowired
        private StudentMapper studentMapper;
        
        public List<Student> listStudents(){
            List<Student> students = new ArrayList<>();
            students = studentMapper.listStudents();
            return students;
        }
    
    }
    View Code

    8、mybatis配置类,主要配置DataSource和SqlSessionFactory。MybatisConfig.java

    package demo.springboot.conf;
    
    import java.util.Properties;
    import javax.sql.DataSource;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.mybatis.spring.SqlSessionFactoryBean;
    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.core.env.Environment;
    import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
    import com.alibaba.druid.pool.DruidDataSourceFactory;
    
    /**
     * 
     * @author danny.yao
     * springboot集成mybatis基本入口
     * 1、创建数据源
     * 2、创建SqlSessionFactory
     */
    @Configuration
    @MapperScan(basePackages="demo.springboot.mapper")
    public class MybatisConfig {
        
        @Autowired
        Environment environment;
        
        /**
         * 1、创建数据源
         * @throws Exception 
         * @Primary该注解表示在同一个接口有多个类可以注入的时候,默认选择哪个,而不是让@Autowired报错
         */
        @Bean
    //    @Primary
        public DataSource getDataSource() throws Exception{
            Properties properties = new Properties();
            properties.put("driverClassName", environment.getProperty("jdbc.driverClassName"));
            properties.put("url", environment.getProperty("jdbc.url"));
            properties.put("username", environment.getProperty("jdbc.username"));
            properties.put("password", environment.getProperty("jdbc.password"));
            return DruidDataSourceFactory.createDataSource(properties);
        }
        
        /**
         * 2、根据数据源创建SqlSessionFactory
         * @throws Exception 
         */
        @Bean
        public SqlSessionFactory sessionFactory(DataSource dataSource) throws Exception{
            SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
            sessionFactoryBean.setDataSource(dataSource);
            sessionFactoryBean.setTypeAliasesPackage(environment.getProperty("mybatis.typeAliasesPackage"));
            sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(environment.getProperty("mybatis.mapperLocations")));
            return sessionFactoryBean.getObject();
        }
        
    
    }
    View Code

    9、src/main/resources/application.properties 配置文件

    jdbc.driverClassName = com.mysql.jdbc.Driver
    jdbc.url = jdbc:mysql://127.0.0.1:3306/test
    jdbc.username = root
    jdbc.password = test
    
    # mybatis #
    mybatis.typeAliasesPackage=demo.springboot.model 
    mybatis.mapperLocations=classpath:/mybatis/mapper/*.xml
    View Code

    10、至此,文件就完整了,启动应用

    Application.java类上 run as Java Application,启动应用。看到“Springboot started successfully!” 说明启动成功

    11、测试

    从浏览器访问 http://localhost:8080/student/list,查看日志看能否正常打印db返回的信息

  • 相关阅读:
    zookeeper
    linux命令大全
    多态1
    单例模式
    java this
    java 构造代码块
    java return
    mapreduce实现分组求最大
    数据相关脚本
    mapreduce实现社交中共同好友
  • 原文地址:https://www.cnblogs.com/dannyyao/p/6992769.html
Copyright © 2020-2023  润新知