(1) --- mybatis entry mybatis framework

What MyBatis that?

  MyBatis This is an open source project iBatis apache 2010 migration project by the apache software foundation to google code, and changed its name to MyBatis, essentially Mybatis to ibatis some improvements. Currently mybatis hosted on github. git (Distributed version control, comparison of the current flow)
  MyBatis is an excellent persistence framework, the process of its operation jdbc database encapsulation, so that developers only need to focus on SQL itself, without the need to spend energy to processing such as registration drive Create Connection created Statement, set the parameters manually, the result set retrieval jdbc complicated procedure code.
  Various statement (statement, preparedStatemnt, CallableStatement) Mybatis xml or annotation by way arranged to be performed together, and the final map generation sql statement executed by a java object and the sql statement, sql and executed by the Last frame mybatis mapped into java objects and return.

 mybatis architecture

Setup the development environment

(1) leader packet

(2) into the profile

 

I'm new here in a project file and the file src same level, to separate the relevant mybatis profiles and src files, and looked interface is more clear, because you certainly have to ssh to develop other configuration files

log4j.properties here mainly to see in the background, output is more clear execution flow, this can not happen.

(3) with the relevant documents required attributes

  User.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">
<!-- namespace命名空间,为了对sql语句进行隔离,方便管理,mapper开发dao方式,使用namespace有特殊作用 -->
<mapper namespace="test">
<!-- 在mapper.xml文件中配置很多的sql语句,执行每个sql语句时,封装为MappedStatement对象
    mapper.xml以statement为单位管理sql语句
 -->
    <!-- 根据id查询用户信息 -->
    <!-- 
        id:唯一标识 一个statement
        #{}:表示 一个占位符,如果#{}中传入简单类型的参数,#{}中的名称随意
        parameterType:输入 参数的类型,通过#{}接收parameterType输入 的参数
        resultType:输出结果 类型,不管返回是多条还是单条,指定单条记录映射的pojo类型
     -->
    <select id="findUserById" parameterType="int" resultType="com.study.model.User">
        SELECT * FROM USER WHERE id= #{id}
    </select>
    
    <!-- 根据用户名称查询用户信息,可能返回多条
    ${}:表示sql的拼接,通过${}接收参数,将参数的内容不加任何修饰拼接在sql中。
     -->
    <select id="findUserByName" parameterType="java.lang.String" resultType="com.study.model.User">
        select * from user where username like '%${value}%'
    </select>
    
    <!-- 添加用户
    parameterType:输入 参数的类型,User对象 包括 username,birthday,sex,address
    #{}接收pojo数据,可以使用OGNL解析出pojo的属性值
    #{username}表示从parameterType中获取pojo的属性值
    selectKey:用于进行主键返回,定义了获取主键值的sql
    order:设置selectKey中sql执行的顺序,相对于insert语句来说
    keyProperty:将主键值设置到哪个属性
    resultType:select LAST_INSERT_ID()的结果 类型


下文中insert失败:可能是这个原因

SELECT LAST_INSERT_ID():得到刚 insert 进去记录的主键值,只适用与自增主键

引自: https://blog.csdn.net/czd3355/article/details/71302441

