spring boot+mybatis整合

一、java web开发环境搭建

网上有很多教程,参考教程:http://www.cnblogs.com/Leo_wl/p/4752875.html

二、Spring boot搭建

1、Intellij idea菜单栏File->new->project。

image

2、选择左侧栏中spring initializr,右侧选择jdk版本,以及默认的Service URL,点击next。

image

/3、然后填写项目的Group、Artifact等信息,helloworld阶段选默认就可以了,点击next。

image

4、左侧点击Web,中间一侧选择Web,然后左侧选择SQL,中间一侧选择JPA、Mybatis、MYSQL(LZ数据库用的是mysql,大家可以选择其他DB),点击next。

image

5、填写Project name 等信息,然后点击Finish。

image

至此,一个maven web项目就创建好了,目录结构如下:

image

这样,Spring boot就搭建好了,pom.xml里已经有了Spring boot的jar包,包括我们的mysql数据连接的jar包。Spring boot内置了类似tomcat这样的中间件,所以,只要运行DemoApplication中的main方法就可以启动项目了。我们测试一下。

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

[
复制代码

](javascript:void(0); "复制代码")

<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>

[
复制代码

](javascript:void(0); "复制代码")

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

[
复制代码

](javascript:void(0); "复制代码")

<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>

[
复制代码

](javascript:void(0); "复制代码")

spring boot启动DemoAplication是需要扫描它下面的Controller等类的,所以将DemoApplication移动到com/demo目录下。还有就是Spring boot启动默认是要加载数据源的,所以我们在src/main/resources下新建application.yml:

按 Ctrl+C 复制代码

<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 复制代码

或者将pom.xml中加载数据源的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>

最终的目录结构如下,

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文件:

[
复制代码

](javascript:void(0); "复制代码")

<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>

[
复制代码

](javascript:void(0); "复制代码")

在application.yml中添加数据源、Mybatis的实体和配置文件位置。

[
复制代码

](javascript:void(0); "复制代码")

<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选择无关 mapperLocations指的路径是src/main/resources

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


开发配置

spring:
profiles: dev

datasource:
url: jdbc:mysql://localhost:3306/test
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
# 使用druid数据源
type: com.alibaba.druid.pool.DruidDataSource</pre>

[
复制代码

](javascript:void(0); "复制代码")

就这样就整合完成了!我们测试一下。

用MyBatis Generator自动生成代码,参考博文:http://blog.csdn.net/zhshulin/article/details/23912615 这里列一下自动生成的代码。

[
复制代码

](javascript:void(0); "复制代码")

<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>

[
复制代码

](javascript:void(0); "复制代码")

UserMapper.xml

[
复制代码

](javascript:void(0); "复制代码")

<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>

[
复制代码

](javascript:void(0); "复制代码")

[
复制代码

](javascript:void(0); "复制代码")

<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>

[
复制代码

](javascript:void(0); "复制代码")

最后将DemoApplication.java修改一下,让其扫描dao层接口。

[
复制代码

](javascript:void(0); "复制代码")

<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>

[
复制代码

](javascript:void(0); "复制代码")

自己添加controller和service

[
复制代码

](javascript:void(0); "复制代码")

<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>

[
复制代码

](javascript:void(0); "复制代码")

[
复制代码

](javascript:void(0); "复制代码")

<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>

[
复制代码

](javascript:void(0); "复制代码")

[
复制代码

](javascript:void(0); "复制代码")

<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>

[
复制代码

](javascript:void(0); "复制代码")

浏览器访问http://localhost:8080/user/showUser?id=1

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

推荐阅读更多精彩内容