Mybatis-Helloword
生活随笔
收集整理的這篇文章主要介紹了
Mybatis-Helloword
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
文章目錄
- 環(huán)境搭建
- 導(dǎo)包
- 寫配置
- 全局配置文件
- dao接口的實(shí)現(xiàn)文件
- 測(cè)試
環(huán)境搭建
package com.jh.bean;public class Employee {private Integer id;private String empName;private String email;private String gender; package com.jh.dao;import com.jh.bean.Employee;public interface EmployeeDao {//按照員工id查詢員工public Employee getEmpByid(Integer id); }導(dǎo)包
寫配置
全局配置文件
指導(dǎo)mybatis如何正確運(yùn)行,比如,連接向哪個(gè)數(shù)據(jù)庫(kù)
dao接口的實(shí)現(xiàn)文件
編寫每個(gè)方法都是如何向數(shù)據(jù)庫(kù)發(fā)送sql語(yǔ)句的,如何執(zhí)行。。。
<!-- namespace,名稱空間:寫接口的全類名,相當(dāng)于告訴Mybatis這個(gè)配置文件是實(shí)現(xiàn)哪個(gè)接口的 --> <mapper namespace="com.jh.dao.EmployeeDao"><!-- public Employee getEmpByid(Integer id); --> <!-- select,用來(lái)定義一個(gè)查詢操作 id:方法名,相當(dāng)于這個(gè)配置是對(duì)某個(gè)方法的實(shí)現(xiàn) resultType:指定方法運(yùn)行后的返回值類型(查詢操作必須指定的)#{屬性名}:代表取出傳遞過(guò)來(lái)的某個(gè)參數(shù)的值--><select id="getEmpByid" resultType="com.jh.bean.Employee">select * from t_employee where id = #{id}</select></mapper>我們寫的dao接口的實(shí)現(xiàn)文件,mybatis默認(rèn)是不知道的,需要在全局配置文件中注冊(cè)
<!-- 引入自己編寫的每一個(gè)接口的實(shí)現(xiàn)文件 --><mappers><!--resource 表示從類路徑下找資源 --><mapper resource="EmployeeDao.xml"/></mappers>注意:
測(cè)試
@Testpublic void test() throws IOException{/*1.根據(jù)全局配置文件創(chuàng)建出一個(gè)sqlSessionFactory* sqlSessionFactory:是sqlSession工廠,負(fù)責(zé)創(chuàng)建sqlSession對(duì)象;* sqlSession:sql會(huì)話(和數(shù)據(jù)庫(kù)的一次會(huì)話)*/String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//4.調(diào)用之前的方法Employee employee;//2.獲取和數(shù)據(jù)庫(kù)的一次會(huì)話SqlSession openSession = sqlSessionFactory.openSession();try { //3.使用sqlSession操作數(shù)據(jù)庫(kù),獲取dao接口的實(shí)現(xiàn)EmployeeDao employeeDao = openSession.getMapper(EmployeeDao.class);employee = employeeDao.getEmpByid(1);} finally{openSession.close();}System.out.println(employee);}總結(jié)
以上是生活随笔為你收集整理的Mybatis-Helloword的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: SpringMVC-RestfulCRU
- 下一篇: 操作系统期末复习知识点