<insert id="insertStudent" parameterType="com.czd.mybatis01.bean.Student">
  INSERT stu(name)VALUES (#{name})
  <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
      SELECT LAST_INSERT_ID()
    </selectKey>
</insert>

     -->
    <insert id="insertUser" parameterType="com.study.model.User">
        <selectKey keyProperty="id" order="AFTER" resultType="int">
            select LAST_INSERT_ID()
        </selectKey>
        INSERT INTO USER(username,birthday,sex,address) VALUES(#{username},#{birthday},#{sex},#{address})
    </insert>
    
    <!-- 用户删除  -->
    <delete id="deleteUser" parameterType="int">
     delete from user where id=#{id}
    </delete>
    <!-- 用户更新 
    要求:传入的user对象中包括 id属性值
    -->
    <update id="updateUser" parameterType="com.study.model.User">
        update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id}
    </update>
</mapper>
复制代码

SqlMapConfig.xml

复制代码
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 和spring整合后 environments配置将废除-->
    <environments default="development">
        <environment id="development">
        <!-- 使用jdbc事务管理-->
            <transactionManager type="JDBC" />
        <!-- 数据库连接池-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8" />
                <property name="username" value="root" />
                <property name="password" value="root" />
            </dataSource>
        </environment>
    </environments>
    <!-- 加载mapper.xml -->
    <mappers>
        <mapper resource="sqlmap/User.xml" />
    </mappers>
</configuration>
复制代码

User.java

复制代码
public class User {
    private int id;
    private String username;// 用户姓名
    private String sex;// 性别
    private Date birthday;// 生日
    private String address;// 地址
   /*
    *提供set和get方法,和toString方法
    *
    */
}
复制代码





MybatisFirst 测试类,进行增删改查
复制代码
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
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 org.junit.Before;
import org.junit.Test;

import com.guigu.model.User;

public class MybatisFirst {
    // 会话工厂
    private SqlSessionFactory sqlSessionFactory;
    // 创建工厂
    @Before  //before在text标签之前执行,所以会创建好sqlSessionFactory对象
    public void init() throws IOException {
        // 配置文件(SqlMapConfig.xml)
        String resource = "SqlMapConfig.xml";
        // 加载配置文件到输入流
        InputStream inputStream = Resources.getResourceAsStream(resource);
        // 创建会话工厂
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }
   
    
    // 根据id查询用户(得到单条记录)
    @Test
    public void testFindUserById() {
        // 通过sqlSessionFactory创建sqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        // 通过sqlSession操作数据库
        // 第一个参数:statement的位置,等于namespace+statement的id
        // 第二个参数:传入的参数
        User user = sqlSession.selectOne("test.findUserById", 16);
        sqlSession.close();7
        System.out.println(user);
    }

    // 模糊查询(可能是单条也可能是多条)
    @Test
    public void testFindUserByName() {
        // 通过sqlSessionFactory创建sqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
       
        //selectList代表着返回是list集合
        List<User>  list = sqlSession.selectList("test.findUserByName", "小明");
       sqlSession.close();
        System.out.println(list.get(0).getUsername());
    }

    // 添加用户
    @Test
    public void testInsertUser() {
        // 通过sqlSessionFactory创建sqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
     
        User user = new User();
        user.setUsername("小小徐");
        user.setAddress("杭州市余杭区未来科技城");
        user.setBirthday(new Date());
        user.setSex("1");
        //insert代表插入
        sqlSession.insert("test.insertUser", user);
        //查看是不需要提交事物的,但是插入和修改是需要提交事物的
        sqlSession.commit();
        sqlSession.close();
        //这里输出的id竟然是0,有哪位大神解释下吗?-----看上方红色注释
        System.out.println("用户的id=" + user.getId());
    }

// 根据id删除用户 @Test public void testDeleteUser() {   // 通过sqlSessionFactory创建sqlSession   SqlSession sqlSession = sqlSessionFactory.openSession();   // delete代表删除用户 sqlSession.delete("test.deleteUser", 29); sqlSession.commit(); sqlSession.close(); } // 根据id更新用户 @Test public void testUpdateUser() { // 通过sqlSessionFactory创建sqlSession SqlSession sqlSession = sqlSessionFactory.openSession(); // 创建更新数据对象,要求必须包括 id User user = new User(); user.setId(40); user.setUsername("小小钟"); user.setAddress("杭州余杭区东西大道"); //user.setBirthday(new Date()); user.setSex("1"); //update更新数据 sqlSession.update("test.updateUser", user); sqlSession.commit(); sqlSession.close(); System.out.println("用户的id=" + user.getId()); } }
复制代码

mybatis与hibernate重要区别 

  企业开发进行技术选型 ,考虑mybatis与hibernate适用场景。
    mybatis:入门简单,程序容易上手开发,节省开发成本 。mybatis需要程序员自己编写sql语句,是一个不完全 的ORM框架,对sql修改和优化非常容易实现 。
         适合开发需求变更频繁的系统,比如:互联网项目。


    hibernate:入门门槛高,如果用hibernate写出高性能的程序不容易实现。hibernate不用写sql语句,是一个 ORM框架。
         适合需求固定,对象数据模型稳定,中小型项目,比如:企业OA系统。


  总之,企业在技术选型时根据项目实际情况,以降低成本和提高系统 可维护性为出发点进行技术选型。

 


总结
  SqlMapConfig.xml: 是mybatis全局配置文件,只有一个,名称不固定的,主要mapper.xml,mapper.xml中配置 sql语句

  mapper.xml: 是以statement为单位进行配置。(把一个sql称为一个statement),satatement中配置 sql语句、parameterType输入参数类型(完成输入映射)、resultType输出结果类型(完成输出映射)。还提供了parameterMap配置输入参数类型(过期了,不推荐使用了),还提供resultMap配置输出结果类型(完成输出映射)

  #{}: 表示一个占位符,向占位符输入参数,mybatis自动进行java类型和jdbc类型的转换。程序员不需要考虑参数的类型,

              比如:传入字符串,mybatis最终拼接好的sql就是参数两边加单引号。#{}接收pojo数据,可以使用OGNL解析出pojo的属性值

  ${}: 表示sql的拼接,通过${}接收参数,将参数的内容不加任何修饰拼接在sql中。${}也可以接收pojo数据,可以使用OGNL解析出pojo的属性值
    缺点:不能防止sql注入。


  selectOne: 用于查询单条记录,不能用于查询多条记录,否则异常:
      org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned by selectOne(), but found: 4

  selectList: 用于查询多条记录,可以用于查询单条记录的。

 

引用了博客:凌晨。。。三点,非常感谢!

 

Guess you like

Origin www.cnblogs.com/651434092qq/p/11101078.html