MyBatis---简单增删改查的带事物的例子

本例子包含了对数据库表简单的增删改查的操作,并且包含事物。该例子只适用于MySQL数据库。该例子需要手动创建数据库以及数据库表

例子中所需要的jar包,详查MyBatis---简介

一个entity类Student.java这个类包含一个无参的构造函数,以及所有属性的getset方法

private static final long serialVersionUID = 2257468553009291835L;
    
private int id;
private String name;
private int age;

public Student() { }
    
public Student(String name, int age) {
  super();
  this.name = name;
}

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 getAge() {
  return age;
}

public void setAge(int age) {
  this.age = age;
}

一个MyBatis配置文件MyBatisConfig.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>

    <!-- 为entity类创建别名 -->
    <typeAliases>
        <typeAlias alias="Student" type="com.studyMyBatis.entity.Student"/>
    </typeAliases>
    
    <!-- 数据库配置 -->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" /><!-- 设置事物采用JDBC处理方式,另一种处理方式为MANAGED -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/jsp_db"/>
                <property name="username" value="root"/>
                <property name="password" value="Lfq,909475"/>
            </dataSource>
        </environment>
    </environments>

    <!-- 关联mappers,每一个entity类都应有一个对应的mapper.xml文件,该文件用于存放操作数据库语句,相当于将sql保存到配置文件中,java直接调用即可 -->
    <mappers>
        <mapper resource="com/studyMyBatis/map/student.xml" />
    </mappers>

</configuration>

输出日志信息配置log4j.properties:该配置文件中设置sql显示级别为DEBUG,显示在控制台中

log4j.rootLogger=DEBUG, Console  
  
#Console  
log4j.appender.Console=org.apache.log4j.ConsoleAppender  
log4j.appender.Console.layout=org.apache.log4j.PatternLayout  
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n  
  
log4j.logger.java.sql.ResultSet=INFO  
log4j.logger.org.apache=INFO  
log4j.logger.java.sql.Connection=DEBUG  
log4j.logger.java.sql.Statement=DEBUG  
log4j.logger.java.sql.PreparedStatement=DEBUG

一个与entity类Student.java对应的mapper文件student.xml:文件中所有的#{值}应与传过来的对象中的属性名称或HashMap中键的名称相同。如:#{name},那么传过来的Student中就必须有name属性,或传过来的HashMap中有键为name的值

