1. 程式人生 > >MyBatis入門(三)---介面+註解的方式

MyBatis入門(三)---介面+註解的方式

一、使用meavn建立專案,並匯入相應的包

<?xml version="1.0" encoding="UTF-8"?>
<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>me.mybatis</groupId> <artifactId>mybatis-study1</artifactId> <version>1.0-SNAPSHOT</version> <properties> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target
>
</properties> <dependencies> <!-- mybatis核心包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.6</version> </dependency> <!-- mysql驅動包 -->
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.46</version> </dependency> <!-- junit測試包 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!-- 日誌檔案管理包 --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.12</version> </dependency> </dependencies> </project>

二、建立資料庫和表,針對MySQL資料庫

create database mybatis;
use mybatis;
CREATE TABLE `User` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
);
INSERT INTO `User` VALUES (1, 'test', 18);
INSERT INTO `User` VALUES (2, '張三', 25);

三、新增Mybatis的配置檔案

1、在src/main/resources下建立mysql.properties檔案,程式碼如下

properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.0.111:3306/mybatis
jdbc.username=root
jdbc.password=root

2、在src/main/resources下建立mybatis-config.xml檔案,程式碼如下

<?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>
    <properties resource="mysql.properties"/>
    <settings>
        <!--全域性性設定懶載入。如果設為‘false’,則所有相關聯的都會被初始化載入,預設值為false-->
        <setting name="lazyLoadingEnabled" value="true"/>
        <!--當設定為‘true’的時候,懶載入的物件可能被任何懶屬性全部載入。否則,每個屬性都按需載入。預設值為true-->
        <setting name="aggressiveLazyLoading" value="false"/>
    </settings>
    <!--對事務的管理和連線池的配置-->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED"><!--POOLED:使用Mybatis自帶的資料庫連線池來管理資料庫連線-->
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
</configuration>

四、建立資料庫表對應的實體類

在src/java下新建一個包me.mybatis.entity,然後在該包下建立一個java檔案,檔名User,增加程式碼如下 :

package me.mybatis.entity;

/**
 * User 表所對應的實體類
 */
public class User {
    //實體類的屬性和表的欄位名稱一一對應
    private int id;
    private String name;
    private int age;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
    }
}

五、建立介面並添加註解

在src/java下新建一個包me.mybatis.dao,然後在該包下建立一個java介面檔案,檔名IUser,增加程式碼如下 :

package me.mybatis.dao;

import me.mybatis.entity.User;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

public interface IUser {
    @Select("select * from User where id = #{id}")
    public User getUserById(int id);

    @Select("select * from User")
    public List<User> getUserList();

    @Insert("insert into User (name, age) values (#{name}, #{age})")
    public void insertUser(User user);

    @Update("update User set name = #{name}, age = #{age} where id = #{id}")
    public void updateUser(User user);

    @Delete("delete from User where id = #{id}")
    public void deleteUser(int userId);
}

User.java 對應的 XML 配置檔案UserMapper.xml 可以省略,不用建立,

即:使用註解方式,不需要配置 SQL對映檔案 UserMapper.xml

六、編寫測試類

src/main/resources下建立一個資料夾mapper,在該資料夾下建立一個UserMapper.xml檔案,程式碼如下

package me.mybatis.test;

import me.mybatis.dao.IUser;
import me.mybatis.entity.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.Reader;
import java.util.List;

public class UserTest {

    private static SqlSessionFactory sqlSessionFactory;
    private static Reader reader;

    static {
        try {
            String resource = "mybatis-config.xml";
            reader = Resources.getResourceAsReader(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
            //使用註解時,不需要使用SQL對映檔案,但是需要在此新增介面類。
            sqlSessionFactory.getConfiguration().addMapper(IUser.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        // 使用者資料列表
        getUserList();
        // 插入資料
//        testInsert();

        // 更新使用者
//        testUpdate();

         //刪除資料
//        testDelete();
    }


    private static void getUserList() {
        SqlSession session = sqlSessionFactory.openSession();
        IUser iUser = session.getMapper(IUser.class);
        List<User> users = iUser.getUserList();
        for (User user : users){
            System.out.println(String.format("[%d, %s, %d]", user.getId(), user.getName(), user.getAge()));
        }
    }

    private static void testInsert() {
        SqlSession session = sqlSessionFactory.openSession();
        IUser iUser = session.getMapper(IUser.class);
        User user = new User();
        // 設定id和不設定id都一樣,自動增加
//        user.setId(10);
        user.setName("Lili");
        user.setAge(25);
        iUser.insertUser(user);
        // 一定要進行commit,否則操作失敗
        session.commit();
        getUserList();
    }

    private static void testUpdate() {
        SqlSession session = sqlSessionFactory.openSession();
        IUser iUser = session.getMapper(IUser.class);
        User user = iUser.getUserById(2);
        user.setName("Luxi");
        iUser.updateUser(user);
        session.commit();
        getUserList();
    }


    private static void testDelete() {
        SqlSession session = sqlSessionFactory.openSession();
        IUser iUser = session.getMapper(IUser.class);
        iUser.deleteUser(2);
        session.commit();
        getUserList();
    }
}