1. 程式人生 > >擴充套件:SpringBoot+MyBatis框架+mysql資料庫的整合(配置檔案版)

擴充套件:SpringBoot+MyBatis框架+mysql資料庫的整合(配置檔案版)

開發環境:

開發工具:Intellij IDEA 2017.2.3JDK : 1.8.0_144spring boot 版本 : 1.5.10.RELEASEmaven : 3.2.3SpringBoot整合MyBatis加入基礎依賴:mybatis:<dependency>   <groupId>org.mybatis.spring.boot</groupId>   <artifactId>mybatis-spring-boot-starter</artifactId>   <version>1.3.1</version>
</dependency>MySQL:<dependency>   <groupId>mysql</groupId>   <artifactId>mysql-connector-java</artifactId>   <version>5.1.38</version></dependency>資料庫配置:application.ymlspring:  datasource:     url: jdbc:mysql://192.168.1.59:3306/test?useUnicode=true&characterEncoding=UTF-8
     username: root     password: 123456     driver-class-name: com.mysql.jdbc.Driver在Mysql資料庫中建立資料表:CREATE DATABASE mytest; USE mytest; CREATE TABLE t_user( id BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT, name VARCHAR(255) NOT NULL , password VARCHAR(255) NOT NULL , phone VARCHAR(255) NOT NULL ) ENGINE=INNODB AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8;
MyBatis配置檔案配置application.yml(對映檔案配置的位置mybatis:  mapper-locations: classpath*:mapper/*Mapper.xml使用Mybatis:建立對映物件User/** * User實體對映類 * Created by Administrator on 2017/11/24. */ public class User { private Integer id; private String name; private String password; private String phone; //省略 get 和 set ... }建立User對映的操作UserMapper,為了後續單元測試驗證,實現插入和查詢操作/**    * User對映類    * Created by Administrator on 2017/11/24.    */@Mapperpublic interface UserMapper {    User findUserByPhone(@Param("phone") String phone);    int insert(@Param("name") String name, @Param("password") String password, @Param("phone") String phone);對映檔案配置<?xml version="1.0" encoding="UTF-8"?><mapper namespace="com.test2.mapper.UserMapper">    <select id="findUserByPhone" resultType="com.test2.entry.User">        SELECT * FROM t_user WHERE PHONE=#{phone}    </select>    <insert id="insert">        INSERT INTO t_user(NAME,PASSWORD,PHONE) VALUES (#{name},#{password},#{phone})    </insert></mapper>建立單元測試:@RunWith(SpringRunner.class)@SpringBootTestpublic class Demo2ApplicationTests {   @Autowired   private UserMapper userMapper;   @Test   public void insert(){      userMapper.insert("hy","123456","123456789");   }   @Test   public void getBYphone(){      User user =userMapper.findUserByPhone("123456789");      Assert.assertEquals("hy", user.getName());      System.out.println(user.getName()+":"+user.getPassword());   }}配置檔案版:1.需要在application.yml中指明mapping.xml檔案的位置, 2.將sql寫到mapping配置檔案中注意:配置版、通用mapper版、配置檔案版,這三版可以混合使用,