1. 程式人生 > >springboot簡單整合Mybatis

springboot簡單整合Mybatis

整合MyBatis之前,先搭建一個基本的Spring Boot專案開啟Spring Boot。然後引入mybatis-spring-boot-starter

 可參考上一篇

在pom中引入:注意版本問題

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.1</version>
</dependency>

我引入是mysql 連線池是druid

	<!-- 資料庫 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>

		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid-spring-boot-starter</artifactId>
			<version>1.1.9</version>
		</dependency>

Druid資料來源配置

spring:
  datasource:
    druid:
      url: jdbc:mysql://localhost:3306/spdb?characterEncoding=utf8&useSSL=false&serverTimezone=UTC
      username: root
      password: infosys668
      initial-size: 5
      max-active: 20
      max-wait: 60000
      pool-prepared-statements: true
      max-pool-prepared-statement-per-connection-size: 20
      filters:
            commons-log.connection-logger-name: stat,wall,log4j
      time-between-eviction-runs-millis: 60000
      min-evictable-idle-time-millis: 300000
      validation-query: select 1 from dual
mybatis:
  # type-aliases掃描路徑
  # type-aliases-package:
  # mapper xml實現掃描路徑
  mapper-locations: classpath:mapper/*.xml
  property:
    order: BEFORE

上述配置不但配置了Druid作為連線池,而且還開啟了Druid的監控功能。 其他配置可參考官方wiki——https://github.com/alibaba/druid/tree/master/druid-spring-boot-starter

使用MyBatis

使用的庫表:

DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) COLLATE utf8_bin NOT NULL,
  `password` varchar(200) COLLATE utf8_bin NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=16 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'admin', '$2a$10$2SEEBYecvUr0MeP7.afSvu1VQmnsRPR.2tLRx0pIX3vgMUjZUcOqG');
INSERT INTO `user` VALUES ('2', 'user', '$2a$10$2SEEBYecvUr0MeP7.afSvu1VQmnsRPR.2tLRx0pIX3vgMUjZUcOqG');

建立對應實體:

package com.yxkj.aha.entity;

/**
 * @Auther: zch
 * @Date: 2018/12/6 08:38
 * @Description:
 */
public class user {
    private Integer id;
    private String username;
    private String password;

   //省略get set
}

建立一個包含查詢的userMapper:

package com.yxkj.aha.mapper;

import com.yxkj.aha.entity.user;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Auther: zch
 * @Date: 2018/12/6 08:37
 * @Description:
 */
@Component
@Mapper
public interface userMapper {

    @Select("select * from user")
    List<user> selectOne();

}

測試

@RunWith(SpringRunner.class)
@SpringBootTest
public class userMapperTest {

    @Autowired
    userMapper userMapper;

    @Test
    public void selectOne() {
        System.out.println(userMapper.selectOne());
    }
}

結果

程式碼