SpringBoot+MyBatis简单数据访问应用的实例代码

时间:2019-03-30
本文章向大家介绍SpringBoot+MyBatis简单数据访问应用的实例代码,主要包括SpringBoot+MyBatis简单数据访问应用的实例代码使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

因为实习用的是MyBatis框架,所以写一篇关于SpringBoot整合MyBatis框架的总结。

一,Pom文件

<?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>com.example</groupId>
  <artifactId>example</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging> //这里设置为jar,因为我们会使用jar包部署运行
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.2.RELEASE</version>
  </parent>
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    <dependency>
      <groupId>org.mybatis.spring.boot</groupId>
      <artifactId>mybatis-spring-boot-starter</artifactId> //Mybatis的jar包
      <version>1.1.1</version>
    </dependency>
    <dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-mapper-asl</artifactId> //json数据格式和对象的转换jar包
      <version>1.9.8</version>
      <type>jar</type>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>com.h2database</groupId> //内嵌数据库
      <artifactId>h2</artifactId> 
      <version>1.3.156</version>
    </dependency>
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId> //lombok插件,方便model对象的处理
      <version>1.16.2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId> //mysql驱动
      <version>5.1.18</version>
    </dependency>
  </dependencies>
  <build>
    <finalName>example</finalName> //打包后的jar包名称
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId> //必须要的SpringBoot继承的maven插件,缺少了无法打包jar。
        <executions>
          <execution>
            <goals>
              <goal>repackage</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <artifactId>maven-resources-plugin</artifactId> //因为jar包中可能存在很多其他的配置资源,例如mapper文件所以打包为jar包需要将其加入,所以需要此资源打包插件
        <version>2.5</version>
        <executions>
          <execution>
            <id>copy-xmls</id>
            <phase>process-sources</phase>
            <goals>
              <goal>copy-resources</goal>
            </goals>
            <configuration>
              <outputDirectory>${basedir}/target/classes</outputDirectory>
              <resources>
                <resource>
                  <directory>${basedir}/src/main/java</directory>
                  <includes>
                    <include>**/*.xml</include>
                  </includes>
                </resource>
              </resources>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
    <resources> //打包包含相应的资源文件
      <resource>
        <directory>src/main/resources</directory> 
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
          <include>**/*.tld</include>
        </includes>
        <filtering>false</filtering>
      </resource>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
          <include>**/*.tld</include>
        </includes>
        <filtering>false</filtering>
      </resource>
    </resources>
  </build>
  <repositories>//设置仓库
    <repository>
      <id>spring-milestone</id>
      <url>http://repo.spring.io/libs-release</url>
    </repository>
  </repositories>
</project>

好了简单的SpringBoot整合Mybatis框架的基础环境已经搭建完成了,一个Pom文件搞定,接下来我们配置我们的配置文件。

二,配置文件

我们写在resources目录下的application.properties文件中。

spring.datasource.url=jdbc:mysql://localhost:3306/数据库名称?useUnicode=true&characterEncoding=UTF8
spring.datasource.username=用户名
spring.datasource.password=用户密码
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
mybatis.mapper-locations=classpath*:/mapper/*Mapper.xml //mapper文件的路径
mybatis.type-aliases-package=map.model //mapper文件中的前缀
server.port=监听端口号,不设置默认8080

ok,现在环境已经彻底搭建完成我们可以编写自己的代码了。

三,编写代码

Model对象

@Data//@Data lombok插件的注解自动添加get set方法
public class ExampleModel {
  private Long id;
  private String name;
}
//一个简单的model对象

Dao层

这里需要注意的是,推荐公司使用的一种做法,因为很多的Dao对象都是简单的增删改查功能,所以我们抽象出一个最基本的父类,这个父类实现最基本的增删改查功能,每个新的Dao对象可以继承这个类,然后自定义实现特殊的数据库访问功能,我们可以把这个基本的父类成为MyBatisHelper并用上泛型,具体实现如下:

@Data
public class MybatisHelper<T> {
  @Autowired
  private SqlSession sqlSession; //这里自动注入mybatis的SqlSession
  private String nameSpace;
  public MybatisHelper(String nameSpace) {
    this.nameSpace = nameSpace;
  }
  public String getSqlName(String sqlName) {
    return nameSpace +"."+ sqlName;
  }
  public Integer create(String name, T obj) {
    return sqlSession.insert(getSqlName(name), obj);
  }
  public Boolean update(String name, T obj) {
    return Boolean.valueOf(sqlSession.update(getSqlName(name), obj) > 0);
  }
  public T findById(String name, Long id) {
    return sqlSession.selectOne(getSqlName(name), id);
  }
  public Boolean delete(String name, Long id) {
    return Boolean.valueOf(sqlSession.delete(getSqlName(name), id) > 0);
  }
  public List<T> findAll(String name){return sqlSession.selectList(getSqlName(name));}
}

需要说明的是因为sqlSession的执行回去寻找相应的mapper文件,所以namespace+方法名称很重要,这个一定要注意不要弄错了,弄错了就会无法正确调用。

然后我们的Dao层实现继承此类

@Component
public class ExampleModelDao extends MybatisHelper<ExampleModel>{
  public ExampleModelDao() {
    super("example.dao.");
  }
//todo 自定义操作
public Integer findDataCounts(){
  return getSqlSession().selectOne(getSqlName("findDataCounts"));//他会寻找example.dao.findDataCounts对应的方法执行
}
}

这样是不是很简单,也能大量复用很省事,关于service层我就不写了很简单。

四,mapper文件

<?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="example.dao">//这里很重要就是前缀
  <resultMap id="ExampleModelMap" type="ExampleMode">
    <id column="id" property="id"/>
    <result column="name" property="name"/>
  </resultMap> //自定义resultMap对象,利于对象的操作
  <sql id="tb"> //数据表标签
    example_data
  </sql>
  <sql id="value_exclude_id"> //除了主键以为的字段集合标签
    name
  </sql>
  <sql id="vls"> //插入属性的字段集合标签
    id,name
  </sql>
  <sql id="insert_value">//插入输入进来的字段值标签
    #{name}
  </sql>
  <insert id="create" parameterType="ExampleModel">
    INSERT INTO <include refid="tb"/> (<include refid="value_exclude_id"/>) VALUES (<include refid="insert_value"/>)
  </insert>//一看就明白了创建一个对象
  <select id="findById" parameterType="long" resultMap="ExampleModelMap">//返回我们定义的resultMap
    SELECT <include refid="vls"/> FROM <include refid="tb"/> WHERE id = #{id}
  </select>
  <select id="findAll" resultMap="ExampleModelMap">
    SELECT <include refid="vls"/> FROM <include refid="tb"/>
  </select>
  <select id="findDataCounts" resultType="int">
    SELECT count(1) FROM <include refid="tb"/>
  </select>//自定义的操作
</mapper>

ok,对应的mapper文件已经有了,我们就可以调用了,调用很简单一般写在service层中调用,下面我们去编写对应的controller。

五,控制器编写

推荐使用restful风格,因此我们控制器编写代码如下:

@RestController
@CrossOrigin //这个是ajax跨域请求允许的注解,不用可以去掉
public class DigMapDataController {
  @Autowired
  private ExampleService exampleService;//service对象
  @RequestMapping(value = "/create", method = RequestMethod.POST)
  public String create(@requestBody ExampleModel exampleModel) {
    return String.valueOf(exampleService.create(exampleModel));
}
//@requestBody注解会接受前端的JSON数据并配合jackson自动转换为相应的对象
  @RequestMapping(value = "/find/count",method = RequestMethod.GET)
  public Integer findCounts() {
    return exampleService.findDataCounts();
  }
}

一个简单的控制器就编写完成了,这个时候我们可以启动应用进行数据访问了,是不是很简单。

六,应用的部署

直接在终端中使用命令,将应用打包为jar文件

1.maven  [clean]  package ;打包后的文件在target目录下

2.java -jar example.jar ; 运行我们的jar包程序

ok 大功告成!

以上所述是小编给大家介绍的SpringBoot+MyBatis简单数据访问应用的实例代码,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言!