8.mybatis與SpringBoot集成

本來想寫一篇關(guān)于ssm集成方面的文章,但是考慮到現(xiàn)在基本上使用的是SpringBoot框架進(jìn)行開發(fā),因此直接寫SpringBoot框架集成mybatis更好。

一、創(chuàng)建maven項(xiàng)目并導(dǎo)入相應(yīng)的包

<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.qiu</groupId>
    <artifactId>mybatis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.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>
    <!-- springboot 熱部署插件 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!-- springboot集成mybatis需要的包 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.26</version>
        </dependency>
        <!-- 分頁插件 -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>4.1.6</version>
        </dependency>
        <!-- alibaba的druid數(shù)據(jù)庫連接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.0</version>
        </dependency>
        <!-- mybatis代碼生成器相關(guān)的包 -->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.5</version>
        </dependency>

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

        </plugins>
    </build>
</project>

二、mysql中創(chuàng)建數(shù)據(jù)表

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(255) DEFAULT NULL,
  `user_password` varchar(255) DEFAULT NULL,
  `user_email` varchar(255) DEFAULT NULL,
  `user_info` varchar(255) DEFAULT NULL,
  `head_img` varchar(255) DEFAULT NULL,
  `create_time` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

三、使用代碼生成器自動生成相關(guān)的entity、xxxMapper和xxxMapper映射文件。

參照之前的mybatis代碼生成器使用博客:http://www.itdecent.cn/p/b6a0ac3ba17c

  • 在生成的xxxMapper接口上加上@Mapper注解,否則Springboot掃描不到該接口,會報(bào)錯誤。然后自定義一個方法
@Mapper
public interface UserMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(User record);

    int insertSelective(User record);

    User selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);
    //自定義一個方法
    List<User>findAllUser();
}
  • 生成的model類
public class User {
    private Integer id;
    private String userName;
    private String userPassword;
    private String userEmail;
    private String userInfo;
    private String headImg;
    private Date createTime;
    ...省略getter/setter
  • 把UserMapper.xml文件放在src/main/resource/mapper目錄下面,然后在UserMapper.xml文件中添加自定義方法
<?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.qiu.mapper.UserMapper">
  <resultMap id="BaseResultMap" type="com.qiu.model.User">
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="user_name" jdbcType="VARCHAR" property="userName" />
    <result column="user_password" jdbcType="VARCHAR" property="userPassword" />
    <result column="user_email" jdbcType="VARCHAR" property="userEmail" />
    <result column="user_info" jdbcType="VARCHAR" property="userInfo" />
    <result column="head_img" jdbcType="VARCHAR" property="headImg" />
    <result column="create_time" jdbcType="TIMESTAMP" property="createTime" />
  </resultMap>
  <sql id="Base_Column_List">
    id, user_name, user_password, user_email, user_info, head_img, create_time
  </sql>
   <!-- 增加自己增加的方法 -->
  <select id="findAllUser" resultMap="BaseResultMap">
    select
    <include refid="Base_Column_List"></include>
    from user
  </select>
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from user
    where id = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from user
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.qiu.model.User">
    insert into user (id, user_name, user_password, 
      user_email, user_info, head_img, 
      create_time)
    values (#{id,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{userPassword,jdbcType=VARCHAR}, 
      #{userEmail,jdbcType=VARCHAR}, #{userInfo,jdbcType=VARCHAR}, #{headImg,jdbcType=VARCHAR}, 
      #{createTime,jdbcType=TIMESTAMP})
  </insert>
  <insert id="insertSelective" parameterType="com.qiu.model.User">
    insert into user
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        id,
      </if>
      <if test="userName != null">
        user_name,
      </if>
      <if test="userPassword != null">
        user_password,
      </if>
      <if test="userEmail != null">
        user_email,
      </if>
      <if test="userInfo != null">
        user_info,
      </if>
      <if test="headImg != null">
        head_img,
      </if>
      <if test="createTime != null">
        create_time,
      </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="userPassword != null">
        #{userPassword,jdbcType=VARCHAR},
      </if>
      <if test="userEmail != null">
        #{userEmail,jdbcType=VARCHAR},
      </if>
      <if test="userInfo != null">
        #{userInfo,jdbcType=VARCHAR},
      </if>
      <if test="headImg != null">
        #{headImg,jdbcType=VARCHAR},
      </if>
      <if test="createTime != null">
        #{createTime,jdbcType=TIMESTAMP},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.qiu.model.User">
    update user
    <set>
      <if test="userName != null">
        user_name = #{userName,jdbcType=VARCHAR},
      </if>
      <if test="userPassword != null">
        user_password = #{userPassword,jdbcType=VARCHAR},
      </if>
      <if test="userEmail != null">
        user_email = #{userEmail,jdbcType=VARCHAR},
      </if>
      <if test="userInfo != null">
        user_info = #{userInfo,jdbcType=VARCHAR},
      </if>
      <if test="headImg != null">
        head_img = #{headImg,jdbcType=VARCHAR},
      </if>
      <if test="createTime != null">
        create_time = #{createTime,jdbcType=TIMESTAMP},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.qiu.model.User">
    update user
    set user_name = #{userName,jdbcType=VARCHAR},
      user_password = #{userPassword,jdbcType=VARCHAR},
      user_email = #{userEmail,jdbcType=VARCHAR},
      user_info = #{userInfo,jdbcType=VARCHAR},
      head_img = #{headImg,jdbcType=VARCHAR},
      create_time = #{createTime,jdbcType=TIMESTAMP}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>

四、創(chuàng)建一個配置類,并配置好分頁插件

@Configuration
public class MybatisConfig {
    @Bean
    public PageHelper pageHelper() {
        PageHelper pageHelper=new PageHelper();
        Properties properties=new Properties();
//該參數(shù)默認(rèn)為false ,設(shè)置為true時,會將RowBounds第一個參數(shù)offset當(dāng)
//成pageNum頁碼使用,和startPage中的pageNum效果一樣
        properties.setProperty("offsetAsPageNum","true");
//該參數(shù)默認(rèn)為false,設(shè)置為true時,使用RowBounds分頁會進(jìn)行count查詢 
        properties.setProperty("rowBoundsWithCount","true");
//分頁參數(shù)合理化,默認(rèn)false禁用
        properties.setProperty("reasonable","true");
//配置mysql數(shù)據(jù)庫方言
        properties.setProperty("dialect","mysql");
        pageHelper.setProperties(properties);
        return pageHelper;
    }
}

五、創(chuàng)建UserService和UserServiceImp

  • UserService接口
public interface UserService {
    int addUser(User user);
    List<User> findAllUser(int pageNum, int pageSize);
}
  • UserServiceImp實(shí)現(xiàn)類
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public int addUser(User user) {
        return userMapper.insert(user);
    }
    @Override
    public List<User> findAllUser(int pageNum, int pageSize) {
        //進(jìn)行分頁,必須在mybatis從數(shù)據(jù)庫獲取數(shù)據(jù)之前
        PageHelper.startPage(pageNum, pageSize);
        List<User> findAllUser = userMapper.findAllUser();
        return findAllUser;
    }
}

六、創(chuàng)建controller,執(zhí)行web相關(guān)操作

@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/addUser")
    public String addUser() {
        User user=new User();
        user.setCreateTime(new Date());
        user.setUserEmail("111@qq.com");
        user.setUserInfo("hahah");
        user.setUserName("qiu");
        user.setUserPassword("1233");
        int addUser = userService.addUser(user);
        return addUser!=0?"插入成功":"插入失敗";
    }
    @RequestMapping("/getUserByPage")
//默認(rèn)pageNum為1,pageSize為1
    public String getUsersByPage(@RequestParam(value="pageNum",defaultValue="1")Integer pageNum,
     @RequestParam(value="pageSize",defaultValue="2")Integer pageSize) {
         List<User> list = userService.findAllUser(pageNum, pageSize);
         list.forEach(System.out::println);
         return list.toString();
    }

七、創(chuàng)建springboot啟動類

@SpringBootApplication
public class SpringbootMybatisApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootMybatisApplication.class, args);
    }
}

