欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot+MyBatis簡單數(shù)據(jù)訪問應用的實例代碼

 更新時間:2017年05月21日 19:24:45   作者:說話的方式簡單點丶  
這篇文章主要介紹了SpringBoot+MyBatis簡單數(shù)據(jù)訪問應用的實例代碼,需要的朋友可以參考下

因為實習用的是MyBatis框架,所以寫一篇關(guān)于SpringBoot整合MyBatis框架的總結(jié)。

一,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> //這里設(shè)置為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數(shù)據(jù)格式和對象的轉(zhuǎn)換jar包
      <version>1.9.8</version>
      <type>jar</type>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>com.h2database</groupId> //內(nèi)嵌數(shù)據(jù)庫
      <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驅(qū)動
      <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>//設(shè)置倉庫
    <repository>
      <id>spring-milestone</id>
      <url>http://repo.spring.io/libs-release</url>
    </repository>
  </repositories>
</project>

好了簡單的SpringBoot整合Mybatis框架的基礎(chǔ)環(huán)境已經(jīng)搭建完成了,一個Pom文件搞定,接下來我們配置我們的配置文件。

二,配置文件

我們寫在resources目錄下的application.properties文件中。

spring.datasource.url=jdbc:mysql://localhost:3306/數(shù)據(jù)庫名稱?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=監(jiān)聽端口號,不設(shè)置默認8080

ok,現(xiàn)在環(huán)境已經(jīng)徹底搭建完成我們可以編寫自己的代碼了。

三,編寫代碼

Model對象

@Data//@Data lombok插件的注解自動添加get set方法
public class ExampleModel {
  private Long id;
  private String name;
}
//一個簡單的model對象

Dao層

這里需要注意的是,推薦公司使用的一種做法,因為很多的Dao對象都是簡單的增刪改查功能,所以我們抽象出一個最基本的父類,這個父類實現(xiàn)最基本的增刪改查功能,每個新的Dao對象可以繼承這個類,然后自定義實現(xiàn)特殊的數(shù)據(jù)庫訪問功能,我們可以把這個基本的父類成為MyBatisHelper并用上泛型,具體實現(xiàn)如下:

@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的執(zhí)行回去尋找相應的mapper文件,所以namespace+方法名稱很重要,這個一定要注意不要弄錯了,弄錯了就會無法正確調(diào)用。

然后我們的Dao層實現(xiàn)繼承此類

@Component
public class ExampleModelDao extends MybatisHelper<ExampleModel>{
  public ExampleModelDao() {
    super("example.dao.");
  }
//todo 自定義操作
public Integer findDataCounts(){
  return getSqlSession().selectOne(getSqlName("findDataCounts"));//他會尋找example.dao.findDataCounts對應的方法執(zhí)行
}
}

這樣是不是很簡單,也能大量復用很省事,關(guān)于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"> //數(shù)據(jù)表標簽
    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>//一看就明白了創(chuàng)建一個對象
  <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文件已經(jīng)有了,我們就可以調(diào)用了,調(diào)用很簡單一般寫在service層中調(diào)用,下面我們?nèi)ゾ帉憣腸ontroller。

五,控制器編寫

推薦使用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數(shù)據(jù)并配合jackson自動轉(zhuǎn)換為相應的對象
  @RequestMapping(value = "/find/count",method = RequestMethod.GET)
  public Integer findCounts() {
    return exampleService.findDataCounts();
  }
}

一個簡單的控制器就編寫完成了,這個時候我們可以啟動應用進行數(shù)據(jù)訪問了,是不是很簡單。

六,應用的部署

直接在終端中使用命令,將應用打包為jar文件

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

2.java -jar example.jar ; 運行我們的jar包程序

ok 大功告成!

以上所述是小編給大家介紹的SpringBoot+MyBatis簡單數(shù)據(jù)訪問應用的實例代碼,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言!

相關(guān)文章

  • Spring Security學習之rememberMe自動登錄的實現(xiàn)

    Spring Security學習之rememberMe自動登錄的實現(xiàn)

    這篇文章主要給大家介紹了關(guān)于Spring Security學習之rememberMe自動登錄的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧
    2020-06-06
  • Java?Spring讀取和存儲詳細操作

    Java?Spring讀取和存儲詳細操作

    這篇文章主要介紹了Spring讀取和存儲詳細操作,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下
    2022-08-08
  • Java實現(xiàn)簡單圖形界面計算器

    Java實現(xiàn)簡單圖形界面計算器

    這篇文章主要為大家詳細介紹了Java實現(xiàn)簡單圖形界面計算器,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-04-04
  • springboot加載一個properties文件轉(zhuǎn)換為map方式

    springboot加載一個properties文件轉(zhuǎn)換為map方式

    這篇文章主要介紹了springboot加載一個properties文件轉(zhuǎn)換為map方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-07-07
  • 關(guān)于使用MyBatis簡化JDBC開發(fā)和解決SQL語句警告的問題

    關(guān)于使用MyBatis簡化JDBC開發(fā)和解決SQL語句警告的問題

    這篇文章主要介紹了關(guān)于使用MyBatis簡化JDBC開發(fā)和解決SQL語句警告的問題,如果idea和數(shù)據(jù)庫沒有建立鏈接,idea不識別表的信息,就會出現(xiàn)SQL語句的警告,需要的朋友可以參考下
    2023-05-05
  • 使用java實現(xiàn)猜拳小游戲

    使用java實現(xiàn)猜拳小游戲

    這篇文章主要為大家詳細介紹了使用java實現(xiàn)猜拳小游戲,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-07-07
  • SpringBoot利用注解來實現(xiàn)Redis分布式鎖

    SpringBoot利用注解來實現(xiàn)Redis分布式鎖

    有些業(yè)務請求,屬于耗時操作,需要加鎖,防止后續(xù)的并發(fā)操作,同時對數(shù)據(jù)庫的數(shù)據(jù)進行操作,需要避免對之前的業(yè)務造成影響。本文將利用注解來實現(xiàn)Redis分布式鎖,需要的可以參考一下
    2022-09-09
  • 解決springboot啟動報錯bean找不到的問題

    解決springboot啟動報錯bean找不到的問題

    這篇文章主要介紹了解決springboot啟動報錯bean找不到原因,本文給大家分享完美解決方案,通過圖文相結(jié)合給大家介紹的非常詳細,需要的朋友可以參考下
    2023-03-03
  • java中注解的原理解析

    java中注解的原理解析

    這篇文章主要介紹了java中注解的原理解析,java 注解又稱 Java 標注,是 JDK5.0 引入的一種注釋機制,可以理解為為某個東西,打個標記的記號,等要使用這個注解時,可以通過反射獲取標注里面的內(nèi)容,需要的朋友可以參考下
    2023-10-10
  • JDK20?+?SpringBoot?3.1.0?+?JdbcTemplate?使用案例詳解

    JDK20?+?SpringBoot?3.1.0?+?JdbcTemplate?使用案例詳解

    通過 JdbcTemplate 直接執(zhí)行 SQL 語句,結(jié)合源碼動態(tài)編譯即可方便實現(xiàn)動態(tài)修改代碼邏輯的效果,這篇文章主要介紹了JDK20?+?SpringBoot?3.1.0?+?JdbcTemplate?使用,需要的朋友可以參考下
    2023-09-09

最新評論