mybatis小结-001

Posted

tags:

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

代码不能直接copy运行,有些内容是为了说明知识点

1,sqlMqpConfig.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>

    <!-- 引入外部属性文件 -->
    <properties resource="jdbc.properties" />
    
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driverClassName}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
            
            <!-- 
            <dataSource type="POOLED">
                <property name="driver" value="oracle.jdbc.driver.OracleDriver"/>
                <property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl"/>
                <property name="username" value="scott"/>
                <property name="password" value="tiger"/>
            </dataSource>
             -->
        </environment>
    </environments>
    
    <!-- 指定映射文件或映射类 -->
    <mappers>
        <mapper resource="sqlMap/emp.xml"/>
    </mappers>
    
</configuration>

2,log4j.properties

#在开发环境下,日志级别要设置成DEBUG,生产环境设置成info或error
log4j.rootLogger=DEBUG, stdout

#Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{HH:mm:ss,SSS} [%c] - %m%n

3, jdbc.properties

jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
jdbc.username=scott
jdbc.password=tiger

4, Emp.java

package com.mybatis.entity;

public class Emp {

    private String ename;
    
    private int empno;
    
    private String job;

    public String getEname() {
        return ename;
    }

    public void setEname(String ename) {
        this.ename = ename;
    }
    
    @Override
    public String toString(){
        return "Emp [ ename = " + ename + "; empno = " + empno + "]";
        
    }
    
    public Emp(int empno, String ename, String job){
        
        super();
        this.empno = empno;
        this.ename = ename;
        this.job = job;
    }

    public int getEmpno() {
        return empno;
    }

    public void setEmpno(int empno) {
        this.empno = empno;
    }

    public String getJob() {
        return job;
    }

    public void setJob(String job) {
        this.job = job;
    }
}

5, emp.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="test">


    <!-- #{id}如果传入参数是简单类型,名称任意 -->
    <!-- ${}表示拼接字符串,将接收到的参数内容不加修饰拼接到sql中
        会引起sql注入
        ${value}:接收输入参数内容,如果是简单类型,只能使用${value}
     -->
    <select id="findEmpByEmpNo" parameterType="int" resultType="com.mybatis.entity.Emp">
        select * from emp where empno =#{empno}
    </select>
    
    <select id="findEmpByJob" parameterType="java.lang.String" resultType="com.mybatis.entity.Emp">
        select ename from emp where job =#{job}
    </select>
    
    <!-- 模糊查询 -->
    <select id="findByName" parameterType="java.lang.String", resultType="com.mybatis.entity.Emp">
        select * from emp where empno like ‘%${value}%‘
    </select>
    
    <!-- 输入类型参数是pojo,mybatis通过OGNL获取对象属性值 
        //比如java中:System.out.println(emp.getID());
    // 检索时提交事务
            //sqlSession.commit();
            -->
    <insert id="save" parameterType="com.mybatis.entity.Emp">
        <!-- 将插入数据的主键返回(比如自增主键时),返回到user对象中
        SELECT LAST_INSERT_ID():得到insert进去记录的主键值,只适用于自增主键
        注:单独使用时返回0
        keyProperty:将查询到的主键值设置到parameterType指定的对象的那个属性中
        order:SELECT LAST_INSERT_ID()执行顺序,相对于insert语句来说
         -->
         <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
             SELECT LAST_INSERT_ID()
         </selectKey>
         
         <!-- 使用mysql的uuid()函数生成主键 
         执行过程:先使用uuid()获得主键,再将主键设置到user对象的id中
         其次在insert执行时,从user对象中取得id属性
         -->
         
         <selectKey keyProperty="id" order="BEFORE" resultType="java.lang.String">
             SELECT UUID()
         </selectKey>
         《此时需要传入id
         insert into emp(id,empno,ename,job) values (#{id},#{empno},#{ename},#{job})
        insert into emp(empno,ename,job) values (#{empno},#{ename},#{job})
    </insert>
    
    <update id="update" parameterType="com.mybatis.entity.Emp">
        update emp set ename=#{ename} where empno=#{empno}
    </update>
    
    <delete id="delete" parameterType="int">
        delete from emp where empno=#{empno}
    </delete>    

</mapper>
    

6, MybatisService.java

public class MybatisService {
    
    @Test
    public void findEmpByJobTest(){
        
        //mybatis 配置文件
        String resource = "SqlMapConfig.xml";
        InputStream inputStream = null;
        SqlSession  sqlSession = null;
        
        try {
            // 使用MyBatis提供的Resources类加载myBatis的配置文件(它也加载相关联的映射文件)
            inputStream = Resources.getResourceAsStream(resource);
            
            //构建sqlSession工厂
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            // 创建能执行映射文件中sql的sqlSession
            sqlSession = sqlSessionFactory.openSession();
            
            // Emp emp = sqlSession.selectOne("test.findEmpByEmpNo", 7369);
            List<Emp> emp = sqlSession.selectList("test.findEmpByJob", "CLERK");
            //System.out.println(emp.toString());
            
            // 更新时时提交事务
            //sqlSession.insert("test.save", emp);
            //sqlSession.commit();
            //System.out.println(emp.getID());
            
            
            System.out.println(emp);
            
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

}

7, 另外

非自增主键返回(使用uuid)
使用mysql的uuid()函数生成主键,需要修改表中id类型为String
执行思路:
先通过uuid查到主键,将主键输入到insert语句中
执行uuid语句顺序在insert前





以上是关于mybatis小结-001的主要内容,如果未能解决你的问题,请参考以下文章

MyBatis源码分析select源码分析及小结

MyBatis-05-笔记

001. MyBatis+SpringMVC+Spring[重置版]

Mybatis框架之动态SQL书写方式小结

学习记录001-007-阶段习题小结

Java Persistence with MyBatis 小结1