使用maven創建項目配置mybatis


一個mybatis的構建需要六部分:依賴包的導入,創建pojo,配置核心配置文件,配置映射文件,創建mybatis的工具類,測試

1.首先在myeclipse中創建一個maven項目,然后導入依賴包

<dependencies>
        <!-- mybatis核心包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.8</version>
        </dependency>
        <!-- jdbc的包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.32</version>
        </dependency>
        <!-- 查看日志文件的log4j包 -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.12</version>
        </dependency>
        <!-- 測試用的依賴包 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
        </dependency>
    </dependencies>

2.創建一個Student的pojo

注意:如果數據表字段是int類型的數據,建議pojo中使用Integer來修飾,因為int的默認值是0,不是null,可能在進行sql操作時出錯,

private Integer id;

    private String sname;

    private String address;

    private String sex;

    private Integer tid;

    public Integer getId() {
        return id;
    }

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

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname == null ? null : sname.trim();
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address == null ? null : address.trim();
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex == null ? null : sex.trim();
    }

    public Integer getTid() {
        return tid;
    }

    public void setTid(Integer tid) {
        this.tid = tid;
    }

    @Override
    public String toString() {
        return "Student [id=" + id + ", sname=" + sname + ", address=" + address + ", sex=" + sex + ", tid=" + tid
                + "]";
    }

3.創建mybatis的核心配置文件

mybatis的核心配置文件並不像hibernate一樣必須使用特定的名稱,這里我創建的是mybatis.xml

在對jdbc的連接配置時,可以通過properties文件,也可以不使用,如果使用的話,需要在標簽的最上面使用<properties resource="db.properties"></properties>來引入自己配置的properties文件,並在下面通過${}來引用properties中的屬性名

<?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="db.properties"></properties>
    <!-- 接收數據庫的數據源(元數據) default默認讀取以下的配置 -->
    <environments default="mysql">
        <!-- 針對不同的數據庫來配置元數據 id:區分元數據 -->
        <!-- 配置MySQL -->
        <environment id="mysql">
            <!-- 事務的管理交給jdbc管理 -->
            <transactionManager type="jdbc" />
            <!-- 不使用properties手動配置
                <dataSource type="pooled">
                    <property name="driver" value="com.mysql.jdbc.Driver" />
                    <property name="url" value="jdbc:mysql://localhost:3306/test" />
                    <property name="username" value="root" />
                    <property name="password" value="root" />
                </dataSource> 
            -->
            <!-- 使用properties加載properties中的屬性 -->
            <dataSource type="pooled">
                <property name="driver" value="${driver}" />
                <property name="url" value="${url}" />
                <property name="username" value="${username}" />
                <property name="password" value="${password}" />
            </dataSource>
        </environment>

        <!-- 配置Oracle -->
        <environment id="oracle">
            <!-- 事務的管理交給odbc管理 -->
            <transactionManager type="jdbc" />
            <dataSource type="pooled">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:oracle:thin:@localhost:1521/test" />
                <property name="username" value="scott" />
                <property name="password" value="123456" />
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="StudentMapper.xml" />
    </mappers>
</configuration>

 

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
username=root
password=root

 

4.創建映射文件

<?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" >
<!-- namespace命名必須是唯一的,前期可以直接以所映射的pojo類的唯一路徑來命名 -->
<mapper namespace="com.oracle.pojo.Student">
    <!-- 
        mybaits通過自己手動寫sql語句來對數據庫進行操作,select就是查詢操作
        同樣有update,delete,insert
        id:標識符,測試時調用的標識符來調用sql語句,相當於方法名
        resultType:返回值類型
        parameterType:傳入的參數類型
        如果是引用數據類型的話,需要傳入完整的路徑.如:java.lang.String以及對象com.oralc.pojo.Student
        在下方的條件需要以#{}來占位,如果傳入類型是對象型,需要與對象的屬性名一致
     -->
    <select id="findStudentById" resultType="com.oracle.pojo.Student" parameterType="int">
        select * from student where id=#{id}
    </select>
    <select id="findAll" resultType="com.oracle.pojo.Student">
        select * from student
    </select>
</mapper>

5.創建mybatis的工具類

這里使用ThreadLocal類,用來綁定線程,當程序執行時作為一個線程,無論執行到dao層或是其他層,從該線程中獲取的session都是同一個session

public class MybatisUtil {
    private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            // 讀取mybatis核心配置文件
            Reader reader = Resources.getResourceAsReader("mybatis.xml");
            // 創建會話工廠
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static SqlSession getSession() {
        // 獲取會話
        SqlSession sqlSession = threadLocal.get();
        if (sqlSession == null) {
            // 從會話工廠獲取session
            sqlSession = sqlSessionFactory.openSession();
            // 綁定會話工廠
            threadLocal.set(sqlSession);
        }
        return sqlSession;
    }

    public static void close() {
        SqlSession sqlSession = threadLocal.get();
        if (sqlSession != null) {
            sqlSession.close();
        }
    }
}

 

6.測試

public class Test {
    private SqlSession session = null;

    @Before
    public void before() {
        //獲取會話
        session = MybatisUtil.getSession();
    }

    @org.junit.Test
    public void add() {
        /**
         * 從會話中調用映射文件中的sql語句,為了防止不同的映射文件標識符重復,通過namespace.標識符來調用
         * 如果后面有參數的話,在后面添加參數
         */
        Student student = session.selectOne("com.oracle.pojo.Student.findStudentById",1);
        System.out.println(student);
        List<Student> studentList = session.selectList("com.oracle.pojo.Student.findAll");
        for (Student student2 : studentList) {
            System.out.println(student2);
        }
    }

    @After
    public void after() {
        session.commit();
        MybatisUtil.close();
    }
}

測試結果

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM