MyBatis初学案例

3 篇文章 0 订阅

mybatis: 入门案例

实现步骤

  1. 新建student表

  2. 加入maven的mybatis坐标,mysql驱动坐标

  3. 创建实体类,student–保存表中的一行数据

  4. 创建持久层dao接口,定义操作数据库方法

  5. 创建一个mybatis使用配置文件
    叫做sql映射文件:写sql文件,一般一个表一个sql映射文件(xml文件)。

  6. 创建一个mybatis的主配置文件:
    一个项目就一个主配置文件:提供数据库连接信息。

  7. 创建使用mybatis类。
    通过mybatis访问数据库。

pom.xml

  <dependencies>
   <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
   </dependency>

   <!--  mybatis依赖-->
   <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.1</version>
   </dependency>

   <!--  mysql驱动-->
   <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.15</version>
   </dependency>

</dependencies>

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>
   <!--  控制mybatis全局行为  -->
   <settings>
      <setting name="logImpl" value="STDOUT_LOGGING"/>
   </settings>
   <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/springdb?useUnicode=true&amp;characterEncoding=utf8"/>
            <property name="username" value="root"/>
            <property name="password" value="111111"/>
         </dataSource>
      </environment>
   </environments>
   <!--  sql mapper(映射文件)位置  -->
   <mappers>
      <mapper resource="com/xiaole/dao/studentdao.xml"/>
   </mappers>
</configuration>

mybatisUtil

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 java.io.IOException;
import java.io.InputStream;

public class MyBatisUtil {
    private static SqlSessionFactory factory = null;
    static {
        String config = "mybatis.xml";
        try {
            InputStream in = Resources.getResourceAsStream(config);
            factory = new SqlSessionFactoryBuilder().build(in);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession getSqlSession(){
        SqlSession sqlSession = null;
        if (factory != null) {
            sqlSession = factory.openSession(true);
        }
        return sqlSession;
    }
}

使用Util

SqlSession sqlSession = MyBatisUtil.getSqlSession();
StudentDao dao = sqlSession.getMapper(StudentDao.class);

接口参数使用

import com.xiaole.domain.Student;
import com.xiaole.vo.QueryParam;
import org.apache.ibatis.annotations.Param;

import java.util.List;
import java.util.Map;

// 接口操作student
public interface StudentDao {
    public Student selectStudentById(Integer id);

    // (重点)多个参数在类型前面加@param
    public List<Student> selectMultiParam(@Param("myName") String name, @Param("myAge") Integer age);

    // (重点)传递对象
    public List<Student> selectMultiObject(QueryParam param);

    public List<Student> selectMultiStudent(Student student);

    // 使用参数位置
    public List<Student> selectMultiPosition(String name, Integer age);

    // 使用map传值
    public List<Student> selectMultiMap(Map<String, Object> map);

    // 使用$
    public List<Student> selectUse$(@Param("name") String name);

    // 使用$替换列
    public List<Student> selectUse$Order(@Param("colName") String colName);

}

student.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.xiaole.dao.StudentDao">
    <select id="selectStudentById" resultType="com.xiaole.domain.Student">
        select id, name, age, email from student where id=#{id}
    </select>
    <!--  多个参数  -->
    <select id="selectMultiParam" resultType="com.xiaole.domain.Student">
        select id, name, age, email from student where name=#{myName} or age=#{myAge}
    </select>
    
    <!--
       传递对象:
           完整语法方式:#{属性名,javaType=java.lang.String,jdbcType=VARCHAR}
           简化方式:#{属性名},其他通过mybatis通过反射实现
    -->
    <select id="selectMultiObject" resultType="com.xiaole.domain.Student">
        select id, name, age, email from student where name=#{paramName} or age=#{paramAge}
    </select>

    <select id="selectMultiStudent" resultType="com.xiaole.domain.Student">
        select id, name, age, email from student where name=#{name} or age=#{age}
    </select>

    <!--  多个参数使用位置  -->
    <select id="selectMultiPosition" resultType="com.xiaole.domain.Student">
        select id, name, age, email from student where name=#{arg0} or age=#{arg1}
    </select>

    <!--  多个参数使用map  -->
    <select id="selectMultiMap" resultType="com.xiaole.domain.Student">
        select id, name, age, email from student where name=#{myName} or age=#{myAge}
    </select>

    <!--  $与#的区别:
        $连接sql 使用statement 效率低,sql注入,常用于替换列名或表名,确定数据是安全的
        #占位符 使用preparedStatement
    -->
    <select id="selectUse$" resultType="com.xiaole.domain.Student">
        select * from student where name=${name}
    </select>

    <select id="selectUse$Order" resultType="com.xiaole.domain.Student">
        select * from student order by ${colName}
    </select>

</mapper>

测试案例

    @Test
    public void testSelectStudentById() {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        StudentDao dao = sqlSession.getMapper(StudentDao.class);
        // 调用dao方法,进行数据库操作
        Student student = dao.selectStudentById(1002);
        System.out.println(student.toString() );
        sqlSession.close();
    }

   @Test
   public void selectMultiParam(){
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        StudentDao dao = sqlSession.getMapper(StudentDao.class);
        List<Student> students = dao.selectMultiParam("张三", 20);
        students.forEach(student -> System.out.println(student));
        sqlSession.close();
        }

   @Test
   public void selectMultiObject(){
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        StudentDao dao = sqlSession.getMapper(StudentDao.class);
        QueryParam param = new QueryParam("张飞", 18);
        List<Student> students = dao.selectMultiObject(param);
        students.forEach(student -> System.out.println(student));
        sqlSession.close();
        }

   @Test
   public void selectMultiStudent(){
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        StudentDao dao = sqlSession.getMapper(StudentDao.class);
        Student student = new Student();
        student.setAge(20);
        student.setName("盾山");
        List<Student> students = dao.selectMultiStudent(student);
        students.forEach(stu -> System.out.println(stu));
        sqlSession.close();
        }

   @Test
   public void selectMultiPosition(){
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        StudentDao dao = sqlSession.getMapper(StudentDao.class);
        List<Student> students = dao.selectMultiPosition("盾山", 20);
        students.forEach(stu -> System.out.println(stu));
        sqlSession.close();
        }

   @Test
   public void selectMultiMap(){
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        StudentDao dao = sqlSession.getMapper(StudentDao.class);
        Map<String, Object> map = new HashMap<>();
        map.put("myName", "张三");
        map.put("myAge", 20);

        List<Student> students = dao.selectMultiMap(map);
        students.forEach(student -> System.out.println(student));
        sqlSession.close();
        }

   @Test
   public void selectUse$(){
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        StudentDao dao = sqlSession.getMapper(StudentDao.class);

        List<Student> students = dao.selectUse$("'张三'");
        students.forEach(student -> System.out.println(student));
        sqlSession.close();
        }

   @Test
   public void selectUse$Order(){
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        StudentDao dao = sqlSession.getMapper(StudentDao.class);
        List<Student> students = dao.selectUse$Order("id");
        students.forEach(student -> System.out.println(student));
        sqlSession.close();
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值