三、MyBatis 使用传统 Dao 开发方式
1.0 使用 Dao 的實(shí)現(xiàn)類,操作數(shù)據(jù)庫(kù)
1.0.1 Dao 開(kāi)發(fā)
(0)定義接口StudentDao 及創(chuàng)建接口的映射文件StudentDao .xm
package com.zep.dao;import com.zep.domain.Student;import java.util.List;public interface StudentDao {List<Student> selectStudents();int insertStudent(Student student);int updateStudent(Student student);int deleteStudent(int id); } <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.zep.dao.StudentDao"><select id="selectStudents" resultType="com.zep.domain.Student">select * from student order by id;</select><insert id="insertStudent">insert into student values(#{id},#{name},#{email},#{age})</insert><update id="updateStudent">update student set age = #{age} where id=#{id}</update><delete id="deleteStudent">delete from student where id=#{studentId}</delete> </mapper>(1) 創(chuàng)建 Dao 接口實(shí)現(xiàn)類
public class StudentDaoImpl implements StudentDao
(2) 實(shí)現(xiàn)接口中 select 方法
@Overridepublic List<Student> selectStudents() {// 1.獲取SqlSession對(duì)象SqlSession sqlSession = MybatisUtils.getSqlSession();String sqlId = "com.zep.dao.StudentDao.selectStudents";// 2.執(zhí)行sql語(yǔ)句,使用SqlSession類的方法List<Student> students = sqlSession.selectList(sqlId);/*for (Student student : students) {System.out.println(student);}*/// 3.關(guān)閉sqlSession.close();return students;}測(cè)試查詢操作:
MyBatisTest 類中創(chuàng)建 StudentDaoImpl 對(duì)象
(3) 實(shí)現(xiàn)接口中 insert 方法
@Overridepublic int insertStudent(Student student) {// 1.獲取SqlSession對(duì)象SqlSession sqlSession = MybatisUtils.getSqlSession();String sqlId = "com.zep.dao.StudentDao.insertStudent";// 2.執(zhí)行sql語(yǔ)句,使用SqlSession類的方法int nums = sqlSession.insert(sqlId,student);// 3.提交事務(wù)sqlSession.commit();// 4.關(guān)閉sqlSession.close();return nums;}測(cè)試 insert
@Testpublic void testInsertStudent() {StudentDaoImpl dao = new StudentDaoImpl();Student student = new Student();student.setId(1003);student.setName("zep");student.setEmail("zep@qq.com");student.setAge(22);int nums = dao.insertStudent(student);System.out.println("添加對(duì)象的數(shù)量:" + nums);}(4) 實(shí)現(xiàn)接口中 update 方法
@Override public int updateStudent(Student student) {SqlSession session = MybatisUtils.getSqlSession();int nums = session.update("com.zep.dao.StudentDao.updateStudent",student);session.commit();session.close();return nums;}測(cè)試 update
@Test public void testUpdateStudent() {StudentDaoImpl dao = new StudentDaoImpl();Student student = new Student();student.setId(1004);student.setAge(222);int nums = dao.updateStudent(student);System.out.println("使用Dao修改數(shù)據(jù):" + nums);}(5) 實(shí)現(xiàn)接口中 delete 方法
@Override public int deleteStudent(int id) {SqlSession session = MybatisUtils.getSqlSession();int nums = session.delete("com.zep.dao.StudentDao.deleteStudent",id);session.commit();session.close();return nums;}測(cè)試 delete
@Testpublic void testDeleteStudent() {StudentDaoImpl dao = new StudentDaoImpl();int nums = dao.deleteStudent(1005);System.out.println("使用Dao刪除的數(shù)據(jù):" + nums);}項(xiàng)目完整代碼如下:
pom.xml:
Student .java:
package com.zep.domain; // 推薦和表名一樣,容易記憶 public class Student {// 定義屬性,目前要求是 屬性名和列名保持一致private Integer id;private String name;private String email;private Integer age;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}@Overridepublic String toString() {return "Student{" +"id=" + id +", name='" + name + '\'' +", email='" + email + '\'' +", age=" + age +'}';} }mybatis.xml:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration><!--mybatis.xml 文件加入日志配置,可以在控制臺(tái)輸出執(zhí)行的 sql 語(yǔ)句和參數(shù)--><settings><setting name="logImpl" value="STDOUT_LOGGING"/></settings><environments default="mysql"><environment id="mysql"><transactionManager type="JDBC"/><dataSource type="POOLED"><!--數(shù)據(jù)庫(kù)的驅(qū)動(dòng)類名--><property name="driver" value="com.mysql.jdbc.Driver"/><!--連接數(shù)據(jù)庫(kù)的url字符串--><property name="url" value="jdbc:mysql://localhost:3306/ssm"/><!--訪問(wèn)數(shù)據(jù)庫(kù)的用戶名--><property name="username" value="root"/><!--密碼--><property name="password" value="root"/></dataSource></environment></environments><mappers><mapper resource="com/zep/dao/StudentDao.xml"/></mappers> </configuration>MybatisUtils .java:
package com.zep.utils;import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder;import java.io.IOException; import java.io.InputStream;public class MybatisUtils {private static SqlSessionFactory factory = null;/*靜態(tài)代碼塊:執(zhí)行優(yōu)先級(jí)高于非靜態(tài)的初始化塊,它會(huì)在類初始化的時(shí)候執(zhí)行一次,執(zhí)行完成便銷毀*///使用 靜態(tài)塊 創(chuàng)建一次 SqlSessionFactorystatic {String config = "mybatis.xml"; //需要和你的項(xiàng)目中的文件名一樣try {//讀取配置文件InputStream in = Resources.getResourceAsStream(config);//創(chuàng)建SqlSessionFactory對(duì)象,使用SqlSessionFactoryBuilderfactory = new SqlSessionFactoryBuilder().build(in);} catch (IOException e) {e.printStackTrace();}}// 獲取SqlSession對(duì)象的方法public static SqlSession getSqlSession() {SqlSession sqlSession = null;if (factory != null) {sqlSession = factory.openSession(); // 非自動(dòng)提交事務(wù)}return sqlSession;} }StudentDao .java:
package com.zep.dao;import com.zep.domain.Student;import java.util.List;public interface StudentDao {List<Student> selectStudents();int insertStudent(Student student);int updateStudent(Student student);int deleteStudent(int id); }StudentDao.xml:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.zep.dao.StudentDao"><select id="selectStudents" resultType="com.zep.domain.Student">select * from student order by id;</select><insert id="insertStudent">insert into student values(#{id},#{name},#{email},#{age})</insert><update id="updateStudent">update student set age = #{age} where id=#{id}</update><delete id="deleteStudent">delete from student where id=#{studentId}</delete> </mapper>StudentDaoImpl .java:
package com.zep.dao.Impl;import com.zep.dao.StudentDao; import com.zep.domain.Student; import com.zep.utils.MybatisUtils; import org.apache.ibatis.session.SqlSession;import java.util.List;public class StudentDaoImpl implements StudentDao {@Overridepublic List<Student> selectStudents() {// 1.獲取SqlSession對(duì)象SqlSession sqlSession = MybatisUtils.getSqlSession();String sqlId = "com.zep.dao.StudentDao.selectStudents";// 2.執(zhí)行sql語(yǔ)句,使用SqlSession類的方法List<Student> students = sqlSession.selectList(sqlId);/*for (Student student : students) {System.out.println(student);}*/// 3.關(guān)閉sqlSession.close();return students;}@Overridepublic int insertStudent(Student student) {// 1.獲取SqlSession對(duì)象SqlSession sqlSession = MybatisUtils.getSqlSession();String sqlId = "com.zep.dao.StudentDao.insertStudent";// 2.執(zhí)行sql語(yǔ)句,使用SqlSession類的方法int nums = sqlSession.insert(sqlId,student);// 3.提交事務(wù)sqlSession.commit();// 4.關(guān)閉sqlSession.close();return nums;}public int updateStudent(Student student) {SqlSession session = MybatisUtils.getSqlSession();int nums = session.update("com.zep.dao.StudentDao.updateStudent",student);session.commit();session.close();return nums;}@Overridepublic int deleteStudent(int id) {SqlSession session = MybatisUtils.getSqlSession();int nums = session.delete("com.zep.dao.StudentDao.deleteStudent",id);session.commit();session.close();return nums;} }TestMybatis .java:
package com.zep;import com.zep.dao.Impl.StudentDaoImpl; import com.zep.domain.Student; import org.junit.Test;import java.util.List;public class TestMybatis {@Testpublic void testSelectStudents() {//com.zep.dao.StudentDaoStudentDaoImpl dao = new StudentDaoImpl();/*** 調(diào)用List<Student> students = dao.selectStudents();* 1.dao對(duì)象,類型是StudentDao,可以獲取到它的全限定類名為:com.zep.dao.StudentDao* 這個(gè)全限定名稱和StudentDao.xml文件中mapper的namespace的值是一樣的** 2.方法名稱,selectStudents,這個(gè)方法就是StudentDao.xml文件中mapper標(biāo)簽下的子標(biāo)簽中id的值selectStudents** 3.通過(guò)dao中方法的返回值也可以確定Mybatis要調(diào)用的SqlSession的方法* 如果返回值是List,調(diào)用的是SqlSession.selectList()方法。* 如果返回值是int,或者是非List的,看mapper文件中的標(biāo)簽是<insert>,<update>* 就會(huì)調(diào)用SqlSession的insert(),update()等方法** mybatis的動(dòng)態(tài)代理:mybatis根據(jù)dao的方法調(diào)用,獲取執(zhí)行sql語(yǔ)句的信息。* mybatis根據(jù)你的dao接口,創(chuàng)建出一個(gè)dao接口的實(shí)現(xiàn)類,并創(chuàng)建這個(gè)類的對(duì)象來(lái)完成* SqlSession調(diào)用方法,訪問(wèn)數(shù)據(jù)庫(kù)。*/List<Student> students = dao.selectStudents();for (Student student : students) {System.out.println(student);}}@Testpublic void testInsertStudent() {StudentDaoImpl dao = new StudentDaoImpl();Student student = new Student();student.setId(1005);student.setName("zep");student.setEmail("zep@qq.com");student.setAge(22);int nums = dao.insertStudent(student);System.out.println("添加對(duì)象的數(shù)量:" + nums);}@Testpublic void testUpdateStudent() {StudentDaoImpl dao = new StudentDaoImpl();Student student = new Student();student.setId(1004);student.setAge(222);int nums = dao.updateStudent(student);System.out.println("使用Dao修改數(shù)據(jù):" + nums);}@Testpublic void testDeleteStudent() {StudentDaoImpl dao = new StudentDaoImpl();int nums = dao.deleteStudent(1005);System.out.println("使用Dao刪除的數(shù)據(jù):" + nums);}}1.0.2 傳統(tǒng) Dao 開(kāi)發(fā)方式的分析
在前面例子中自定義 Dao 接口實(shí)現(xiàn)類時(shí)發(fā)現(xiàn)一個(gè)問(wèn)題:Dao 的實(shí)現(xiàn)類其實(shí)并沒(méi)有干什么實(shí)質(zhì)性的工作,它僅僅就是通過(guò) SqlSession 的相關(guān) API 定位到映射文件 mapper (StudentDao.xml)中相應(yīng) id 的 SQL 語(yǔ)句,真正對(duì) DB 進(jìn)行操作的工作其實(shí)是由框架通過(guò) mapper 中的 SQL 完成的。
所以,MyBatis 框架就拋開(kāi)了 Dao 的實(shí)現(xiàn)類,直接定位到映射文件 mapper 中的相應(yīng) SQL 語(yǔ)句,對(duì)DB 進(jìn)行操作。這種對(duì) Dao 的實(shí)現(xiàn)方式稱為 Mapper 的動(dòng)態(tài)代理方式。
Mapper 動(dòng)態(tài)代理方式無(wú)需程序員實(shí)現(xiàn) Dao 接口,不需要我們自己編寫(xiě)Dao接口的實(shí)現(xiàn)類。接口是由 MyBatis 結(jié)合映射文件自動(dòng)生成的動(dòng)態(tài)代理實(shí)現(xiàn)的
總結(jié)
以上是生活随笔為你收集整理的三、MyBatis 使用传统 Dao 开发方式的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: IPv6数据报详解
- 下一篇: 三、scrapy爬虫框架——scrapy