MyBatis框架郭哥视频学习笔记

一、MyBatis简介
MyBatis是一个基于Java的持久层框架,阿里巴巴、慧点科技等多家知名软件公司都使用MyBatis。
与Hibernate相比,其具有以下几个特点:
1、在XML文件中配置SQL语句,实现了SQL语句与代码的分离,给程序的维护带来了很大便利。
2、因为需要程序员自己去编写SQL语句,程序员可以结合数据库自身的特点灵活控制SQL语句,
因此能够实现比Hibernate等全自动ORM框架更高的查询效率,能够完成复杂查询。
3、简单,易于学习,易于使用,上手快。  
二、MyBatis工作原理:
 

 
主要两个配置文件,一个SqlMapConfig.xml,另一个*.xml
SqlMapConfig.xml功能:
a、配置事务管理器,更确切的说,是配置数据源
b、指定映射文件(映射*.xml)
*.xml功能:
a、指定全限定性类名的别名
b、配置SQL语句(即写"select * form Table where id= uid"之类的数据库语句)
注意:映射文件与实体放在同一个包中
三、MyBatis开发步骤
1)导入两个Jar包:数据库驱动、MyBatis Jar
2)定义持久化对象(PO
3)在DB中生成表结构,即创建空表
4)配置主配置文件SqlMapConfig.xml
5)配置映射文件 *.xml
6)定义接口
7)定义接口实现类,该类通过MyBaties API访问DB
8)定义测试类,调用接口的实现类
 现在看一个例子:
IStudentDao.java功能:接口类,数据库功能的接口(有什么接口就有什么功能,不具体实现。)
StudentDaoMyBatisImpl.java功能:接口实现类,在这个框架中不再具体实现,而是调用Student.xml去实现IStudentDao.java接口提供的功能。
 
 
 IstudentDao.java源码如下:
package dao;
import java.util.List;
import entity.Student;
public interface IStudentDao { void insert(Student student); void deleteById(int id); void update(Student student); List<Student> selectAll(); Student selectById(int id); List<Student> selectByCondition(String condition); }

StudentDaoMyBatisImpl.java源码如下:

package dao;

import java.io.IOException;
import java.io.Reader;
import java.sql.SQLException;
import java.util.List;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;

import entity.Student;

public class StudentDaoMyBatisImpl implements IStudentDao {
    // 声明静态SqlMapClient对象
    private static SqlMapClient client = null;
    static {
        try {
            Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");
            client = SqlMapClientBuilder.buildSqlMapClient(reader);
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    //插入
    @Override
    public void insert(Student student) {
        try {
            client.insert("insertStu", student);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    //修改更新
    @Override
    public void update(Student student) {
        try {
            client.update("updateStu",student);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    //删除
    @Override
    public void deleteById(int id) {
        try {
            client.delete("deleteStu", id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<Student> selectAll() {
        try {
            return client.queryForList("selectAll");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;//假的返回值,不会执行此返回值
    }
    @Override
    public List<Student> selectByCondition(String condition) {
        try {
            return client.queryForList("selectByCondition", condition);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;//假的返回值,不会执行此返回值
    }

    @Override
    public Student selectById(int id) {
        try {
            return (Student) client.queryForObject("selectById", id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }


}

aynu_stu.sql内容如下:

/*
Navicat MySQL Data Transfer

Source Server         : localhost_3306
Source Server Version : 50130
Source Host           : localhost:3306
Source Database       : aynu_stu
数据库连接 
账号:root
密码:toor Target Server Type : MYSQL Target Server Version : 50130 File Encoding : 65001 Date: 2014-12-01 16:49:41
*/ create database aynu_stu; use aynu_stu; SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for `t_stu` -- ---------------------------- DROP TABLE IF EXISTS `t_stu`; CREATE TABLE `t_stu` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) DEFAULT NULL, `age` int(11) DEFAULT NULL, `score` double DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of t_stu -- ----------------------------

Student.java

package entity;

import java.io.Serializable;
public class Student implements Serializable {
    
    private int id;
    private String name;
    private int age;
    private double score;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public double getScore() {
        return score;
    }

    public void setScore(double score) {
        this.score = score;
    }

    public String toString() {
        return "name="+name+",age="+age+",score="+score;
    }
}

Student.xml内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap
    PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"
    "http://ibatis.apache.org/dtd/sql-map-2.dtd">

<sqlMap>
    <typeAlias alias="Student" type="entity.Student"/>
    <insert id="insertStu" parameterClass="Student">
        insert into T_stu(name,age,score) values(#name#, #age#, #score#)
    </insert>
    <delete id="deleteStu" parameterClass="int">
        delete from T_stu where id=#id#
    </delete>
    <update id="updateStu" parameterClass="Student">
        update T_stu set name=#name#,age=#age#,score=#score# where id=#id#
    </update>
    <select id="selectAll" resultClass="Student">
        select id,name,age,score from T_stu
    </select>
    <select id="selectById" resultClass="Student" parameterClass="int">
        select id,name,age,score from T_stu where id=#id#
    </select>
    <select id="selectByCondition" resultClass="Student" parameterClass="String">
        select id,name,age,score from T_stu where $condition$
    </select>
</sqlMap>

Test.java内容如下:

package test;

import java.util.List;

import junit.framework.TestCase;
import dao.IStudentDao;
import dao.StudentDaoMyBatisImpl;
import entity.Student;

public class Test extends TestCase {
    private static final boolean Student = false;
    private IStudentDao dao;

    protected void setUp() throws Exception {
        dao=new StudentDaoMyBatisImpl();
    }
    //测试添加方法
    public void addTest(){
        Student student = new Student();
        student.setName("测试员6");
        student.setAge(21);
        student.setScore(98.5);
        dao.insert(student);
    }
    //测试删除方法
    public void deleteTest(){
        dao.deleteById(2);
    }
    //测试修改更新方法,根据id进行更新
    public void updateTest(){
        Student student=new Student();
        student.setId(3);
        student.setName("测试员3");
        student.setAge(22);
        student.setScore(98.5);
        dao.update(student);//根据id进行更新
    }
    //测试根据ID进行查询方法
    public void selectById(){
        Student student=new Student();
        student=dao.selectById(4);
        System.out.println(student);
    }
    //测试查询全部学生信息方法
    public void selectAll(){
        List<Student> students=dao.selectAll();
        for(int i=0;i<students.size();i++)
        {
            System.out.println(students.get(i));
        }        
    }
    //测试按条件查询
    public void selectByCondition(){
        List<Student> students=dao.selectByCondition(" name='测试员5'");//查询条件如果是 '1'='1',那么查询出所有,此时SQL存在注入漏洞
        for (Student student : students) {
            System.out.println(student);
        }
    }

}

SqlMapConfig.xml内容如下:

<?xml version="1.0" encoding="UTF-8"?>    
<!DOCTYPE sqlMapConfig          
    PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"          
    "http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
        
<sqlMapConfig>    
   <transactionManager type="JDBC">
           <dataSource type="SIMPLE">
               <property name="JDBC.Driver" value="com.mysql.jdbc.Driver" />
               <property name="JDBC.ConnectionURL" value="jdbc:mysql://127.0.0.1:3306/aynu_stu" />
               <property name="JDBC.Username" value="root" />
               <property name="JDBC.Password" value="toor" />
           </dataSource>
   </transactionManager>
   
   <sqlMap resource="entity/Student.xml"/>
   
</sqlMapConfig>    

 

 程序演示:
 
posted @ 2014-12-02 19:51  技术宅星云  阅读(1387)  评论(0编辑  收藏  举报