1. 程式人生 > >MyBatis 筆記(二)——XML vs 註解

MyBatis 筆記(二)——XML vs 註解

MyBatis 支援註解和 XML 兩種配置。這一節延續 MyBatis 筆記(一)繼續講。

1. 基於 XML 的配置

基於 XML 的配置其實和 MyBatis 筆記(一)幾乎是一樣的。先看最基礎的配置檔案:

<?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
>
<environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property
name="url" value="jdbc:mysql://127.0.0.1:3306/test?useSSL=true"/>
<property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <mappers> <!-- 基於XML配置檔案 -->
<mapper resource="edu/wzm/mybatis/mapping/PersonMapper.xml"/> </mappers> </configuration>

最後一行指向 XML 對映檔案,XML 對映檔案配置要執行的 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,namespace的值習慣上設定成包名+sql對映檔名,這樣就能夠保證namespace的值是唯一的
  例如:namespace="edu.wzm.mybatis.mapping.PersonMapper"(userMapper.xml檔案去除字尾)
-->
<mapper namespace="edu.wzm.mybatis.mapping.PersonMapper">
  <!--
    在select、insert、update、delete標籤中編寫查詢的SQL語句, 設定標籤的id屬性值必須是唯一的,不能夠重複。使用parameterType屬性
    指明查詢時,使用的引數型別。resultType屬性指明查詢返回的結果集型別,resultType="edu.wzm.mybatis.domain.Person"就表示將查詢
    結果封裝成一個Person類的物件返回,Person類就是person表所對應的實體類。
  -->

  <insert id="insert" parameterType="edu.wzm.mybatis.domain.Person">
    insert into person(name, age) values(#{name}, #{age})
  </insert>

  <select id="getById" resultType="edu.wzm.mybatis.domain.Person">
    select *
    from person
    where id = #{id}
  </select>

  <select id="getAll" resultType="edu.wzm.mybatis.domain.Person">
    select * from person;
  </select>

  <update id="update" parameterType="edu.wzm.mybatis.domain.Person">
    update person set age = #{age} where id = #{id}
  </update>

  <delete id="delete" parameterType="int">
    delete from person where id = #{id}
  </delete>
</mapper>

在用 MyBatis 呼叫這些 SQL 語句時,需要寫出 XML 的全路徑,同時加上每個 SQL 語句的 id 名:

public class PersonServices {

    public void add(){
        Person person = new Person("Alice", 30);
        SqlSession sqlSession = MyBatisUtils.getSqlSession(true);
        /**
         * 對映sql的標識字串。
         * edu.wzm.mybatis.mapping.PersonMapper是PersonMapper.xml中mapper標籤的namespace屬性的值,
         * insert是insert標籤的id屬性值,通過update標籤的id屬性值就可以找到要執行的SQL。
         */
        int result = sqlSession.insert("edu.wzm.mybatis.mapping.PersonMapper.insert", person);

        System.out.println(result);
        sqlSession.close();
    }

    public void getAll(){
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        List<Person> persons = sqlSession.selectList("edu.wzm.mybatis.mapping.PersonMapper.getAll");

        System.out.println(persons);

        sqlSession.close();
    }

    public void getById(){
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        Person person = sqlSession.selectOne("edu.wzm.mybatis.mapping.PersonMapper.getById", 1);

        System.out.println(person);

        sqlSession.close();
    }

    public void update(){
        Person person = new Person();
        person.setId(7);
        person.setAge(27);

        SqlSession sqlSession = MyBatisUtils.getSqlSession(true);
        int result = sqlSession.update("edu.wzm.mybatis.mapping.PersonMapper.update", person);

        System.out.println(result);

        sqlSession.close();
    }

    public void delete(){
        SqlSession sqlSession = MyBatisUtils.getSqlSession(true);
        int result = sqlSession.update("edu.wzm.mybatis.mapping.PersonMapper.delete", 6);
        System.out.println(result);

        sqlSession.close();
    }
}    

2. 基於註解的配置

這裡我們只看配置這部分,其他部分和 MyBatis 筆記(一)一樣。首先是最基礎的配置檔案:

<?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>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/test?useSSL=true"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <!-- 基於註解 -->
        <mapper class="edu.wzm.mybatis.mapping.PersonMapper"/>
    </mappers>
</configuration>

最後一行配置指向註解配置的 Mapping 對映檔案。這個對映檔案是 Java 的介面,每個方法上面會用註解配置 SQL 語句:

public interface PersonMapper {

    @Insert("insert into person(name, age) values(#{name}, #{age})")
    public int add(Person person);

    @Select("select * " +
            "from person " +
            "where id = #{id}")
    public Person getById(int id);

    @Select("select * from person")
    public List<Person> getAll();

    @Update("update person set age = #{age} where id = #{id}")
    public int update(Person person);

    @Delete("delete from person where id = #{id}")
    public int deleteById(int id);

}

在啟動 MyBatis 訪問資料庫時,也和 XML 不同。它不需要寫 XML 對映檔案的全路徑,直接指定介面名即可:

public class PersonServices {

    public void add(){
        Person person = new Person("Kim", 30);
        SqlSession sqlSession = MyBatisUtils.getSqlSession(true);
        PersonMapper mapper = sqlSession.getMapper(PersonMapper.class);
        int result = mapper.add(person);

        System.out.println(result);
        sqlSession.close();
    }

    public void getAll(){
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        PersonMapper mapper = sqlSession.getMapper(PersonMapper.class);
        List<Person> person = mapper.getAll();

        System.out.println(person);

        sqlSession.close();
    }

    public void getById(){
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        PersonMapper mapper = sqlSession.getMapper(PersonMapper.class);
        Person person = mapper.getById(1);

        System.out.println(person);

        sqlSession.close();
    }

    public void update(){
        SqlSession sqlSession = MyBatisUtils.getSqlSession(true);
        PersonMapper mapper = sqlSession.getMapper(PersonMapper.class);

        Person person = new Person();
        person.setId(6);
        person.setAge(50);
        int result = mapper.update(person);

        System.out.println(result);

        sqlSession.close();
    }

    public void delete(){
        SqlSession sqlSession = MyBatisUtils.getSqlSession(true);
        PersonMapper mapper = sqlSession.getMapper(PersonMapper.class);

        int result = mapper.deleteById(7);

        System.out.println(result);

        sqlSession.close();
    }
}