其他分享
首页 > 其他分享> > Mybatis

Mybatis

作者:互联网

Mybatis

基本使用

  1. 创建工具类来构造SqlSessionFactory
public class MybatisUtil {

    //在类加载时就进行创建
    private static SqlSessionFactory sqlSessionFactory;
    static {
        try {
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(new FileInputStream("mybatis-config.xml"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取一个新的会话
     * @param autoCommit 是否开启自动提交(跟JDBC是一样的,如果不自动提交,则会变成事务操作)
     * @return SqlSession对象
     */
    public static SqlSession getSession(boolean autoCommit){
        return sqlSessionFactory.openSession(autoCommit);
    }
}

  1. main方法更简单
package com.test;

import com.test.Util.MybatisUtil;
import com.test.mapper.TestMapper;
import org.apache.ibatis.session.SqlSession;

import java.awt.print.Book;
import java.util.List;

public class Main {
    public static void main(String[] args) {
MybatisUtil.getSession(true).getMapper(TestMapper.class).selectStudent().forEach(System.out::println);
    }
}


  1. entity.Student
package com.test.entity;


import lombok.Data;

@Data
public class Student {
    int sid;
    String name;
    String sex;
    int grade;
}


  1. mapper.TestMapper.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="com.test.mapper.TestMapper">
    <select id="selectStudent" resultType="com.test.entity.Student">
        select * from book_manage.student
    </select>
</mapper>
  1. mapper.TestMapper
package com.test.mapper;

import com.test.entity.Student;

import java.awt.print.Book;
import java.util.List;

public interface TestMapper {
    List<Student> selectStudent();
}

  1. 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>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/book_manage"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
<mappers>
    <mapper resource="com/test/mapper/TestMapper.xml"/>
</mappers>


</configuration>

起别名

  1. Student.java

    @Alias("MiKu")
    public class Student {
        int sid;
        String name;
        String sex;
        int grade;
    }
    

    mybatis-config.xml

    <typeAliases>
        <package name="com.test.entity"/>
    </typeAliases>
    

    TestMapper.xml

<mapper namespace="com.test.mapper.TestMapper">
    <select id="selectStudent" resultType="MiKu">
        select * from book_manage.student
    </select>
</mapper>
  1. mybatis-config.xml
<!-- 需要在environments的上方 -->
<typeAliases>
    <typeAlias type="com.test.entity.Student" alias="Student"/>
</typeAliases>

TestMapper.xml

<mapper namespace="com.test.mapper.TestMapper">
    <select id="selectStudent" resultType="Student">
        select * from book_manage.student
    </select>
</mapper>
  1. mybatis-config.xml
<typeAliases>
        <package name="com.test.entity"/>
    </typeAliases>

TestMapper.xml

<select id="selectStudent" resultType="student">
        select * from book_manage.student
    </select>

<insert id="addStudent" >
    insert into student(name,age) values (#{name},#{age})
</insert>
int addStudent(Student student);
System.out.println(mapper.addStudent(new Student().setName("白牛").setAge(88)));

<delete id="deleteStudent">
    delete from student where id = #{id}
</delete>
int deleteStudent(int id);
System.out.println(mapper.deleteStudent(16));

<update id="updateStudent">
    update student
    set name=#{name},age=#{age}
    where id = #{id}
</update>
int updateStudent(Student student);
System.out.println(mapper.updateStudent(new Student(2,"cat",999)));

<select id="selectStudentById" resultType="Student">
    select * from student where id = #{id}
</select>
Student selectStudentById(int id);
System.out.println(mapper.selectStudentById(3));

用Map映射

<resultMap id="Test" type="Student">
    <result column="id" property="age"/>
    <result column="name" property="name"/>
    <result column="age" property="id"/>
</resultMap>
<select id="selectStudent" resultType="Map">
        select * from student
    </select>
List<Student> selectStudent();
mapper.selectStudent().forEach(System.out::println);

构造器问题

一个类中存在多个构造方法,会报错

<resultMap id="Test" type="Student">
    <constructor>
        <arg column="id" javaType="int"/>
        <arg column="name" javaType="String"/>
    </constructor>
</resultMap>

<select id="selectStudent" resultMap="Test">
    select * from student
</select>
@Data
@Accessors(chain = true)
public class Student {

    public Student(Integer id, String name) {
        this.id = id;
        this.name = name;
    }

    int id;
    String name;
    int age;


}

驼峰命名

数据库是下划线命名,java是驼峰命名,可以进行转换

<settings>
    <setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>

下划线命名 -> 驼峰命名

事务操作

SqlSession session = MybatisUtil.getSession(false); // 开启事务
session.rollback(); // 回滚
session.commit(); // 提交

缓存机制

概念

把一部分内容放入缓存,下次获取数据,直接从缓存读取,直接从内存获取,而不是向数据库索要,效率更高

一级缓存

Mybatis默认启动一级缓存

作用范围有限,作用于一个会话,我们希望缓存扩展到所有会话,通过二级缓存,默认关闭

<cache
  eviction="FIFO"
  flushInterval="60000"
  size="512"
  readOnly="true"/>

某个方法关闭缓存

<select id="getStudentBySid" resultType="Student" useCache="false">
    select * from student where sid = #{sid}
</select>

操作完成后清空缓存

<select id="getStudentBySid" resultType="Student" flushCache="true">
    select * from student where sid = #{sid}
</select>

读取顺序:二级缓存 => 一级缓存 => 数据库

注解开发

@Insert("insert into student(name, sex) values(#{name}, #{sex})")
int addStudent(Student student);

<mappers>
    <mapper class="com.test.mapper.MyMapper"/>
    <!--  也可以直接注册整个包下的 <package name="com.test.mapper"/>  -->
</mappers>

指定构造方法

@ConstructorArgs({
        @Arg(column = "sid", javaType = int.class),
        @Arg(column = "name", javaType = String.class)
})
@Select("select * from student where sid = #{sid} and sex = #{sex}")
Student getStudentBySidAndSex(@Param("sid") int sid, @Param("sex") String sex);

指定参数类型

@Select("select * from student where sid = #{sid} and sex = #{sex}")
Student getStudentBySidAndSex(@Param("sid") int sid, @Param("sex") String sex);

注解控制缓存

@CacheNamespace(readWrite = false)
public interface MyMapper {

    @Select("select * from student")
    @Options(useCache = false)
    List<Student> getAllStudent();

Mybatis是半自动框架,SQL语句需要自己写,有一定麻烦,JPA框架这种全自动框架,几乎没有SQL语句!

标签:name,student,int,sex,Student,sid,Mybatis
来源: https://www.cnblogs.com/instore/p/16468467.html