天天看點

Mybatis持久層架構環境搭建,加簡單查詢,插入資料

Mybatis持久層架構環境搭建

隸屬Apache組織的半自動架構(相對于hibernate) Mybatis原理圖:

Mybatis持久層架構環境搭建,加簡單查詢,插入資料

建立一個普通的java工程

導入mybatis和mysql連接配接資料庫所需的包:

mybatis-3.2.8.jar

mysql-connector-java-5.1.34

1.配置mysql資料庫    jdbc.username填你自己的資料庫使用者名  jdbc.password填你自己的資料庫密碼

建立resource包  再包下建立file 名為jdbc.properties

jdbc.properties:

jdbc.driver=com.mysql.jdbc.Driver

jdbc.url=jdbc:mysql://localhost:3306/mysql_demo

jdbc.username=

jdbc.password=

2.建立要映射的對象 student表結構:

Mybatis持久層架構環境搭建,加簡單查詢,插入資料

這裡要根據自己資料庫表的結構來建立實體對象 : 建立Student實體類:

public class Student {

    private Integer Sid;

    private String Sname;

    private String Ssex;

    private Integer Sage;

    private Integer Tid;

    public Integer getSid() {

        return Sid;

    }

    public void setSid(Integer sid) {

        Sid = sid;

    }

    public String getSname() {

        return Sname;

    }

    public void setSname(String sname) {

        Sname = sname;

    }

    public String getSsex() {

        return Ssex;

    }

    public void setSsex(String ssex) {

        Ssex = ssex;

    }

    public Integer getSage() {

        return Sage;

    }

    public void setSage(Integer sage) {

        Sage = sage;

    }

    public Integer getTid() {

        return Tid;

    }

    public void setTid(Integer tid) {

        Tid = tid;

    }

}

3.建立dao包 再建StudentMapper接口 public interface StudentMapper {

        //插入了一條資料  傳回一   插了兩條就傳回二

    public int insertStudent(Student student)throws Exception;

    //查詢一位學生

    public Student selectOneById(int id) throws Exception;

    //查詢所有學生清單

    List<Student> selectAllStudent()throws Exception;

}

4.mybatis的配置檔案  設定mybatis,對象要映射到什麼地方去

在resource包建立file  名為mybatis-cfg.xml

mybatis-cfg.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="resource/jdbc.properties"/>

    <!--default可以随便寫的-->

    <environments default="mybatis-demo">

        <environment id="mybatis-demo">

            <!--type是用什麼方式管理事務,假如用了Spring架構管理事務,就填Spring-->

            <transactionManager type="JDBC"></transactionManager>

            <!--這裡是用了自帶的連接配接池-->

            <dataSource type="POOLED">

                <!--加載了配置檔案之後,要取值-->

                <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>

   <!--聲明mapper的位置    -->

    <mappers>

        <!--聲明mybatis要掃描那個包下面的全部mapper-->

        <package name="dao"/>

    </mappers>

</configuration>

5.在dao包建立file  名為StudentMapper.xml

寫資料庫和對象的映射所需mapper   和sql語句

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0"

        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

        <!--資料庫和對象的映射所需mapper-->

