zoukankan      html  css  js  c++  java
  • mybatis入门

    1.什么是MyBatis ?

         亲爱的度娘是这样说的:
    MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。2013年11月迁移到Github。
    iBATIS一词来源于“internet”和“abatis”的组合,是一个基于Java的持久层框架。iBATIS提供的持久层框架包括SQL Maps和Data Access Objects(DAO)
    我们把Mybatis的功能架构分为三层:
    (1)API接口层:提供给外部使用的接口API,开发人员通过这些本地API来操纵数据库。接口层一接收到调用请求就会调用数据处理层来完成具体的数据处理。
    (2)数据处理层:负责具体的SQL查找、SQL解析、SQL执行和执行结果映射处理等。它主要的目的是根据调用的请求完成一次数据库操作。
    (3)基础支撑层:负责最基础的功能支撑,包括连接管理、事务管理、配置加载和缓存处理,这些都是共用的东西,将他们抽取出来作为最基础的组件。为上层的数据处理层提供最基础的支撑。

    2.MyBatis 的入门案例

    源码介绍:

    1.jar包

     2.其次,我们要准备mybatis-config.xml(mybatis的配置文件)

    <?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>
        <!-- 配置别名 -->
        <typeAliases>
            <!--方式一: 按类型名定制别名 -->
            <typeAlias type="cn.zhang.entity.Student" alias="Student" />
            <!--方式二: 拿当前指定包下的简单类名作为别名 -->
            <!-- <package name="cn.zhang.entity"/> -->
        </typeAliases>
        <environments default="development">
            <environment id="development">
                <!-- 使用jdbc的事务 -->
                <transactionManager type="JDBC" />
                <!-- 使用自带的连接池 -->
                <dataSource type="POOLED">
                <!-- 我用的Oracle数据库 -->
                    <property name="driver" value="oracle.jdbc.driver.OracleDriver" />
                    <property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl" />
                    <property name="username" value="zhangzong" />
                    <property name="password" value="123" />
                </dataSource>
            </environment>
        </environments>
        <mappers>
            <mapper resource="cn/zhang/dao/StudentDAO.xml" />
        </mappers>
    </configuration>
    View Code

    3.Student.java (实体类)

    package cn.zhang.entity;
    
    import java.util.Date;
    
    /**
     * 学生实体类
     * 
     */
    public class Student {
        private Integer stuno;
        private String stuname;
        private Integer stuage;
        private Date studate;
    
        public String toString() {
            return "Student [stuno=" + stuno + ", stuname=" + stuname + ", stuage="
                    + stuage + ", studate=" + studate + "]";
        }
    
        public Integer getStuno() {
            return stuno;
        }
    
        public void setStuno(Integer stuno) {
            this.stuno = stuno;
        }
    
        public String getStuname() {
            return stuname;
        }
    
        public void setStuname(String stuname) {
            this.stuname = stuname;
        }
    
        public Integer getStuage() {
            return stuage;
        }
    
        public void setStuage(Integer stuage) {
            this.stuage = stuage;
        }
    
        public Date getStudate() {
            return studate;
        }
    
        public void setStudate(Date studate) {
            this.studate = studate;
        }
    
    }
    View Code

    4.StudentDao.java

    package cn.zhang.dao;
    
    import java.io.IOException;
    import java.util.List;
    
    import cn.zhang.entity.Student;
    
    public interface StudentDao {
        /**
         * 新增学生
         * 
         * @param stu
         * @return
         * @throws IOException
         */
        public int add(Student stu) throws IOException;
    
        /**
         * 删除学生
         * @param id
         * @return
         * @throws IOException
         */
        public int delStu(int id) throws IOException;
    
        /**
         * 查询所有记录
         * @return
         * @throws IOException
         */
        public List<Student> findAll() throws IOException;
    
        /**
         * 按照学生姓名查询学生集合(实体)
         * @param stu 
         * @return
         * @throws IOException
         */
        public List<Student> findStudntByName(Student stu) throws IOException;
    
        /**
         * 按照学生姓名查询学生集合(字符串)
         * @param stuname
         * @return
         * @throws IOException
         */
        public List<Student> findStudntByName(String stuname) throws IOException;
    
    }
    View Code

    5.StudentDaoImpl.java

    package cn.zhang.dao.impl;
    
    import java.io.IOException;
    import java.io.Reader;
    import java.util.List;
    
    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 cn.zhang.dao.StudentDao;
    import cn.zhang.entity.Student;
    import cn.zhang.util.MybatisUtil;
    
    public class StudentDaoImpl implements StudentDao {
        SqlSession session;
        
        public StudentDaoImpl() throws IOException {
            session = MybatisUtil.getSession();
        }
    
        /**
         * 添加
         */
        @Override
        public int add(Student stu) throws IOException {
            Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
            // 获取Session
            SqlSessionFactory build = new SqlSessionFactoryBuilder().build(reader);
            SqlSession session = build.openSession();
            int count = session.insert("insertStudent", stu);
            session.commit();
            session.close();
            return count;
        }
    
        
    
        /**
         * 模糊查询(字符串)
         */
        public List<Student> findStudntByName(String stuname) throws IOException {
            List<Student> list = session.selectList("findStudentByName", stuname);
            session.close();
            return list;
        }
    
        /**
         * 模糊查询(实体)
         */
    
        public java.util.List<Student> findStudntByName(Student stu)
                throws IOException {
            List<Student> list = session.selectList("findStudentByName", stu);
            session.close();
            return list;
        }
    
        /**
         * 查询所有
         */
        public java.util.List<Student> findAll() throws IOException {
            List<Student> list = session.selectList("findAll");
            session.close();
            return list;
        }
    
        /**
         * 删除
         */
        public int delStu(int id) throws IOException {
            int result = session.delete("delStudent", id);
            session.commit();
            session.close();
            return result;
        }
    
    }
    View Code

    6.StudentDAO.xml

    <?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">
    <mapper namespace="cn.zhang.dao">
        <!-- 获得自增值 -->
        <insert id="insertStudent" parameterType="Student">
            insert into student(stuno,stuname,stuage,studate)
            values(mybatis.nextval,#{stuname},#{stuage},#{studate})
            <!-- sqlserver 和4Mysql 只有自自增 自增时机和insert时机: 先insert返回自增值 Oracle先产生一个自增值,然后再执行insert -->
            <selectKey keyProperty="stuno" resultType="int">
                select mybatis.currval from dual
                <!-- select @@identity --><!--MySQL和SQLServer中的用法 -->
            </selectKey>
        </insert>
        
        <!--删除学生 -->
        <delete id="delStudent">
            delete from student where stuno=#{xxx}<!-- #{xxx}随便写,起到一个占位的作用 -->
        </delete>
        
        <!-- 查询所有 -->
        <select id="findAll" resultType="Student">
            select * from student
        </select>
    
        <!--模糊查询 --><!-- $方式无法防止Sql注入 ,#方式能够很大程度防止sql注入 -->
        <select id="findStudentByName" resultType="Student">
            <!-- select * from student where stuname like concat('%',#{stuname},'%') -->
            select * from student where stuname like '%${value}%'
        </select>
    
    </mapper>
    View Code

    7.MybatisUtil.java

    package cn.zhang.util;
    
    import java.io.IOException;
    import java.io.Reader;
    
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    
    /**
     * 工具类
     * 
     */
    public class MybatisUtil {
        private static String config = "mybatis-config.xml";
        static Reader reader;
        static {
            try {
                reader = Resources.getResourceAsReader(config);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        private static SqlSessionFactory factory = new SqlSessionFactoryBuilder()
                .build(reader);
    
        // 提供一个可以获取到session的方法
        public static SqlSession getSession() throws IOException {
    
            SqlSession session = factory.openSession();
            return session;
        }
    }
    View Code

    8.MyTest.java

    package cn.zhang.test;
    
    import java.io.IOException;
    import java.util.Date;
    import java.util.List;
    
    import org.junit.Before;
    import org.junit.Test;
    
    import cn.zhang.dao.StudentDao;
    import cn.zhang.dao.impl.StudentDaoImpl;
    import cn.zhang.entity.Student;
    
    public class MyTest {
        
        StudentDao dao;
        @Before
        public void initData() throws IOException{
            dao=new StudentDaoImpl();
        }
        
        /**
         * 模糊查询
         * @throws IOException
         */
        @Test
        public void findStudentByName() throws IOException{
            List<Student> list = dao.findStudntByName("呵");
            for (Student student : list) {
                System.out.println("编号: "+student.getStuno()+"姓名:"+student.getStuname());
            }
            
        }
        
        /**
         * 查询所有学生
         * @throws IOException
         */
        @Test
        public void findAll() throws IOException{
            List<Student> list = dao.findAll();
            for (Student student : list) {
                System.out.println("编号: "+student.getStuno()+"姓名:"+student.getStuname());
            }
            
        }
        
        
        /**
         * 删除学生
         * @throws IOException
         */
        
        @Test
        public void delStudent() throws IOException{
            dao.delStu(2);
            System.out.println("成功!");
        }
    
        /**
         * 添加学生
         * @throws IOException
         */
        @Test
        public void testAdd() throws IOException{
            Student stu=new Student();
            stu.setStuname("呵呵");
            stu.setStuage(21);
            stu.setStudate(new Date());
            StudentDao dao=new StudentDaoImpl();
            dao.add(stu);
        }
    
    }
    View Code

    9.log4j.properties

    ### direct log messages to stdout ###
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.Target=System.out
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
    
    ### direct messages to file mylog.log ###
    log4j.appender.file=org.apache.log4j.FileAppender
    log4j.appender.file.File=c:mylog.log
    log4j.appender.file.layout=org.apache.log4j.PatternLayout
    log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
    
    ### set log levels - for more verbose logging change 'info' to 'debug' ###
    
    log4j.rootLogger=debug, stdout
    View Code
  • 相关阅读:
    golang roadrunner中文文档(五)集成到其他服务 docker
    golang roadrunner中文文档(四)app服务器
    golang roadrunner中文文档(三)HTTPS 和 HTTP/2
    golang roadrunner中文文档(二)PHP Workers
    golang roadrunner中文文档(一)基础介绍
    Laravel Octane中文文档
    PHP海量excel数据导出方案解决 xlswriter性能测试
    中国车牌归属地数据库
    php模仿go实现多变量返回
    laravel 异步队列任务 广播系统
  • 原文地址:https://www.cnblogs.com/zhangzongle/p/6188987.html
Copyright © 2011-2022 走看看