欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-02-16 23:36:16
因为实习用的是mybatis框架,所以写一篇关于springboot整合mybatis框架的总结。 一,pom文件

因为实习用的是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简单数据访问应用的实例代码,希望对大家有所帮助