<mapper namespace="dao.StudentMapper">

    <!--type是告訴resultMap  要映射到哪一個javabean-->

    <resultMap id="studentMapper" type="entity.Student">

        <!--column是資料庫屬性ID對應的是property是實體對象屬性ID-->

        <!--<id >  這個是寫主鍵的-->

        <id  property="Sid"  column="Sid" />

        <result property="Sname" column="Sname" />

        <result property="Ssex" column="Ssex" />

        <result property="Tid" column="Tid" />

        <result property="Sage" column="SageNum" />

    </resultMap>

    <!--編寫StudentMapper接口裡面所需要實作的方法-->

    <insert id="insertStudent"  parameterType="entity.Student">

        INSERT INTO student (Sid,Sname,Ssex,Tid,SageNum) VALUES (#{Sid},#{Sname},#{Ssex},#{Tid},#{Sage})

    </insert>

</mapper>

6.在主函數寫

public class Main {

    public static void main(String[] args) throws Exception {

            //加載配置檔案  通過io流加載xml檔案

         InputStream in= Main.class.getResourceAsStream("resource/mybatis-cfg.xml");

        SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(in);

        SqlSession session= factory.openSession();

        StudentMapper mapper=session.getMapper(StudentMapper.class);

        //建立需要插入的Student對象

        Student student=new Student();

        student.setSid(10);

        student.setSage(12);

        student.setTid(1);

        student.setSsex("男");

        student.setSname("haha");

        mapper.insertStudent(student);

        //需要session.commit  不然資料庫是不會發生改變的

        session.commit();

        //關閉會話   避免占用資源

        session.close();

    }

}

demo目錄結構:

Mybatis持久層架構環境搭建,加簡單查詢,插入資料

執行程式前資料庫studnet表:

Mybatis持久層架構環境搭建,加簡單查詢,插入資料

執行程式後  student表:

Mybatis持久層架構環境搭建,加簡單查詢,插入資料

資料成功插入  可喜可賀O(∩_∩)O

因為mybatis已經搭建好了  是以我們執行查詢操作就簡答多了

倘若我們想要執行查詢操作:

1.修改StudentMapper.xml:

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0"

        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

        <!--資料庫和對象的映射所需mapper-->

<mapper namespace="dao.StudentMapper">

    <!--type是告訴resultMap  要映射到哪一個javabean-->

    <resultMap id="studentMapper" type="entity.Student">

        <!--column是資料庫屬性ID對應的是property是實體對象屬性ID-->

        <!--<id >  這個是寫主鍵的-->

        <id  property="Sid"  column="Sid" />

        <result property="Sname" column="Sname" />

        <result property="Ssex" column="Ssex" />

        <result property="Tid" column="Tid" />

        <result property="Sage" column="SageNum" />

    </resultMap>

    <!--編寫StudentMapper接口裡面所需要實作的insertStudent方法-->

    <insert id="insertStudent"  parameterType="entity.Student">

        INSERT INTO student (Sid,Sname,Ssex,Tid,SageNum) VALUES (#{Sid},#{Sname},#{Ssex},#{Tid},#{Sage})

    </insert>

    <!--編寫StudentMapper接口裡面所需要實作的selectOneById方法-->

    <!--根據studentMapper來映射-->

    <!--Sid=#{id}  花括号裡面填id是因為StudentMapper接口裡面所需要實作的selectOneById方法的參數是id-->

    <select id="selectOneById" resultMap="studentMapper">

        SELECT * FROM student WHERE Sid=#{id}

    </select>

</mapper>

2.修改主函數:

public class Main {

    public static void main(String[] args) throws Exception {

            //加載配置檔案  通過io流加載xml檔案

         InputStream in= Main.class.getResourceAsStream("resource/mybatis-cfg.xml");

        SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(in);

        SqlSession session= factory.openSession();

        StudentMapper mapper=session.getMapper(StudentMapper.class);

        //建立需要插入的Student對象

        Student student=new Student();

        //需要session.commit  不然資料庫是不會發生改變的

        //查詢student表Sid為5号的人

     student=   mapper.selectOneById(5);

        session.commit();

        //關閉會話   避免占用資源

        session.close();

    }

}

自行debug  會發現已經把5号student對象查詢成功

倘若我們不查詢單個人,我們要查詢list集合

1.修改StudentMapper.xml

StudentMapper.xml:

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0"

        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

        <!--資料庫和對象的映射所需mapper-->

<mapper namespace="dao.StudentMapper">

    <!--type是告訴resultMap  要映射到哪一個javabean-->

    <resultMap id="studentMapper" type="entity.Student">

        <!--column是資料庫屬性ID對應的是property是實體對象屬性ID-->

        <!--<id >  這個是寫主鍵的-->

        <id  property="Sid"  column="Sid" />

        <result property="Sname" column="Sname" />

        <result property="Ssex" column="Ssex" />

        <result property="Tid" column="Tid" />

        <result property="Sage" column="SageNum" />

    </resultMap>

    <!--編寫StudentMapper接口裡面所需要實作的insertStudent方法-->

    <insert id="insertStudent"  parameterType="entity.Student">

        INSERT INTO student (Sid,Sname,Ssex,Tid,SageNum) VALUES (#{Sid},#{Sname},#{Ssex},#{Tid},#{Sage})

    </insert>

    <!--編寫StudentMapper接口裡面所需要實作的selectOneById方法-->

    <!--根據studentMapper來映射-->

    <!--Sid=#{id}  花括号裡面填id是因為StudentMapper接口裡面所需要實作的selectOneById方法的參數是id-->

    <select id="selectOneById" resultMap="studentMapper">

        SELECT * FROM student WHERE Sid=#{id}

    </select>

    <!--查詢多人清單  傳回list集合-->

    <select id="selectAllStudent" resultMap="studentMapper" >

         SELECT * FROM student

    </select>

</mapper>

2.修改主函數:

public class Main {

    public static void main(String[] args) throws Exception {

            //加載配置檔案  通過io流加載xml檔案

         InputStream in= Main.class.getResourceAsStream("resource/mybatis-cfg.xml");

        SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(in);

        SqlSession session= factory.openSession();

        StudentMapper mapper=session.getMapper(StudentMapper.class);

        Student student=new Student();

        //需要session.commit  不然資料庫是不會發生改變的

        //查詢student表Sid為5号的人

        //mybatis自動把查詢出的資料,自動映射,封裝成對象  大大節省了時間

        //現在看來   寫StudentMapper  和StudentMapper.xml都很費時間  在後面,我會在部落格裡說如何自動生成Mapper和Mapper.xml

        List<Student> studentList=mapper.selectAllStudent();

        session.commit();

        //關閉會話   避免占用資源

        session.close();

    }

}

自行debug執行程式  會發現查詢成功了 完結撒花O(∩_∩)O

繼續閱讀