mybaits二:通过接口类,查询数据
生活随笔
收集整理的這篇文章主要介紹了
mybaits二:通过接口类,查询数据
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
定義bean,對應數據庫中的表
package com.atChina.bean;public class Employee {private Integer deptno;private String dname;private String loc;public int getDeptno() {return deptno;}public void setDeptno(int deptno) {this.deptno = deptno;}public String getDname() {return dname;}public void setDname(String dname) {this.dname = dname;}public String getLoc() {return loc;}@Overridepublic String toString() {return "Employee [deptno=" + deptno + ", dname=" + dname + ", loc="+ loc + "]";}public void setLoc(String loc) {this.loc = loc;} }定義接口類
package com.atChina.dao;import com.atChina.bean.Employee;public interface EmployeeMapper {public Employee getEmployeeById(Integer depno); }sql映射文件(EmployeeMapper.xml):sql映射文件的namespace,id要與接口類保持一致.
? SqlSession和Connection一樣都是非線程安全。
<?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不能隨便自定義了,應該是接口類的全限定名 --> <mapper namespace="com.atChina.dao.EmployeeMapper"><!-- id:唯一標識 ,應該是接口類中的抽象方法名resultType: 返回值類型#{deptno}:參數 --><selectid="getEmployeeById" resultType="com.atChina.bean.Employee">select * from DEPTTEST where deptno = #{deptno}</select> </mapper>全局配置文件??
<?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"><propertyname="driver"value="oracle.jdbc.OracleDriver" /><propertyname="url"value="jdbc:oracle:thin:@localhost:1521:orcl" /><propertyname="username"value="scott" /><propertyname="password"value="123456" /></dataSource></environment></environments><!-- 把sql映射文件(EmployeeMapper.xml)一定要注冊到全局配置文件(mybatis-config.xml)中 --><mappers><mapper resource="EmployeeMapper.xml" /></mappers> </configuration>執行sql,測試代碼:?
@Testpublic void test2() throws IOException {String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession openSession = sqlSessionFactory.openSession();try{// 命名空間.id,這樣別的配置文件里有同名的id,程序也不報錯EmployeeMapper em = openSession.getMapper(EmployeeMapper.class);// 會為接口自動創建一個代理對象,代理對象去執行增刪改查方法System.out.println(em.getClass()); // 動態代理類Employee ee = em.getEmployeeById(10);System.out.println(ee);}finally{// 關閉openSession.close();}}?
總結
以上是生活随笔為你收集整理的mybaits二:通过接口类,查询数据的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mybaits一:初步认识mybatis
- 下一篇: spring21:Aspectj实现后置