spring boot+mybatis整合

一、java web開發(fā)環(huán)境搭建

網(wǎng)上有很多教程,參考教程:http://www.cnblogs.com/Leo_wl/p/4752875.html

二、Spring boot搭建

1、Intellij idea菜單欄File->new->project。

image

2、選擇左側(cè)欄中spring initializr,右側(cè)選擇jdk版本,以及默認的Service URL,點擊next。

image

/3、然后填寫項目的Group、Artifact等信息,helloworld階段選默認就可以了,點擊next。

image

4、左側(cè)點擊Web,中間一側(cè)選擇Web,然后左側(cè)選擇SQL,中間一側(cè)選擇JPA、Mybatis、MYSQL(LZ數(shù)據(jù)庫用的是mysql,大家可以選擇其他DB),點擊next。

image

5、填寫Project name 等信息,然后點擊Finish。

image

至此,一個maven web項目就創(chuàng)建好了,目錄結(jié)構(gòu)如下:

image

這樣,Spring boot就搭建好了,pom.xml里已經(jīng)有了Spring boot的jar包,包括我們的mysql數(shù)據(jù)連接的jar包。Spring boot內(nèi)置了類似tomcat這樣的中間件,所以,只要運行DemoApplication中的main方法就可以啟動項目了。我們測試一下。

在src/main/java下新建目錄com/demo/entity/User。

[
復(fù)制代碼

](javascript:void(0); "復(fù)制代碼")

<pre style="margin: 0px; white-space: pre-wrap; overflow-wrap: break-word; padding: 0px; list-style-type: none; list-style-image: none; font-family: "Courier New" !important; font-size: 12px !important;">package com.demo.entity; public class User { private String name; public String getName() { return name;
} public void setName(String name) { this.name = name;
}
}</pre>

[
復(fù)制代碼

](javascript:void(0); "復(fù)制代碼")

相同目錄下新建com/demo/controller/TestBootController。

[
復(fù)制代碼

](javascript:void(0); "復(fù)制代碼")

<pre style="margin: 0px; white-space: pre-wrap; overflow-wrap: break-word; padding: 0px; list-style-type: none; list-style-image: none; font-family: "Courier New" !important; font-size: 12px !important;">package com.demo.controller; import com.demo.entity.User; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;

@RestController
@EnableAutoConfiguration
@RequestMapping("/testboot") public class TestBootController {
@RequestMapping("getuser") public User getUser() {
User user = new User();
user.setName("test"); return user;
}
}</pre>

[
復(fù)制代碼

](javascript:void(0); "復(fù)制代碼")

spring boot啟動DemoAplication是需要掃描它下面的Controller等類的,所以將DemoApplication移動到com/demo目錄下。還有就是Spring boot啟動默認是要加載數(shù)據(jù)源的,所以我們在src/main/resources下新建application.yml:

按 Ctrl+C 復(fù)制代碼

<textarea style="margin: 0px; padding: 0px; list-style-type: none; list-style-image: none; font: 12px/1.5 "Courier New"; width: 689px; height: 403.2px;"></textarea>

按 Ctrl+C 復(fù)制代碼

或者將pom.xml中加載數(shù)據(jù)源的jar包先注釋掉也可以。

<pre style="margin: 0px; white-space: pre-wrap; overflow-wrap: break-word; padding: 0px; list-style-type: none; list-style-image: none; font-family: "Courier New" !important; font-size: 12px !important;">/<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
/</pre>

最終的目錄結(jié)構(gòu)如下,

image

啟動DemoApplication的main方法,訪問http://localhost:8080/testboot/getuser即可。

image

三、整合Mybatis

1、集成druid,使用連接池。pom.xml中添加:

<pre style="margin: 0px; white-space: pre-wrap; overflow-wrap: break-word; padding: 0px; list-style-type: none; list-style-image: none; font-family: "Courier New" !important; font-size: 12px !important;"><dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.0</version>
</dependency></pre>

最終的pom.xml文件:

[
復(fù)制代碼

](javascript:void(0); "復(fù)制代碼")

