1. 程式人生 > 實用技巧 >Mybatis配置並實現(XML方式)

Mybatis配置並實現(XML方式)

Mybatis配置並實現(XML方式)

  1. idea中建立一個maven專案

  2. 在pom檔案中匯入下面的依賴

    <!--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>8.0.18</version>
        </dependency>
        <!--log4j日誌包-->
        <dependency>
          <groupId>log4j</groupId>
          <artifactId>log4j</artifactId>
          <version>1.2.17</version>
        </dependency>
    
  3. 建立一個java原始檔夾和resources資原始檔夾並準備好mybatis配置檔案mybaits.xml和資料庫檔案db.properties

mybaits.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="db.properties"></properties>
    <!--別名的配置,可以不用-->
    <typeAliases>
        <package name="cn.cqy.domain"></package>
    </typeAliases>
    <!--配置環境,可以多個,這裡要設定一個預設使用的環境-->
    <environments default="dev">
        <!--配置環境名,唯一一個id名稱-->
        <environment id="dev">
            <!--事務管理   type:JDBC(支援事務)/MANAGED(什麼都不做)-->
            <transactionManager type="JDBC"></transactionManager>
            <!--資料來源, 連線池  type(POOLED):MyBatis自帶的連線池-->
            <dataSource type="POOLED">
                <property name="driver" value="${driverClassName}"></property>
                <property name="url" value="${url}"></property>
                <property name="username" value="${username}"></property>
                <property name="password" value="${password}"></property>
            </dataSource>
        </environment>
    </environments>

    <!--這個mappers代表的是相應的ORM對映檔案 這裡先準備好了-->
    <mappers>
        <mapper resource="cn/cqy/mapper/StudentMapper.xml"></mapper>
    </mappers>
</configuration>

db.properties

driverClassName=com.mysql.jdbc.Driver 
url=jdbc:mysql://localhost:3306/prc?userUnicode=true&characterEncoding=utf8&serverTimezone=UTC
username=root
password=root
  1. 資料庫準備,略。

  2. 準備相應的物件

    建立一個Student物件,和資料庫的表對應

    public class Student {
        private String s_id;
        private String s_name;
        private String s_birth;
        private String s_sex;
    
        public Student() {}
        
        //getter,setter 方法省略
    }
    
  3. mapper的準備 ,建立一個mapper資料夾,並在內建立一個StudentMapper介面

    public interface StudentMapper {
    	//查詢學生表全部資訊
        public List<Student> selectAll();
    	//根據姓名查詢學生
        public Student selectByName(String name);
    	//插入一條學生資訊
        public void insertOne(Student stu);
    	//根據姓名刪除一條學生資訊
        public void deleteByName(String name);
    	//根據姓名修改一條學生資訊
        public void updateByName(Student stu);
    
    }
    
  4. 在resoures資原始檔夾下建立和mapper資料夾路徑相同的資料夾

    然後建立對映檔案StudentMapper.xml

    <?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="cn.cqy.mapper.StudentMapper">
        <!--定義sql的標籤的id,需要和對應介面的方法名一致 resultType的型別在沒有配置別名的情況下,應該是POJO類的全限定名 如cn.cqy.domain.Student-->
        <select id="selectAll" resultType="Student">
            SELECT s_id,s_name,s_birth,s_sex FROM student
        </select>
        <!--引數型別為自定型別沒有別名,輸入型別全限定名,為Java型別時輸入其對應對映名 如 long:大Long  _long:小long (具體的對應請參見文件)-->
        <select id="selectByName" resultType="Student" parameterType="String">
            SELECT s_id,s_name,s_birth,s_sex FROM student
            WHERE s_name = #{name}
        </select>
    
        <insert id="insertOne" parameterType="Student">
            INSERT INTO student (s_id,s_name,s_birth,s_sex) VALUES (#{s_id},#{s_name},#{s_birth},#{s_sex})
        </insert>
    
        <delete id="deleteByName" parameterType="String">
            DELETE FROM student where s_name = #{s_name}
        </delete>
    
        <update id="updateByName" parameterType="Student" >
            UPDATE student SET s_birth = #{s_birth},s_sex = #{s_sex} WHERE s_name = #{s_name}
        </update>
    </mapper>
    
  5. 抽取出一個MybatisUtil工具類

    public class MybatisUtil {
        private static SqlSessionFactory sqlSessionFactory;
    	//靜態程式碼塊:在使用的時候先執行,並且執行一次
        static {
            try {
                InputStream is = Resources.getResourceAsStream("mybatis.xml");
                SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
                //建立一個工廠例項(載入了我們的配置檔案)
                sqlSessionFactory = builder.build(is);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    	/**
    	 *拿到了一個SqlSession物件
    	 */
        public static SqlSession getSqlSession() {
            return sqlSessionFactory.openSession();
        }
    
        public static void closeSqlSession(SqlSession sqlSession) {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }
    
  6. 編寫測試類

    public class SqlTest {
        @Test
        public void testSelectAll() {
            //通過工具類獲得SqlSession物件
            SqlSession sqlSession = MybatisUtil.getSqlSession();
            //獲取到繫結到SqlSession的POJO類對應的對映
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            //通過對映呼叫查詢方法
            List<Student> students = studentMapper.selectAll();
            //關閉SqlSession
            sqlSession.close();
            for (Student student : students) {
                System.out.println(student);
            }
        }
    
        @Test
        public void testSelectByName() {
            SqlSession sqlSession = MybatisUtil.getSqlSession();
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            Student stu = studentMapper.selectByName("吳蘭");
            sqlSession.close();
            System.out.println(stu);
        }
    
        @Test
        public void testInsertOne() {
            SqlSession sqlSession = MybatisUtil.getSqlSession();
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            Student stu = new Student();
            stu.setS_id("09");
            stu.setS_name("李水");
            stu.setS_birth("1988-08-22");
            stu.setS_sex("男");
            studentMapper.insertOne(stu);
            //增、刪、改需要提交事務,否則不會修改
            sqlSession.commit();
            sqlSession.close();
        }
    
        @Test
        public void testDeleteByName() {
            SqlSession sqlSession = MybatisUtil.getSqlSession();
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            studentMapper.deleteByName("李水");
            sqlSession.commit();
            sqlSession.close();
        }
    
        @Test
        public void testUpdateByName() {
            SqlSession sqlSession = MybatisUtil.getSqlSession();
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            Student stu = new Student();
            stu.setS_name("李水");
            stu.setS_birth("1999-01-22");
            stu.setS_sex("女");
            studentMapper.updateByName(stu);
            sqlSession.commit();
            sqlSession.close();
        }
    }
    
  7. 測試查詢結果