mybatis框架——入门级

Posted byxz-dx

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mybatis框架——入门级相关的知识,希望对你有一定的参考价值。

什么是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框架——入门级的主要内容,如果未能解决你的问题,请参考以下文章

mybatis(入门级项目)

基于 xml 配置文件的入门级 SSM 框架整合

Cg入门20:Fragment shader - 片段级模型动态变色(实现汽车动态换漆)

Cg入门19:Fragment shader - 片段级模型动态变色

Cg入门16:Fragment shader - 片段级光照

Mybatis框架入门