springBoot整合MyBatise及简单应用

springBoot整合MyBatise及简单应用

我采用的是 工具IDEA 框架是springBoot+maven+Mybatise

第一步:

   pom.xml 引入相关jar包

<?xml version="1.0" encoding="UTF-8"?>
<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>cn.xudy.base</groupId>
    <artifactId>testMybase</artifactId>
    <version>1.0-SNAPSHOT</version>

   <parent>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-parent</artifactId>
       <version>1.5.4.RELEASE</version>
       <relativePath/>
   </parent>


    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
        <mybatis-spring-boot.version>1.2.0</mybatis-spring-boot.version>
        <mysql-connector.version>5.1.39</mysql-connector.version>
    </properties>

    <dependencies>

        <!-- MYSQL -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!-- Spring Boot JDBC -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.7</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
          <!--Mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>${mybatis-spring-boot.version}</version>
        </dependency>

    </dependencies>

    <!--maven打包时应用-->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

 第二部:

     建立两个配置文件类

    1、  我采用了c3p0 JDBC 连接池这个文件主要是配置mybatis  的xml配置文件位置

 

@Configuration
//加上这个注解,使得支持事务
@EnableTransactionManagement
public class MyBatisConfig implements TransactionManagementConfigurer {

    @Bean(name = "dataSource")
    @Qualifier(value = "dataSource")
    @Primary
    @ConfigurationProperties(prefix = "c3p0")
    public DataSource dataSource() {
        return DataSourceBuilder.create().type(com.mchange.v2.c3p0.ComboPooledDataSource.class).build();
    }

    @Override
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }

    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactoryBean() {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource());
        bean.setTypeAliasesPackage("cn.group.xudy.model");//每一张表对应的实体类
         //添加XML目录
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            bean.setMapperLocations(resolver.getResources("classpath:mapper/*Mapper.xml"));//每张表对应的xml文件
            return bean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    /**
     * 跨域
     * @return
     */
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**");
            }
        };
    }


}

 2、配置mapper java文件

/**
 * 扫描mybatis的接口
 *MyBatis扫描接口,使用的tk.mybatis.spring.mapper.MapperScannerConfigurer,如果你不使用通用Mapper,可以改为org.xxx...
 * @author zxj
 *
 */
@Configuration
// 因为这个对象的扫描,需要在MyBatisConfig的后面注入,所以加上下面的注解
@AutoConfigureAfter(MyBatisConfig.class)
public class MyBatisMapperScannerConfig {

        @Bean
        public MapperScannerConfigurer mapperScannerConfigurer() {
            MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
            //获取之前注入的beanName为sqlSessionFactory的对象
            mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
            //每张表对应的XXMapper.java interface类型的Java文件
            mapperScannerConfigurer.setBasePackage("cn.group.xudy.mapper");
//            Properties properties = new Properties();
//            properties.setProperty("mappers", "tk.mybatis.springboot.util.MyMapper");
//            properties.setProperty("notEmpty", "false");
//            properties.setProperty("IDENTITY", "MYSQL");
//            mapperScannerConfigurer.setProperties(properties);

            return mapperScannerConfigurer;

        }
}

 注意 mybatis 的mapper.xml  在IDEA中一定要写到resources下面如图

第三步 :

    1.sql以注解的形式访问数据库获取数据

在java下mapper文件下一个下一个简单的注解代码测试下 下面是三种模式


@Select("select * from claims;")
    List<Map<String,Object>> find();

@Select("Select * from claims where id = '${id}'")
Map<String,Object> selectClaimsName(@Param("id") String id);

@Select("Select * from claims where id = #{id}")
Map<String,Object> selectClaimsName(@Param("id") String id);

 

  写一个调用类根据自己的数据库配置 应该没什么问题了

    2、sql语句以xml形式也就是大家常用的mybatis的形式获取数据

    在java下mapper中写调用方法

   

    List<ClaimsModel> getAll();

 在resources下xml写到  我写的是一对多的形式 有点乱 ,这部分就不细说了,如果不懂可以看看相关Mybatis的使用这里只介绍集成

<?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="cn.group.xudy.mapper.claimsMapper">

    <resultMap id="BaseResultMap" type="cn.group.xudy.model.ClaimsModel" >
        <id column="id" property="id" jdbcType="BIGINT" />
        <id column="reason" property="reason" jdbcType="VARCHAR" />
        <id column="files" property="files" jdbcType="VARCHAR" />
        <!-- ofType指定students集合中的对象类型 -->
        <!--<association property="claimFilesModelList" javaType="cn.group.xudy.model.ClaimFilesModel">-->
        <!--</association>-->
        <collection property="claimFilesModelList" ofType="cn.group.xudy.model.ClaimFilesModel" column="id" select="getStudent"></collection>
        <!--<collection property="claimFilesModelList" ofType="cn.group.xudy.model.ClaimFilesModel" column="id">-->
            <!--<id column="file_name" property="fileName" jdbcType="VARCHAR" />-->
        <!--</collection>-->
    </resultMap>

    <sql id="Base_Column_List" >
        id,reason,files
    </sql>


    <select id="getAll" resultMap="BaseResultMap">
--         select * from claims c,claim_files f WHERE  c.id=f.claim_id
            select * from claims c,claim_files
    </select>

    <select id="getStudent" parameterType="int" resultType="cn.group.xudy.model.ClaimFilesModel">
        SELECT * FROM claim_files WHERE claim_id=#{id}
    </select>

</mapper>

 

  OK  代码附上

       https://gitee.com/xdymemory00/testMybase.git

 

posted @ 2017-10-10 14:37  Mr.DongYang  阅读(910)  评论(0编辑  收藏  举报