久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

Java框架MyBatis接口編程過(guò)程解析

瀏覽:111日期:2022-09-05 10:43:18

要求:

1.配置文件的namespace名稱空間指定為接口的全類名

2.配置文件中的id唯一標(biāo)識(shí)與接口中的方法對(duì)應(yīng)(返回值類型對(duì)應(yīng),方法名對(duì)應(yīng),參數(shù)個(gè)數(shù)和類型對(duì)應(yīng))

接口代碼:

package com.bird.mybatis.dao;import com.bird.mybatis.bean.Employee;public interface EmployeeMapper { public Employee getEmpById(Integer id); }

對(duì)應(yīng)配置文件代碼:

<?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:名稱空間(若使用接口式編程,與EmployeeMapper接口全類名一致) id:唯一標(biāo)識(shí)(與接口中的方法名對(duì)應(yīng)) resultType:返回值類型(與對(duì)應(yīng)方法的返回值對(duì)應(yīng)) #{id}:從傳遞過(guò)來(lái)的參數(shù)中取出id值 --><mapper namespace='com.bird.mybatis.dao.EmployeeMapper'> <select resultType='com.bird.mybatis.bean.Employee'> select id,last_name lastName,gender,email from tbl_employee where id = #{id} </select></mapper>

測(cè)試代碼:

/** * MyBatis接口編程 * @throws IOException */ @Test void test2() throws IOException { //獲取sqlSessionFactory對(duì)象 SqlSessionFactory ssf = getSqlSessionFactory(); //獲取sqlSession對(duì)象 SqlSession openSession = ssf.openSession(); try { //獲取接口的實(shí)現(xiàn)類對(duì)象 EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class); Employee empById = mapper.getEmpById(1); System.out.println(empById); }finally { openSession.close(); } } /** * 獲取sqlSessionFactory對(duì)象 * @throws IOException */ public static SqlSessionFactory getSqlSessionFactory() throws IOException { String resource = 'mybatis-config.xml'; InputStream is = Resources.getResourceAsStream(resource); return new SqlSessionFactoryBuilder().build(is); }

總結(jié):

1.接口編程:

原生接口: Dao ===> DaoImpl

MyBatis: Dao ===> Mapper.xml

2. SqlSession代表與數(shù)據(jù)庫(kù)的一次會(huì)話,用完要關(guān)閉

3. SqlSession和Connection都是非線程安全的,所以每次都要獲取新的對(duì)象,而不能寫成成員變量

4.mapper接口沒有實(shí)現(xiàn)類,但是MyBatis生成代理對(duì)象

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。

標(biāo)簽: Java
相關(guān)文章:
主站蜘蛛池模板: 浦东新区| 中方县| 托克托县| 安顺市| 昌图县| 奈曼旗| 巧家县| 松滋市| 宁城县| 南丹县| 黄骅市| 涪陵区| 台东市| 文成县| 鹤峰县| 洪雅县| 通州市| 南城县| 南溪县| 兴业县| 昌都县| 曲麻莱县| 扎鲁特旗| 榕江县| 银川市| 田东县| 鹤峰县| 寿宁县| 如皋市| 高雄市| 嘉黎县| 汕头市| 巴彦淖尔市| 通道| 井研县| 义马市| 平凉市| 冀州市| 栾川县| 黔东| 肥西县|