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版、配置檔案版,這三版可以混合使用,