1. 程式人生 > 實用技巧 >MyBatis入門篇

MyBatis入門篇

一.入門步驟:

1.開啟IDEA,建立maven工程(或者springboot工程),為了便於測試,我使用springboot工程
2.開啟pom檔案,匯入MySQL座標(注意MySQL版本,後面版本驅動變了),匯入mybatis座標
3.建庫建表
4.建立實體類
5.編寫查詢介面
6.配置mybatis配置,在sql.xml檔案中書寫sql
7.測試

二.具體操作

1.建立一個springboot模組,如圖

2.匯入座標

                <dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.48</version>
			<!--如果不寫上mysql版本,那麼在寫驅動的時候加上cj和超時時間-->
		</dependency>
                <dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.4.5</version>
		</dependency>

3.建庫建表

create springbootdb;create springbootdb;
USE springbootdb;
DROP TABLE IF EXISTS user;
CREATE TABLE user (
  id bigint(20) NOT NULL COMMENT '主鍵ID',
  name varchar(30) DEFAULT NULL COMMENT '姓名',
  age int(11) DEFAULT NULL COMMENT '年齡',
  email varchar(50) DEFAULT NULL COMMENT '郵箱',
  PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

4.建立實體類

public class User {
    private int id;
    private String name;
    private int age;
    private String email;
//get和set方法以及toString,便於測試
}

5.書寫查詢介面

public interface UserDao {

    List<User> findAll();
}

6.配置mybatis環境以及sql對映檔案

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--配置mybatis的環境-->
    <environments default="mysql">
        <!--配置mysql環境-->
        <environment id="mysql">
            <!--配置事務型別-->
            <transactionManager type="JDBC"></transactionManager>
            <!--配置連線池資訊-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/springbootdb"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <!--告知mybatis對映檔案位置-->
    <mappers>
        <mapper resource="com/xjz/lw/dao/UserDao.xml"></mapper>
    </mappers>
    
</configuration>

sql對映檔案,但是要注意sql對映檔案要和查詢介面的路徑要一致才可以

<?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.xjz.lw.dao.UserDao">
    <select id="findAll" resultType="com.xjz.lw.pojo.User">
        select * from user
    </select>

</mapper>

7.測試

        @Test
	void contextLoads() {
		try {
			InputStream is = Resources.getResourceAsStream("MybatisConfig.xml");
			SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
			SqlSessionFactory factory = builder.build(is);
			SqlSession session = factory.openSession();
			UserDao mapper = session.getMapper(UserDao.class);
			List<User> users = mapper.findAll();
			for(User u: users){
				System.out.println(u.toString());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

      輸出結果
User{id=1, name='Jone', age=18, email='[email protected]'}
User{id=2, name='Jack', age=20, email='[email protected]'}
User{id=3, name='Tom', age=28, email='[email protected]'}
User{id=4, name='Sandy', age=21, email='[email protected]'}
User{id=5, name='Billie', age=24, email='[email protected]'}