八、在classpath目錄下面創(chuàng)建SpringBoot配置文件application.properties

#tomcat端口
server.port=8082
#datasource
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

# 數(shù)據(jù)庫訪問配置
# 主數(shù)據(jù)源,默認(rèn)的
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

# 下面為連接池的補(bǔ)充設(shè)置,應(yīng)用到上面所有數(shù)據(jù)源中
# 初始化大小,最小,最大
spring.datasource.initialSize=5
spring.datasource.minIdle=5
# 配置獲取連接等待超時的時間
spring.datasource.maxWait=60000
# 配置間隔多久才進(jìn)行一次檢測,檢測需要關(guān)閉的空閑連接,單位是毫秒
spring.datasource.timeBetweenEvictionRunsMillis=60000
# 配置一個連接在池中最小生存的時間,單位是毫秒
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 'x'
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
# 打開PSCache,并且指定每個連接上PSCache的大小
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
# 配置監(jiān)控統(tǒng)計(jì)攔截的filters,去掉后監(jiān)控界面sql無法統(tǒng)計(jì),'wall'用于防火墻
spring.datasource.filters=stat,wall,log4j
# 通過connectProperties屬性來打開mergeSql功能;慢SQL記錄
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.s
tat.slowSqlMillis=5000
# 合并多個DruidDataSource的監(jiān)控?cái)?shù)據(jù)
spring.datasource.useGlobalDataSourceStat=true

#mybatis相關(guān)
#別名
mybatis.type-aliases-package=com.qiu.model
#映射配置文件位置
mybatis.mapper-locations=classpath:mapper/*.xml

九、啟動SpringBoot項(xiàng)目并進(jìn)行訪問

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 1 Mybatis入門 1.1 單獨(dú)使用jdbc編程問題總結(jié) 1.1.1 jdbc程序 上邊使...
    哇哈哈E閱讀 3,416評論 0 38
  • 開羅 午夜里,我獨(dú)自在偌大的房間里輾轉(zhuǎn)難眠。窗外稀稀疏疏的蛐蛐蟈蟈演奏曲,不間斷地從白色的百葉窗的夾縫里鉆進(jìn)來。空...
    修墨68閱讀 421評論 0 1
  • 前些天看了一篇談?wù)撟杂梢庵镜墓栁恼?,其中講到了神經(jīng)科學(xué)論的實(shí)驗(yàn)研究引發(fā)的對于是否存在自由意志的懷疑,并且用另一個...
    YousoBlind_9f1f閱讀 649評論 0 1
  • “把金錢當(dāng)做某種行為的外部獎勵時,行為主體就失去了對這項(xiàng)活動的內(nèi)在興趣"獎勵只能帶來短期的爆發(fā),就像是少量咖啡因只...
    榛果Latte閱讀 241評論 0 1
  • 句子:“自己思考原本就是件很快樂的事情,而教別人思考則是學(xué)習(xí)思考,鍛煉思考的最好方法?!?“只有學(xué)會真正地思考,才...
    不加奶糖的咖啡閱讀 334評論 2 1

友情鏈接更多精彩內(nèi)容