SpringBoot和Mybatis整合

SpringBoot和Mybatis整合


使用Maven配置 Eclipse环境 MySql数据库

  • 最近刚开始学习Spring框架
  • 然后也是第一次使用MyBatis和SpringBoot的整合
  • 从网上找了很多种方法 一直都搞不出来 最后终于成功了 所以写一下博客记录一下
  • 下面的代码里面我只写了SelectByPrimayKey的方法 其余的方法大同小异也就没有写了 毕竟只是为了试验这两个框架的整合使用
  • 然后有很多代码是从别的博客里面照搬的 不过东拼西凑的也没注意原作者到底是谁 所以也没写作者的名字
  • 如果有侵权请指正 我会马上删除或者写上出处

1.首先配置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.tony</groupId>
    <artifactId>SecondMyBatisWithSB</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.2.3.RELEASE</version>
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <!-- commons -->
        <commons-io.version></commons-io.version>
        <commons-lang3.version>3.4</commons-lang3.version>
        <!-- springMvc -->
        <spring-jdbc.version>4.1.6.RELEASE</spring-jdbc.version>
        <spring-tx.version>4.1.6.RELEASE</spring-tx.version>
        <spring-web.version>4.1.6.RELEASE</spring-web.version>
        <spring-webmvc>4.1.6.RELEASE</spring-webmvc>
        <spring-data-japa.version>1.8.0.RELEASE</spring-data-japa.version>
        <spring-test.version>4.1.6.RELEASE</spring-test.version>
        <aspectjweaver.version>1.8.5</aspectjweaver.version>
        <webmvc.version>2.2.2.RELEASE</webmvc.version>
        <!-- myBatis -->
        <mybatis.version>3.2.8</mybatis.version>
        <mybatis-generator-core.version>1.3.2</mybatis-generator-core.version>
        <mybatis-spring.version>1.2.2</mybatis-spring.version>
        <mysql-connector-java.version>5.1.34</mysql-connector-java.version>
        <!-- mybatis pagehelper -->
        <pagehelper.version>3.6.3</pagehelper.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>${commons-lang3.version}</version>
        </dependency>
        <!-- datasource heroku -->
        <dependency>
            <groupId>com.zaxxer</groupId>
            <artifactId>HikariCP-java6</artifactId>
            <exclusions>
                <exclusion>
                    <artifactId>tools</artifactId>
                    <groupId>com.sun</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- aspectJ -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
        </dependency>
        <!-- Spring boot -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- myBatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatis.version}</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>${mybatis-spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>${mybatis-generator-core.version}</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!-- mybatis pagehelper -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>${pagehelper.version}</version>
        </dependency>
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-rest-webmvc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-commons</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.hateoas</groupId>
            <artifactId>spring-hateoas</artifactId>
        </dependency>
        <!-- javax -->
        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
            <version>1</version>
        </dependency>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>7.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.glassfish.web</groupId>
            <artifactId>javax.servlet.jsp.jstl</artifactId>
            <version>1.2.2</version>
        </dependency>
    </dependencies>
    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.mybatis.generator</groupId>
                    <artifactId>mybatis-generator-maven-plugin</artifactId>
                    <version>1.3.2</version>
                    <configuration>
                        <configurationFile>src/main/resources/mybatis-generator-config.xml</configurationFile>
                        <verbose>true</verbose>
                        <overwrite>true</overwrite>
                    </configuration>
                    <executions>
                        <execution>
                            <id>Generate MyBatis Artifacts</id>
                            <goals>
                                <goal>generate</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <configuration>
                        <source>1.7</source>
                        <target>1.7</target>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>

</project>

2.配置application.yml 放置在resources文件夹下即可

# Server settings
server:
    port:8080
    address:localhost

# DATASOURCE
jdbc:
    dataSourceClassName: com.mysql.jdbc.jdbc2.optional.MysqlDataSource
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&charaterEncoding=utf-8
    databaseName: test
    serverName: 127.0.0.1
    username: root
    password: root
    cachePrepStmts: true
    prepStmtsSize: 250
    prepStmtsCacheSqlLimit: 2048
    userServerPrepStmts: true

# SPRING PROFILES
spring:       
    # HTTP ENCODING
    http:
        encoding.charset: UTF-8
        encoding.enable: true
        encoding.force: true

# MyBatis
mybatis:
    typeAliasesPackage: com.tony.entity
    mapperLocations: classpath:/com/tony/mapper/*.xml
    configLocation: classpath:/mybatis-config.xml

# LOGGING
logging:
    level:
       com.ibatis:DEBUG

3.配置mybatis-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
    <properties>
        <property name="dialect" value="mysql" />
    </properties>
    <settings>
        <!-- 这个配置使全局的映射器启用或禁用缓存。系统默认值是true,设置只是为了展示出来 -->
        <setting name="cacheEnabled" value="true" />
        <!-- 全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载。 系统默认值是true,设置只是为了展示出来 -->
        <setting name="lazyLoadingEnabled" value="true" />
        <!-- 允许或不允许多种结果集从一个单独的语句中返回(需要适合的驱动)。 系统默认值是true,设置只是为了展示出来 -->
        <setting name="multipleResultSetsEnabled" value="true" />
        <!--使用列标签代替列名。不同的驱动在这方便表现不同。参考驱动文档或充分测试两种方法来决定所使用的驱动。 系统默认值是true,设置只是为了展示出来 -->
        <setting name="useColumnLabel" value="true" />
        <!--允许 JDBC 支持生成的键。需要适合的驱动。如果设置为 true 则这个设置强制生成的键被使用,尽管一些驱动拒绝兼容但仍然有效(比如 
            Derby)。 系统默认值是false,设置只是为了展示出来 -->
        <setting name="useGeneratedKeys" value="false" />
        <!--配置默认的执行器。SIMPLE 执行器没有什么特别之处。REUSE 执行器重用预处理语句。BATCH 执行器重用语句和批量更新 系统默认值是SIMPLE,设置只是为了展示出来 -->
        <setting name="defaultExecutorType" value="SIMPLE" />
        <!--设置超时时间,它决定驱动等待一个数据库响应的时间。 系统默认值是null,设置只是为了展示出来 -->
        <setting name="defaultStatementTimeout" value="25000" />
    </settings>
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageHelper">
            <property name="dialect" value="mysql" />
            <property name="offsetAsPageNum" value="true" />
            <property name="rowBoundsWithCount" value="true" />
            <property name="pageSizeZero" value="true" />
            <property name="reasonable" value="true" />
        </plugin>
    </plugins>
</configuration>

4.配置mybatis-generator.properties

  • 这个是用来配置自动生成mapper.xml\dao\entity用的配置文件
#=============================#
#======database setting=======#
#=============================#

# mysql database setting
jdbc.type=mysql
jdbc.driverClassName:com.mysql.jdbc.Driver
jdbc.url:jdbc:mysql://127.0.0.1:3306/xxx?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true
jdbc.username=root
jdbc.password=root

# pool settings
jdbc.pool.minIdle=8
jdbc.pool.maxActive=100

# mybatis generator setting
generator.classPath=C:/Users/TonyJiang/.m2/repository/mysql/mysql-connector-java/5.1.38/mysql-connector-java-5.1.38.jar
generator.mapperConfigFilename=mapper-config.xml
generator.targetProject=SecondMyBatisWithSB
generator.domainPackage=com.tony.entity
generator.mapperPackage=com.tony.mapper
generator.daoPackage=com.tony.dao

5.配置mybatis-generator-config.xml

<?xml version="1.0" encoding="UTF-8" ?>  
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
<generatorConfiguration>
    <!-- 引入配置文件 -->
    <properties resource="mybatis-generator.properties" />
    <!-- 指定数据连接驱动jar地址 -->
    <classPathEntry location="${generator.classPath}" />
    <!-- 一个数据库一个context -->
    <context id="BuildingTables" targetRuntime="Mybatis3">
        <!-- defaultModelType="hierarchical" -->
        <property name="javaFileEncoding" value="UTF-8" />
        <property name="suppressTypeWarnings" value="true" />

        <plugin type="org.mybatis.generator.plugins.SerializablePlugin" />
        <plugin type="org.mybatis.generator.plugins.CaseInsensitiveLikePlugin" />
        <plugin type="org.mybatis.generator.plugins.RowBoundsPlugin" />
        <plugin type="org.mybatis.generator.plugins.ToStringPlugin" />
        <plugin type="org.mybatis.generator.plugins.CachePlugin" />


        <plugin type="org.mybatis.generator.plugins.MapperConfigPlugin">
            <property name="fileName" value="${generator.mapperConfigFilename}" />
            <property name="targetPackage" value="${generator.mapperPackage}" />
            <property name="targetProject"
                value="${generator.targetProject}/src/main/java" />
        </plugin>
        <plugin type="org.mybatis.generator.plugins.RenameExampleClassPlugin">
            <property name="searchString" value="Example$" />
            <property name="replaceString" value="Criteria" />
        </plugin>

        <!-- 注释 -->
        <commentGenerator>
            <property name="suppressAllComments" value="true" /><!-- 是否取消注释 -->
            <property name="suppressDate" value="true" /> <!-- 是否生成注释代时间戳 -->
        </commentGenerator>

        <!-- jdbc连接 -->
        <jdbcConnection driverClass="${jdbc.driverClassName}"
            connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}" />
        <!-- 类型转换 -->
        <javaTypeResolver>
            <!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!-- 生成实体类地址 -->
        <javaModelGenerator targetPackage="${generator.domainPackage}"
            targetProject="${generator.targetProject}/src/main/java">
            <!-- 是否在当前路径下新加一层schema,eg:fase路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->
            <property name="enableSubPackages" value="true" />
            <!-- 是否针对string类型的字段在set的时候进行trim调用 -->
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <!-- 生成mapxml文件 -->
        <sqlMapGenerator targetPackage="${generator.mapperPackage}"
            targetProject="${generator.targetProject}/src/main/java">
            <!-- 是否在当前路径下新加一层schema,eg:fase路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>

        <!-- 生成mapxml对应client,也就是接口dao -->
        <javaClientGenerator targetPackage="${generator.daoPackage}"
            targetProject="${generator.targetProject}/src/main/java" type="XMLMAPPER">
            <!-- 是否在当前路径下新加一层schema,eg:fase路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>

        <!-- 配置表信息 -->
        <table tableName="t_user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" 
            enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>  
 
    </context>
</generatorConfiguration>  
  • 之后用mybatis-generator的插件自动生成相应的mapper dao接口 entity既可
  • 具体方法可以先百度 相对来说比较简单的
  • 或者也可以手写一下 毕竟刚开始学手写更能熟悉那些结构

6.下面开始代码部分


  • 首先是Application.java
  • 必须放在主包下面 这样才能成功扫描所有的包
  • 比如我是放在com.tony下面
package com.tony;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan
@EnableAutoConfiguration
@SpringBootApplication
public class Application {
    public static void main(String[] args){
        SpringApplication.run(Application.class, args);
    }
}

  • 然后是controller层 先测试一下SpringBoot能不能运行
  • com.tony.controller
package com.tony.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.tony.service.UserService;

@Controller
@RequestMapping("/test")
public class TestAction {

    @Autowired
    private UserService userService;
    @RequestMapping("/greeting")
    @ResponseBody
    public Object hello(){
        return "Hello Spring";
    }
    @ResponseBody
    @RequestMapping("/user")
    public Object get(@RequestParam String id){
        return userService.findOne(id);
    }
}


下面是自动生成的那几个部分

  • com.tony.dao
  • com.tony.mapper
  • com.tony.entity
    不过其实我是修改过的 不是原来自动生成的那些

UserMapper.java

package com.tony.dao;

import com.tony.entity.User;
import com.tony.commons.dao.BaseDao;

public interface UserMapper extends BaseDao<User, String>{
   
}

User.java

package com.tony.entity;

import java.io.Serializable;

import com.tony.commons.entity.AbstractEntity;

public class User extends AbstractEntity implements Serializable {
    private String id;

    private String username;

    private String password;

    private static final long serialVersionUID = 1L;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id == null ? null : id.trim();
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username == null ? null : username.trim();
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password == null ? null : password.trim();
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(getClass().getSimpleName());
        sb.append(" [");
        sb.append("Hash = ").append(hashCode());
        sb.append(", id=").append(id);
        sb.append(", username=").append(username);
        sb.append(", password=").append(password);
        sb.append(", serialVersionUID=").append(serialVersionUID);
        sb.append("]");
        return sb.toString();
    }
}

UserMapper.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="com.tony.dao.UserMapper" >
  <resultMap id="BaseResultMap" type="com.tony.entity.User" >
    <id column="id" property="id" jdbcType="VARCHAR" />
    <result column="username" property="username" jdbcType="VARCHAR" />
    <result column="password" property="password" jdbcType="VARCHAR" />
    <result column="create_by" property="createBy" jdbcType="VARCHAR" />
    <result column="create_date" property="createDate" jdbcType="DATE" />
    <result column="last_modified_by" property="lastModifiedBy" jdbcType="VARCHAR" />
    <result column="last_modified_date" property="lastModifiedDate" jdbcType="DATE" />
  </resultMap>
  
  
  <sql id="Base_Column_List" >
    id, username, password, create_by, create_date, last_modified_by, last_modified_date
  </sql>
  
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.String" >
    select 
    <include refid="Base_Column_List" />
    from t_user
    where id = #{id,jdbcType=VARCHAR}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.String" >
    delete from t_user
    where id = #{id,jdbcType=VARCHAR}
  </delete>
  
  <insert id="insert" parameterType="com.tony.entity.User" >
    insert into t_user (id, username, password, 
      create_by, create_date, last_modified_by, 
      last_modified_date)
    values (#{id,jdbcType=VARCHAR}, #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, 
      #{createBy,jdbcType=VARCHAR}, #{createDate,jdbcType=DATE}, #{lastModifiedBy,jdbcType=VARCHAR}, 
      #{lastModifiedDate,jdbcType=DATE})
  </insert>
  <insert id="insertSelective" parameterType="com.tony.entity.User" >
    insert into t_user
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        id,
      </if>
      <if test="username != null" >
        username,
      </if>
      <if test="password != null" >
        password,
      </if>
      <if test="createBy != null" >
        create_by,
      </if>
      <if test="createDate != null" >
        create_date,
      </if>
      <if test="lastModifiedBy != null" >
        last_modified_by,
      </if>
      <if test="lastModifiedDate != null" >
        last_modified_date,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=VARCHAR},
      </if>
      <if test="username != null" >
        #{username,jdbcType=VARCHAR},
      </if>
      <if test="password != null" >
        #{password,jdbcType=VARCHAR},
      </if>
      <if test="createBy != null" >
        #{createBy,jdbcType=VARCHAR},
      </if>
      <if test="createDate != null" >
        #{createDate,jdbcType=DATE},
      </if>
      <if test="lastModifiedBy != null" >
        #{lastModifiedBy,jdbcType=VARCHAR},
      </if>
      <if test="lastModifiedDate != null" >
        #{lastModifiedDate,jdbcType=DATE},
      </if>
    </trim>
  </insert>

  
  <update id="updateByPrimaryKeySelective" parameterType="com.tony.entity.User" >
    update t_user
    <set >
      <if test="username != null" >
        username = #{username,jdbcType=VARCHAR},
      </if>
      <if test="password != null" >
        password = #{password,jdbcType=VARCHAR},
      </if>
      <if test="createBy != null" >
        create_by = #{createBy,jdbcType=VARCHAR},
      </if>
      <if test="createDate != null" >
        create_date = #{createDate,jdbcType=DATE},
      </if>
      <if test="lastModifiedBy != null" >
        last_modified_by = #{lastModifiedBy,jdbcType=VARCHAR},
      </if>
      <if test="lastModifiedDate != null" >
        last_modified_date = #{lastModifiedDate,jdbcType=DATE},
      </if>
    </set>
    where id = #{id,jdbcType=VARCHAR}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.tony.entity.User" >
    update t_user
    set username = #{username,jdbcType=VARCHAR},
      password = #{password,jdbcType=VARCHAR},
      create_by = #{createBy,jdbcType=VARCHAR},
      create_date = #{createDate,jdbcType=DATE},
      last_modified_by = #{lastModifiedBy,jdbcType=VARCHAR},
      last_modified_date = #{lastModifiedDate,jdbcType=DATE}
    where id = #{id,jdbcType=VARCHAR}
  </update>
  
  <cache />
</mapper>

接下来是一些需要自己写的
com.tony.commons.dao
BaseDao.java

package com.tony.commons.dao;

import java.io.Serializable;

public interface BaseDao<T extends Serializable , ID extends Serializable> {
    int deleteByPrimaryKey(ID id);
    
    int insert(T record);
    
    int insertSelective(T record);
    
    
    T selectByPrimaryKey(ID id);
    
    
    int updateByPrimaryKeySelective(T record);
    
    int updateByPrimaryKey(T record);
}


com.tony.commons.entity
AbstractEntity.java

package com.tony.commons.entity;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.MappedSuperclass;
import javax.validation.constraints.NotNull;

import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;


@MappedSuperclass
public abstract class AbstractEntity implements  Serializable {

    private static final long serialVersionUID = 1L;

    private String id;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
    
    @CreatedBy
    @NotNull
    private String createBy;

    @CreatedDate
    @NotNull
    private Date createDate = new Date();

    @LastModifiedBy
    private String lastModifiedBy;

    @LastModifiedDate
    private Date lastModifiedDate = new Date();

    

    public String getCreateBy() {
        return createBy;
    }

    public void setCreateBy(String createBy) {
        this.createBy = createBy;
    }

    

    public Date getCreateDate() {
        return createDate;
    }

    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }

    public String getLastModifiedBy() {
        return lastModifiedBy;
    }

    public void setLastModifiedBy(String lastModifiedBy) {
        this.lastModifiedBy = lastModifiedBy;
    }

    public Date getLastModifiedDate() {
        return lastModifiedDate;
    }

    public void setLastModifiedDate(Date lastModifiedDate) {
        this.lastModifiedDate = lastModifiedDate;
    }
}


com.tony.commons.service
BaseService.java

package com.tony.commons.service;

import java.io.Serializable;

public interface BaseService<T extends Serializable> {


    T findOne(String id);

}


com.tony.commons.service.impl
BaseServiceImpl.java

package com.tony.commons.service.impl;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.tony.commons.dao.BaseDao;
import com.tony.commons.entity.AbstractEntity;
import com.tony.commons.service.BaseService;

@Transactional
public abstract class BaseServiceImpl<T extends AbstractEntity>
        implements BaseService<T> {

    protected abstract BaseDao<T,  String> getDao();

    protected Class<T> entityClazz;


    @SuppressWarnings("unchecked")
    public BaseServiceImpl() {
        Type genType = getClass().getGenericSuperclass();
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
        entityClazz = (Class<T>) params[0];
    }



    @Transactional(readOnly = true)
    public T findOne(String id) {
        Assert.notNull(id);
        return getDao().selectByPrimaryKey(id);
    }

}


com.tony.service
UserService.java

package com.tony.service;

import com.tony.entity.User;
import com.tony.commons.service.BaseService;

public interface UserService extends BaseService<User> {
    User findOneById(String Id);
}


com.tony.service.impl
UserServiceImpl.java

package com.tony.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.tony.dao.UserMapper;
import com.tony.entity.User;
import com.tony.service.UserService;
import com.tony.commons.dao.BaseDao;
import com.tony.commons.service.impl.BaseServiceImpl;

@Service
@Transactional
public class UserServiceImpl extends BaseServiceImpl<User>
        implements UserService {

    @Autowired
    private UserMapper userDao;


    public User findOneById(String Id) {
        return getDao().selectByPrimaryKey(Id);
    }

    
    @Override
    protected BaseDao<User, String> getDao() {
        return userDao;
    }
}


下面两个是Mybatis的配置类
com.tony.config.mybatis
DataBaseConfiguration.java

package com.tony.config.mybatis;

import java.util.Arrays;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.ApplicationContextException;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

@Configuration
@EnableTransactionManagement
public class DataBaseConfiguration implements EnvironmentAware {

    private RelaxedPropertyResolver propertyResolver;

    private static Logger log = LoggerFactory
            .getLogger(DataBaseConfiguration.class);

    private Environment env;

    public void setEnvironment(Environment env) {
        this.env = env;
        this.propertyResolver = new RelaxedPropertyResolver(env, "jdbc.");
    }

    @Bean(destroyMethod = "shutdown")
    public DataSource dataSource() {
        log.debug("Configruing DataSource");
        if (propertyResolver.getProperty("url") == null
                && propertyResolver.getProperty("databaseName") == null) {
            log.error("Your database conncetion pool configuration is incorrct ! The application "
                    + "cannot start . Please check your jdbc");
            Arrays.toString(env.getActiveProfiles());
            throw new ApplicationContextException(
                    "DataBase connection pool is not configured correctly");
        }
        HikariConfig config = new HikariConfig();
        config.setDataSourceClassName(propertyResolver
                .getProperty("dataSourceClassName"));
        if (propertyResolver.getProperty("url") == null
                || "".equals(propertyResolver.getProperty("url"))) {
            config.addDataSourceProperty("databaseName",
                    propertyResolver.getProperty("databaseName"));
            config.addDataSourceProperty("serverName",
                    propertyResolver.getProperty("serverName"));
        } else {
            config.addDataSourceProperty("url",
                    propertyResolver.getProperty("url"));
        }
        config.setUsername(propertyResolver.getProperty("username"));
        config.setPassword(propertyResolver.getProperty("password"));
        if ("com.mysql.jdbc.jdbc2.optional.MysqlDataSource"
                .equals(propertyResolver.getProperty("dataSourceName"))) {
            config.addDataSourceProperty("cachePrepStmts",
                    propertyResolver.getProperty("cachePrepStmts"));
            config.addDataSourceProperty("prepStmtCacheSize",
                    propertyResolver.getProperty("prepStmtsCacheSize"));
            config.addDataSourceProperty("prepStmtCacheSqlLimit",
                    propertyResolver.getProperty("prepStmtCacheSqlLimit"));
            config.addDataSourceProperty("userServerPrepStmts",
                    propertyResolver.getProperty("userServerPrepStmts"));
        }
        return new HikariDataSource(config);
    }

}

MybatisConfiguration.java

package com.tony.config.mybatis;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@ConditionalOnClass({ EnableTransactionManagement.class, EntityManager.class })
@AutoConfigureAfter({ DataBaseConfiguration.class })
@MapperScan(basePackages={"com.tony.dao"})
public class MybatisConfiguration implements EnvironmentAware {

    private static Log logger = LogFactory.getLog(MybatisConfiguration.class);

    private RelaxedPropertyResolver propertyResolver;

    @Inject
    private DataSource dataSource;

    public void setEnvironment(Environment environment) {
        this.propertyResolver = new RelaxedPropertyResolver(environment,
                "mybatis.");
    }

    @Bean
    @ConditionalOnMissingBean
    public SqlSessionFactory sqlSessionFactory() {
        try {
            SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
            sessionFactory.setDataSource(dataSource);
            sessionFactory.setTypeAliasesPackage(propertyResolver
                    .getProperty("typeAliasesPackage"));
            sessionFactory
                    .setMapperLocations(new PathMatchingResourcePatternResolver()
                            .getResources(propertyResolver
                                    .getProperty("mapperLocations")));
            sessionFactory
                    .setConfigLocation(new DefaultResourceLoader()
                            .getResource(propertyResolver
                                    .getProperty("configLocation")));

            return sessionFactory.getObject();
        } catch (Exception e) {
            logger.warn("Could not confiure mybatis session factory");
            return null;
        }
    }

    @Bean
    @ConditionalOnMissingBean
    public DataSourceTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource);
    }
}


好了 大功告成 运行一下应该就可以了

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 201,784评论 5 474
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,745评论 2 378
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 148,702评论 0 335
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,229评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,245评论 5 363
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,376评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,798评论 3 393
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,471评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,655评论 1 295
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,485评论 2 318
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,535评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,235评论 3 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,793评论 3 304
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,863评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,096评论 1 258
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,654评论 2 348
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,233评论 2 341

推荐阅读更多精彩内容