MyBatis基础

MyBatis简介
MyBatis是支持普通SQL查询、存储过程和高级映射的优秀持久层框架,MyBatis使用简单的XML或注解用于配置和原始映射,将接口和Java的POJO映射成数据库中的记录。

MyBatis框架的核心是SqlSessionFactory对象,它是创建SqlSession对象的工厂,但SqlSessionFactory对象的创建来源于SqlSessionFactoryBuilder类,使用SqlSessionFactoryBuilder类创建SqlSessionFactory对象的方式可以来自于一个XML配置文件,也可以来自于一个实例化的Configuration对象。


MyBatis框架结构
这里写图片描述


MyBatis工作原理
这里写图片描述



注解方式配置第一个Mybatis实例

这里写图片描述

db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/DB_Student
jdbc.username=root
jdbc.password=*****

mybatis-config.xml

<?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>


    <settings>
        <!-- Globally enables or disables any caches configured in any mapper under this configuration -->
        <setting name="cacheEnabled" value="true"/>
        <!-- Sets the number of seconds the driver will wait for a response from the database -->
        <setting name="defaultStatementTimeout" value="3000"/>
        <!-- Enables automatic mapping from classic database column names A_COLUMN to camel case classic Java property names aColumn -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!-- Allows JDBC support for generated keys. A compatible driver is required.
        This setting forces generated keys to be used if set to true,
         as some drivers deny compatibility but still work -->
        <setting name="useGeneratedKeys" value="true"/>
    </settings>

    <!-- Continue going here -->

    <properties resource="db.properties"></properties>

    <typeAliases>
        <typeAlias type="po.Student" alias="Student"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="po/StudentMapper.xml"/>
    </mappers>

</configuration>

StudentMapper接口

package mapper;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import po.Student;

/**
 * Created with IntelliJ IDEA.
 * User: YEN
 * Date: 2016/8/8
 * Time: 08:24
 */
public interface StudentMapper {
    @Insert("insert into tb_student(id,name,score) values (#{id},#{name},#{socre})")
    public void insertStudent(Student student) throws  Exception;

    @Select("select * from tb_student where id=#{id}")
    public void selectStudent(int id) throws  Exception;
}

student.java

package po;

/**
 * Created with IntelliJ IDEA.
 * User: YEN
 * Date: 2016/8/8
 * Time: 08:20
 */

/**
 * 类中的属性字段和数据库中的Student字段一一对应
 */
public class Student {
    private int id;
    private String name%3R
    private int 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 getScore() {
        return score;
    }

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

    /**
     * 必须要有无参构造函数
     */
    public Student(){

    }
    public Student(int id,String name,int socre){
        this.id=id;
        this.name=name;
        this.score=socre;
    }
    @Override
    public String toString(){
        String str="学号:"+id+"   姓名:"+name+"  分数:"+score;
        return str;
    }
}

MyBatisUtil.java

package util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;

/**
 * Created with IntelliJ IDEA.
 * User: YEN
 * Date: 2016/8/8
 * Time: 08:49
 */

/**
 * 单例模式返回SqlSessionFactory
 */
public class MyBatisUtil {
    private final static SqlSessionFactory SQL_SESSION_FACTORY;
    static {
        String resource="config/mybatis.xml";
        Reader reader=null;
        try {
            reader= Resources.getResourceAsReader(resource);
        } catch ( IOException e ) {
            e.printStackTrace();
        }
        SQL_SESSION_FACTORY=new SqlSessionFactoryBuilder().build(reader);
    }

    public static SqlSessionFactory getSqlSessionFactory(){
        return SQL_SESSION_FACTORY;
    }

}

测试类MyBatisTest.java

package test;

import mapper.StudentMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import po.Student;
import util.MyBatisUtil;

/**
 * Created with IntelliJ IDEA.
 * User: YEN
 * Date: 2016/8/8
 * Time: 08:53
 */
public class MyBatisTest {
    static SqlSessionFactory sqlSessionFactory= MyBatisUtil.getSqlSessionFactory();

    public static void main(String[] args) {
        addStudent(new Student(1,"YEN",100));
    }

    public static void addStudent(Student student){
        SqlSession sqlSession=sqlSessionFactory.openSession();
        try {
            StudentMapper studentMapper=sqlSession.getMapper(StudentMapper.class);
            studentMapper.insertStudent(student);
            sqlSession.commit();
        } catch ( Exception e ) {
            e.printStackTrace();
        }
        finally {
            sqlSession.close();
        }
    }
}

XML文件配置方式实现
吧StudentMapper.java中的注解去掉,加上
StudentMapper.xml和Student在同一目录

<?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="po.Student">

    <!--id要与StudentMapper中接口名称相同-->
    <insert id="insertStudent" parameterMap="po.Student">
        INSERT INTO tb_student(id,name,score) values (#{id},#{name},#{socre})
    </insert>

    <select id="selectStudent" resultType="Student" parameterType="int">
        SELECT * FROM  tb_student WHERE id=#{id}
    </select>
</mapper>

开发技巧

    <insert id="insertStudent" parameterMap="po.Student">
        <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
--             如果主键是自动增长的,需要获取刚刚插入的主键
            SELECT LAST_INSERT_ID()
        </selectKey>
        INSERT INTO..........
    </insert>

* #{}和${}*

#{}表示一个占位符号,#{}接收输入参数,类型可以是简单类型,pojo、hashmap。
如果接收简单类型,#{}中可以写成value或其它名称。
#{}接收pojo对象值,通过OGNL读取对象中的属性值,通过属性.属性.属性...的方式获取对象属性值。

${}表示一个拼接符号,会引用sql注入,所以不建议使用${}。
${}接收输入参数,类型可以是简单类型,pojo、hashmap。
如果接收简单类型,${}中只能写成value。
${}接收pojo对象值,通过OGNL读取对象中的属性值,通过属性.属性.属性...的方式获取对象属性值。

properties

 如果在这些地方,属性多于一个的话,MyBatis按照如下的顺序加载它们:
         在properties元素体内指定的属性首先被读取。
         从类路径下资源或properties元素的url属性中加载的属性第二被读取,它会覆盖已经存在的完全一样的属性。
         作为方法参数传递的属性最后被读取,它也会覆盖任一已经存在的完全一样的属性,这些属性可能是从properties元素体内和资源/url属性中加载的。
        因此,最高优先级的属性是那些作为方法参数的,然后是资源/url属性,最后是properties元素中指定的属性。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值