1. 程式人生 > >Mybatis基礎(2)

Mybatis基礎(2)

.MyBatis 介面繫結方案及多引數傳遞

使用方法:

1.在myBatis.xml中加入package標籤,包名必需和mapper.xml檔案的包相同

<mappers>
        <!-- <mapper resource="com/bank/mapper/accountMapper.xml"/>
        <mapper resource="com/bank/mapper/LogMappery.xml"/> -->
        <package name="com.bank.mapper"/>
    </mappers
>

2.在com.bank.mapper下建立一個介面

public interface LogMappery {
    List<Log> selectAll();
}

3.建立一個LogMappery.xml檔案,檔名必需和介面名一樣,id和方法名一樣

<mapper namespace="com.bank.mapper">
          <select id="selectAll" resultType="account">
              select * from account
          
</select>
</mapper>

4.使用方法

public class TestMyBaits {
    public static void main(String[] args) throws IOException {
        InputStream is=Resources.getResourceAsStream("myBatis.xml");
        SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(is);
        SqlSession session
=factory.openSession(); LogMappery logMappery=session.getMapper(LogMappery.class); List<Log> list=logMappery.selectAll(); for (Log l : list) { System.out.println(l); } } }

建立帶引數的查詢方法:(多引數時不用寫parameterType)

介面中:

List<Log> selectPage(int pageStart,int pageSize);

mapper.xml中:

    <select id="selectPage" resultType="log">
        select * from log limit #{0},#{1}
    </select>
   <!-- #{}中使用0,1,2 或param1,param2 -->

使用註解方式 :

     List<Log> selectPage(@Param("pageStart")int pageStart,@Param("pageSize")int pageSize);

  myBaits底層將引數轉化為map , @Param("內容"),內容為key,傳入引數為value;

    <select id="selectPage" resultType="log">
        select * from log limit #{pageStart},#{pageSize}
    </select>