<?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="/">

    <!-- 添加成功,会返回插入数据的主键id到student对象中。但需要数据库支持主键id自增长,比如oracle就不能返回 -->
    <insert id="insertStudent" parameterType="Student"
        statementType="PREPARED" keyProperty="studentId" useGeneratedKeys="true">
        insert into
        Student (name,age) values(#{name},#{age})
    </insert>

    <update id="updateStudentById" parameterType="Student">
        update student set
        name=#{name}, age=#{age} where studentId = #{studentId}
    </update>

    <delete id="deleteStudentById" parameterType="Student">
        delete from student
        where studentId = #{studentId}
    </delete>

    <select id="getStudentById" parameterType="int" resultType="Student">
        select *
        from student where studentId=#{studentId}
    </select>

    <select id="getStudentByEntity" parameterType="Student"
        resultType="Student">
        select *
        from student where studentId=#{studentId}
    </select>

    <select id="getStudentByNameAndAge" parameterType="hashmap"
        resultType="Student">
        select *
        from student where name=#{name} and age=#{age}
    </select>

    <select id="getStudentResultHashMapById" parameterType="int"
        resultType="hashmap">
        select *
        from student where studentId=#{studentId}
    </select>

    <select id="getAllStudents" resultType="Student">
        select * from student
    </select>

    <resultMap type="Student" id="StudentMap">
        <id property="studentId" column="studentId" />
        <result property="name" column="name" />
        <result property="age" column="age" />
    </resultMap>
    <select id="getStudent" parameterType="int" resultMap="StudentMap">
        select *
        from student where studentId=#{studentId}
    </select>

</mapper>

一个测试类

public class Test {

    public static void main(String[] args) {
        
        Reader reader = null;
        SqlSession sqlSession = null;
        try {
            String resoutce = "com/studyMyBatis/map/MyBatisConfig.xml";
            reader = Resources.getResourceAsReader(resoutce);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
            sqlSession = sqlSessionFactory.openSession(false);//参数设置是否自动提交,默认false(相当于事物管理)
            new Test().insertStudent(sqlSession);
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
            if (sqlSession != null) {
                sqlSession.rollback();
            }
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
        
    }
    
    /** 添加一条数据
     * @param sqlSession
     * @return 返回插入的这条数据的主键id
     */
    public int insertStudent(SqlSession sqlSession) {
        Student student = new Student("王五", 24);
        sqlSession.insert("insertStudent", student);
        return student.getId();
    }
    
    /** 根据id修改一条数据
     * @param sqlSession
     */
    public void updateStudentById(SqlSession sqlSession) {
        Student student = new Student("张三改", 24);
        student.setId(3);
        sqlSession.update("updateStudentById", student);
    }
    
    /** 根据id删除一条数据
     * @param sqlSession
     */
    public void deleteStudentById(SqlSession sqlSession) {
        Student student = new Student();
        student.setId(4);
        sqlSession.delete("deleteStudentById", student);
    }
    
    /** 根据id查询一条Student记录
     * @param sqlSession
     * @param studentId Student.id
     * @return
     */
    public Student getStudentById(SqlSession sqlSession, int studentId) {
        return sqlSession.selectOne("getStudentById", studentId);
    }
    
    /** 根据Student对象查询一条Student记录
     * @param sqlSession
     * @param student 该对象中至少应包括查询语句中的条件字段的值
     * @return
     */
    public Student getStudentByEntity(SqlSession sqlSession, Student student) {
        return sqlSession.selectOne("getStudentByEntity", student);
    }
    
    /** 根据一个HashMap查询一条Student记录
     * @param sqlSession
     * @return
     */
    public Student getStudentByNameAndAge(SqlSession sqlSession, HashMap<String, Object> hashMap) {
        return sqlSession.selectOne("getStudentByNameAndAge", hashMap);
    }
    
    /** 根据id查询一条Student记录
     * @param sqlSession
     * @param studentId Student.id
     * @return
     */
    public HashMap<String, Object> getStudentResultHashMapById(SqlSession sqlSession, int studentId) {
        return sqlSession.selectOne("getStudentResultHashMapById", studentId);
    }
    
    /** 查询所有的Student记录
     * @param sqlSession
     * @return List<Student>
     */
    public List<Student> getAllStudents(SqlSession sqlSession){
        return sqlSession.selectList("getAllStudents");
    }
    
/*-------------------------------------------------------------------------------------------------------------------------*
 *---------------------------------------以上是设置参数属性为parameterType-------------------------------------------------*
 *------------------------------------查询多条记录设置参数与查询一条记录相同-----------------------------------------------*
 *--------------------返回值数据类型也可是一个HashMap,即设置resultType属性即可,一般用于联合查询--------------------------*
 *------------------------resultMap就不写java代码了,在xml中最后有介绍,其它用法都差不多-----------------------------------*
 *-------------------------------------------------------------------------------------------------------------------------*/

}

查询语句<select>标签的属性描述

属性 描述
id 在命名空间中唯一的标识符,可以被用来引用这条语句
parameterType 将会传入这条语句的参数类的完全限定名或别名或一个hashmap
parameterMap 这是引用外部parameterMap的已经被废弃的方法。适用内联参数映射和parameterType属性
resultType 从这条语句中返回的期望类型的类的完全限定名或别名。注意集合情形,那应该是集合可以包含的类型,而不是集合。使用resultType或resultMap,但不能同时使用
resultMap 命名引用外部的resultMap。返回map是MyBatis最具力量的特性,对其有一个很好的理解的话,许多复杂映射的情形就能被解决了。使用resultMap或resultType,但不能同时使用
flushCache 将其设置为true,不论语句什么时候被调用,都会导致缓存被清空。默认值为false
useCache 将其设置为true,将会导致本条语句的结果被缓存。默认值为true
timeout 这个设置驱动程序等待数据库返回请求结果,并抛出异常事件的最大等待之。默认不设置(驱动自行处理)
fetchSize 这是暗示驱动程序每次批量返回的结果行数。默认不设置(驱动自行处理)
statementType STATEMENT,PREPARED或CALLABLE的一种。这会让MyBatis使用选择使用Statement,preparedStatement或CallableStatement,默认值:PREPARED
resultSetType FORWAARE_ONLY|SCROLL_SENSITIVE|SCROLL_INSENSITIVE中的一种。默认不设置(驱动自行处理)
posted @ 2017-12-03 23:56  小白知浅  阅读(491)  评论(0编辑  收藏  举报