<pre style="margin: 0px; white-space: pre-wrap; overflow-wrap: break-word; padding: 0px; list-style-type: none; list-style-image: none; font-family: "Courier New" !important; font-size: 12px !important;"><?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.arm</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>demo</name>
<description>Demo project for Spring Boot</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.8.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>1.3.1</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.0</version>
    </dependency>

</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

</project></pre>

[
復(fù)制代碼

](javascript:void(0); "復(fù)制代碼")

在application.yml中添加數(shù)據(jù)源、Mybatis的實體和配置文件位置。

[
復(fù)制代碼

](javascript:void(0); "復(fù)制代碼")

<pre style="margin: 0px; white-space: pre-wrap; overflow-wrap: break-word; padding: 0px; list-style-type: none; list-style-image: none; font-family: "Courier New" !important; font-size: 12px !important;">#默認使用配置
spring:
profiles:
active: dev

公共配置與profiles選擇無關(guān) mapperLocations指的路徑是src/main/resources

mybatis:
typeAliasesPackage: com.xdd.entity
mapperLocations: classpath:mapper/*.xml


開發(fā)配置

spring:
profiles: dev

datasource:
url: jdbc:mysql://localhost:3306/test
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
# 使用druid數(shù)據(jù)源
type: com.alibaba.druid.pool.DruidDataSource</pre>

[
復(fù)制代碼

](javascript:void(0); "復(fù)制代碼")

就這樣就整合完成了!我們測試一下。

用MyBatis Generator自動生成代碼,參考博文:http://blog.csdn.net/zhshulin/article/details/23912615 這里列一下自動生成的代碼。

[
復(fù)制代碼

](javascript:void(0); "復(fù)制代碼")

<pre style="margin: 0px; white-space: pre-wrap; overflow-wrap: break-word; padding: 0px; list-style-type: none; list-style-image: none; font-family: "Courier New" !important; font-size: 12px !important;">import com.xdd.entity.User; import org.springframework.stereotype.Component; public interface UserDao { int deleteByPrimaryKey(Integer id); int insert(User record); int insertSelective(User record);

User selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(User record); int updateByPrimaryKey(User record);

}</pre>

[
復(fù)制代碼

](javascript:void(0); "復(fù)制代碼")

UserMapper.xml

[
復(fù)制代碼

](javascript:void(0); "復(fù)制代碼")

<pre style="margin: 0px; white-space: pre-wrap; overflow-wrap: break-word; padding: 0px; list-style-type: none; list-style-image: none; font-family: "Courier New" !important; font-size: 12px !important;"><?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.xdd.dao.UserDao" >
<resultMap id="BaseResultMap" type="com.xdd.entity.User" >
<id column="id" property="id" jdbcType="INTEGER" />
<result column="user_name" property="userName" jdbcType="VARCHAR" />
<result column="password" property="password" jdbcType="VARCHAR" />
<result column="age" property="age" jdbcType="INTEGER" />
</resultMap>
<sql id="Base_Column_List" > id, user_name, password, age </sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" > select <include refid="Base_Column_List" /> from user_t
where id = #{id,jdbcType=INTEGER} </select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" > delete from user_t
where id = #{id,jdbcType=INTEGER} </delete>
<insert id="insert" parameterType="com.xdd.entity.User" > insert into user_t (id, user_name, password,
age)
values (#{id,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},
#{age,jdbcType=INTEGER}) </insert>
<insert id="insertSelective" parameterType="com.xdd.entity.User" > insert into user_t <trim prefix="(" suffix=")" suffixOverrides="," >
<if test="id != null" > id, </if>
<if test="userName != null" > user_name, </if>
<if test="password != null" > password, </if>
<if test="age != null" > age, </if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="id != null" > #{id,jdbcType=INTEGER}, </if>
<if test="userName != null" > #{userName,jdbcType=VARCHAR}, </if>
<if test="password != null" > #{password,jdbcType=VARCHAR}, </if>
<if test="age != null" > #{age,jdbcType=INTEGER}, </if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.xdd.entity.User" > update user_t <set >
<if test="userName != null" > user_name = #{userName,jdbcType=VARCHAR}, </if>
<if test="password != null" > password = #{password,jdbcType=VARCHAR}, </if>
<if test="age != null" > age = #{age,jdbcType=INTEGER}, </if>
</set> where id = #{id,jdbcType=INTEGER} </update>
<update id="updateByPrimaryKey" parameterType="com.xdd.entity.User" > update user_t
set user_name = #{userName,jdbcType=VARCHAR},
password = #{password,jdbcType=VARCHAR},
age = #{age,jdbcType=INTEGER}
where id = #{id,jdbcType=INTEGER} </update>
</mapper></pre>

[
復(fù)制代碼

](javascript:void(0); "復(fù)制代碼")

[
復(fù)制代碼

](javascript:void(0); "復(fù)制代碼")

<pre style="margin: 0px; white-space: pre-wrap; overflow-wrap: break-word; padding: 0px; list-style-type: none; list-style-image: none; font-family: "Courier New" !important; font-size: 12px !important;">public class User { private Integer id; private String userName; private String password; private Integer age; public Integer getId() { return id;
} public void setId(Integer id) { this.id = id;
} 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();
} public Integer getAge() { return age;
} public void setAge(Integer age) { this.age = age;
}
}</pre>

[
復(fù)制代碼

](javascript:void(0); "復(fù)制代碼")

最后將DemoApplication.java修改一下,讓其掃描dao層接口。

[
復(fù)制代碼

](javascript:void(0); "復(fù)制代碼")

<pre style="margin: 0px; white-space: pre-wrap; overflow-wrap: break-word; padding: 0px; list-style-type: none; list-style-image: none; font-family: "Courier New" !important; font-size: 12px !important;">import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.support.SpringBootServletInitializer;

@SpringBootApplication
@MapperScan("com.xdd.dao") public class DemoApplication extends SpringBootServletInitializer{ public static void main(String[] args) {
SpringApplication.run(DemoApplication.class,args);
}
}</pre>

[
復(fù)制代碼

](javascript:void(0); "復(fù)制代碼")

自己添加controller和service

[
復(fù)制代碼

](javascript:void(0); "復(fù)制代碼")

<pre style="margin: 0px; white-space: pre-wrap; overflow-wrap: break-word; padding: 0px; list-style-type: none; list-style-image: none; font-family: "Courier New" !important; font-size: 12px !important;">import java.util.List; import java.util.Map; public interface UserService { public User getUserById(int userId); boolean addUser(User record);

}</pre>

[
復(fù)制代碼

](javascript:void(0); "復(fù)制代碼")

[
復(fù)制代碼

](javascript:void(0); "復(fù)制代碼")

<pre style="margin: 0px; white-space: pre-wrap; overflow-wrap: break-word; padding: 0px; list-style-type: none; list-style-image: none; font-family: "Courier New" !important; font-size: 12px !important;">import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; import java.util.Map;

@Service("userService") public class UserServiceImpl implements UserService {

@Resource private UserDao userDao; public User getUserById(int userId) { return userDao.selectByPrimaryKey(userId);
} public boolean addUser(User record){ boolean result = false; try {
        userDao.insertSelective(record);
        result = true;
    } catch (Exception e) {
        e.printStackTrace();
    } return result;
}

}</pre>

[
復(fù)制代碼

](javascript:void(0); "復(fù)制代碼")

[
復(fù)制代碼

](javascript:void(0); "復(fù)制代碼")

<pre style="margin: 0px; white-space: pre-wrap; overflow-wrap: break-word; padding: 0px; list-style-type: none; list-style-image: none; font-family: "Courier New" !important; font-size: 12px !important;">@Controller
@RequestMapping("/user") public class UserController {
@Resource private UserService userService;

@RequestMapping("/showUser")
@ResponseBody public User toIndex(HttpServletRequest request, Model model){ int userId = Integer.parseInt(request.getParameter("id"));
    User user = this.userService.getUserById(userId); return user;
}

}</pre>

[
復(fù)制代碼

](javascript:void(0); "復(fù)制代碼")

瀏覽器訪問http://localhost:8080/user/showUser?id=1

image
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,412評論 6 532
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,514評論 3 416
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,373評論 0 374
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,975評論 1 312
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 71,743評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,199評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,262評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,414評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,951評論 1 336
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 40,780評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,983評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,527評論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 44,218評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,649評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,889評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,673評論 3 391
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 47,967評論 2 374

推薦閱讀更多精彩內(nèi)容