1. 程式人生 > >mybatis框架——入門級

mybatis框架——入門級

sed pri 操作 ride inpu 框架 統一 字段 ESS

什麽是mybatis框架?

  MyBatis 是一款優秀的持久層框架,它支持定制化 SQL、存儲過程以及高級映射。MyBatis 避免了幾乎所有的 JDBC 代碼和手動設置參數以及獲取結果集。MyBatis 可以使用簡單的 XML 或註解來配置和映射原生信息,將接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java對象)映射成數據庫中的記錄(百度百科、mybatis官網解釋)。

特點

  • 簡單易學:本身就很小且簡單。沒有任何第三方依賴,最簡單安裝只要兩個jar文件+配置幾個sql映射文件易於學習,易於使用,通過文檔和源代碼,可以比較完全的掌握它的設計思路和實現。
  • 靈活:mybatis不會對應用程序或者數據庫的現有設計強加任何影響。 sql寫在xml裏,便於統一管理和優化。通過sql語句可以滿足操作數據庫的所有需求。
  • 解除sql與程序代碼的耦合:通過提供DAO層,將業務邏輯和數據訪問邏輯分離,使系統的設計更清晰,更易維護,更易單元測試。sql和代碼的分離,提高了可維護性。
  • 提供映射標簽,支持對象與數據庫的orm字段關系映射
  • 提供對象關系映射標簽,支持對象關系組建維護
  • 提供xml標簽,支持編寫動態sql。

下面將通以學生表為例,向數據庫實現增加、刪除、修改、查詢數據,通過簡易的代碼初步理解此框架。

註解:

  a、需導入以下jar包,dom4j-1.6.1.jar、jaxen-1.1-beta-6.jar、mysql-connector-java-5.1.3-rc-bin.jar、xalan.jar;

  b、xml文件url中的數據庫名稱需改為自己電腦上存在的數據庫。

1、包結構

技術分享圖片

2、sqlmap.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<sqlSessionFactory>
    <sqlSession>
        <properties name="driver" value="com.mysql.jdbc.Driver"></properties>
        <properties name="url" value="jdbc:mysql://localhost:3306/yongzhou?characterEncoding=utf-8"></properties>
        <properties name="username" value="root"></properties>
        <properties name="password" value=""></properties>
        
        <!-- 指定要加載的配置文件 -->
        <mapping resource="pojo/Student.xml"/>
    </sqlSession>
</sqlSessionFactory>

2、student,xml文件

<?xml version="1.0" encoding="UTF-8"?>
<class table="student" name="pojo.Student">
    <properties name="stuid" column="sid" type="java.lang.Integer"/>
    <properties name="stuname" column="sname" type="java.lang.String"/>
    <properties name="stuscore" column="score" type="java.lang.Double"/>
    
    <!-- 查了路數據 -->
    <insert id="insertstudent">
        insert into student(sname,score) values(#{stuname},#{stuscore})
    </insert>
    <!-- 刪除數據 -->
    <delete id="deletestudentbyname">
        delete from student where sname=#{stuname}
    </delete>
    <delete id="deletestudentbyscore">
        delete from student where score=#{stuscore}
    </delete>
    <delete id="deleteallstudent">
        delete from student
    </delete>
    <!-- 修改數據 -->
    <update id="updatenamebyid">
        update student set sname=#{stuname} where sid=#{stuid}
    </update>
    <update id="updaescorebyid">
        update student set score=#{stuscore} where sid=#{stuid}
    </update>
    <!-- 查詢數據 -->
    <select id="selectallstudent">
        select * from student 
    </select>
    <select id="selectbyname">
        select * from student where sname=#{stuname}
    </select>
    <select id="selectbyscore">
        select * from student where score=#{stuscore}
    </select>
    <select id="selectbyid">
        select * from student where sid=#{stuid}
    </select>
</class>

3、Student類

package pojo;

import java.io.Serializable;


public class Student implements Serializable,utils.Student{
    private Integer stuid;
    private String stuname;
    private Double stuscore;
    
    public Student() {
        
    }
    public Student(Integer stuid, String stuname, Double stuscore) {
        super();
        this.stuid = stuid;
        this.stuname = stuname;
        this.stuscore = stuscore;
    }
    public Integer getStuid() {
        return stuid;
    }
    public void setStuid(Integer stuid) {
        this.stuid = stuid;
    }
    public String getStuname() {
        return stuname;
    }
    public void setStuname(String stuname) {
        this.stuname = stuname;
    }
    public Double getStuscore() {
        return stuscore;
    }
    public void setStuscore(Double stuscore) {
        this.stuscore = stuscore;
    }
    @Override
    public String toString() {
        return this.getStuid()+"=="+this.getStuname()+"=="+this.getStuscore();
    }
}

4、DBHelper類

package utils;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.print.Doc;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

public class DBHelper {
    static InputStream is=null;
    static Document doc=null;
    static SAXReader reader=null;
    static Map connmap=null;
    static List tablelist=null;

    static{
        try {
            connmap=getConnMap();
            tablelist=getTableList();
            Class.forName(connmap.get("driver").toString());
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    //讀取配置文件
    public static Document getDocument(InputStream is) {
        
        try {
            reader=new SAXReader();
            doc = reader.read(is);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return doc;
    }
    
    //獲得配置文件的map
    public static Map<String, String> getConnMap(){
        is=DBHelper.class.getResourceAsStream("/sqlmap.xml");
        doc=getDocument(is);
        connmap=new HashMap<String,String>();
        if(doc!=null){
            List<Node> list=doc.selectNodes("/sqlSessionFactory/sqlSession/properties");
            for (Node node : list) {
                Element e=(Element)node;
                connmap.put(e.attributeValue("name"),e.attributeValue("value"));
            }
        }
        return connmap;
    }
    
    //獲得映射文件的list
    public static List<String> getTableList(){
        tablelist=new ArrayList<String>();
        if(doc!=null){
            List<Node> list=doc.selectNodes("/sqlSessionFactory/sqlSession/mapping");
            for (Node node : list) {
                Element e=(Element)node;
                tablelist.add(e.attributeValue("resource"));
            }
        }
        return tablelist;
    }
    
    //映射文件的document
    public static List<Document> loadMapping(){
        List<Document> list=new ArrayList<Document>();
        for (String path : getTableList()) {
            InputStream is=DBHelper.class.getResourceAsStream("/"+path);
            Document doc=getDocument(is);
            list.add(doc);
        }
        return list;
    }
    
    //獲得數據庫連接
    public static Connection getConnection(){
        Connection conn=null;
        try {
            conn=DriverManager.getConnection(connmap.get("url").toString(), connmap.get("username").toString(), connmap.get("password").toString());
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return conn;
    }
    
    //關閉數據庫連接
    public static void closeConnection(Connection conn){
        try {
            if(conn!=null&&!conn.isClosed()){
                conn.close();
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
}

5、dao包

package dao;

import java.util.List;

import pojo.Student;

public interface ObjectDao {
    public void saveObject(String id,Object o)throws Exception;
    public void deleteStudent(String id,Object o) throws Exception;
    public void updateStudent(String id,Object o) throws Exception;
    public List<Object> selectStudent(String id,Object o)throws Exception;
}

6、dao包的實現類

package daoimpl;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;

import dao.ObjectDao;
import pojo.Student;
import utils.DBHelper;

public class ObjectDaoImpl implements ObjectDao{
    static Document doc=null;
    
    public Document getTableDocument(Object s){
        List<Document> list=DBHelper.loadMapping();
        for (Document document : list) {
            Element root=document.getRootElement();
            String classname=root.attribute("name").getValue();
            try {
                if(Class.forName(classname)==s.getClass()){
                    doc = document;
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        return doc;
    }
    
    public void saveObject(String id,Object o) throws Exception{
        doc=getTableDocument(o);
        Connection connection=DBHelper.getConnection();
        Element insert=(Element)doc.selectSingleNode("/class/insert");
        String insertid=insert.attribute("id").getValue();
        List<String> fields=new ArrayList<>();
        if(id.equals(insertid)){
            String sql=insert.getText().trim();
            Pattern p=Pattern.compile("#[{](\\w+)[}]");
            Matcher m=p.matcher(sql);
            int count=0;
            while(m.find()){
                count++;
                fields.add(m.group(1));
            }
            sql=sql.replaceAll("#[{]\\w+[}]", "?");
            PreparedStatement ps=connection.prepareStatement(sql);
            int n=0;
            Class c=o.getClass();
            while(n<count){
                String field=fields.get(n);
                String methodname="get"+field.substring(0,1).toUpperCase()+field.substring(1);
                Method method=c.getMethod(methodname, null);
                ps.setObject(++n, method.invoke(o, null));
            }
            int s=ps.executeUpdate();
            if(s>0){
                System.out.println("插入成功");
            }
            ps.close();
            connection.close();
        }
    }

    @Override
    public void deleteStudent(String id, Object o) throws Exception {
        doc=getTableDocument(o);
        Connection connection=DBHelper.getConnection();
        PreparedStatement ps=null;
        List<Node> list=doc.selectNodes("/class/delete");
        List<String> fields=new ArrayList<>();
        for (Node node: list) {
            Element element=(Element)node;
            String insertid=element.attribute("id").getValue();
            if(id.equals(insertid)){
                String sql=element.getText().trim();
                Pattern p=Pattern.compile("#[{](\\w+)[}]");
                Matcher m=p.matcher(sql);
                int count=0;
                while(m.find()){
                    count++;
                    fields.add(m.group(1));
                }
                sql=sql.replaceAll("#[{]\\w+[}]", "?");
                ps=connection.prepareStatement(sql);
                int n=0;
                Class c=o.getClass();
                while(n<count){
                    String field=fields.get(n);
                    String methodname="get"+field.substring(0,1).toUpperCase()+field.substring(1);
                    Method method=c.getMethod(methodname, null);
                    ps.setObject(++n, method.invoke(o, null));
                }
                int s=ps.executeUpdate();
                if(s>0){
                    System.out.println("刪除成功");
                }
                ps.close();
                DBHelper.closeConnection(connection);
                break;
            }
        }
    }

    @Override
    public void updateStudent(String id, Object o) throws Exception {
        doc=getTableDocument(o);
        Connection connection=DBHelper.getConnection();
        PreparedStatement ps=null;
        List<Node> list=doc.selectNodes("/class/update");
        List<String> fields=new ArrayList<>();
        for (Node node: list) {
            Element element=(Element)node;
            String insertid=element.attribute("id").getValue();
            if(id.equals(insertid)){
                String sql=element.getText().trim();
                Pattern p=Pattern.compile("#[{](\\w+)[}]");
                Matcher m=p.matcher(sql);
                int count=0;
                while(m.find()){
                    count++;
                    fields.add(m.group(1));
                }
                sql=sql.replaceAll("#[{]\\w+[}]", "?");
                ps=connection.prepareStatement(sql);
                int n=0;
                Class c=o.getClass();
                while(n<count){
                    String field=fields.get(n);
                    String methodname="get"+field.substring(0,1).toUpperCase()+field.substring(1);
                    Method method=c.getMethod(methodname, null);
                    ps.setObject(++n, method.invoke(o, null));
                }
                int s=ps.executeUpdate();
                if(n>0){
                    System.out.println("修改成功");
                }
                ps.close();
                DBHelper.closeConnection(connection);
                break;
            }
        }
    }

    @Override
    public List<Object> selectStudent(String id, Object s) throws Exception {
        Class c = s.getClass();
        List<Object> list = new ArrayList<Object>();
        Document doc = getTableDocument(s);
        Connection conn = DBHelper.getConnection();
        List<Node> ll =doc.selectNodes("/class/select");
        Element select = null;
        for (Node node : ll) {
            Element ee = (Element)node;
            if(ee.attribute("id").getValue().equals(id)){
                select = ee;
                break;
            }
        }
        String selectid = select.attribute("id").getValue();
        try {
            if(id.equals(selectid)){
                String sql = select.getTextTrim();
                Pattern p = Pattern.compile("#[{](\\w+)[}]");
                Matcher m = p.matcher(sql);
                int count = 0;
                List<String> fileds = new ArrayList<String>();
                while(m.find()){
                    count++;
                    fileds.add(m.group(1));
                }
                sql = sql.replaceAll("#[{]\\w+[}]", "?");
                PreparedStatement ps = conn.prepareStatement(sql);
                int n = 0;
                
                while(n<count){
                    String filed = fileds.get(n);
                    String methodname = "get"+filed.substring(0,1).toUpperCase()+filed.substring(1);
                    System.out.println(n+"=="+methodname);
                    Method mm= c.getMethod(methodname, null);
                    ps.setObject(++n, mm.invoke(s, null));
                }
                ResultSet rs = ps.executeQuery();
                Field[] ff = c.getDeclaredFields();
                while(rs.next()){
                    Object o = c.newInstance();
                    for (int i = 0; i < ff.length; i++) {
                        String fname = ff[i].getName();
                        Element fe = (Element)doc.selectSingleNode("/class/properties[@name=‘"+fname+"‘]");
                        ff[i].setAccessible(true);
                        ff[i].set(o, rs.getObject(fe.attribute("column").getValue()));
                    }
                    list.add(o);
                }
                rs.close();
                ps.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            DBHelper.closeConnection(conn);
        }
        return list;
    }
}

7、測試類

package main;


import java.util.ArrayList;
import java.util.List;

import dao.ObjectDao;
import daoimpl.ObjectDaoImpl;
import pojo.Student;
import utils.*;

public class Test {

    public static void main(String[] args) throws Exception {
        Student student=new Student();
        ObjectDao oDao=new ObjectDaoImpl();
        List<Object> list=new ArrayList<Object>();
        student.setStuname("博園學子");
        student.setStuscore(100d);
        student.setStuid(327);
        System.out.println("===向學生表插入一條數據===");
        oDao.saveObject(Student.insertstudent, student);
        System.out.println("===查詢數據庫中所有的數據===");
        list=oDao.selectStudent(Student.selectallstudent, student);
        for (Object l : list) {
            System.out.println(l);
        }
        System.out.println("===修改學生博園學子這條記錄,將成績改為99===");
        student.setStuscore(99d);
        oDao.updateStudent(Student.updaescorebyid, student);
        System.out.println("===刪除學生博園學子這條記錄===");
        oDao.deleteStudent(Student.deletestudentbyname, student);
    }
}

運行結果:

技術分享圖片

結束。

mybatis框架——入門級