zoukankan      html  css  js  c++  java
  • MyBatis高级 注解开发

    常用注解介绍

    我们除了可以使用映射配置文件来操作以外,还可以使用注解形式来操作

    常用注解

    @Select(”查询的SQL语句“):执行查询操作注解

    @Insert(”新增的SQL语句“):执行新增操作注解

    @Update(”修改的SQL语句“):执行修改的操作注解

    @Delete(”删除的SQL语句“):执行删除操作注解

    注解实现查询操作

    创建接口和查询方法

    在核心配置文件中配置映射关系

    编写测试类

    注解实现新增操作

    创建新增方法

    编写测试类

    注解实现修改操作

    创建修改方法

    编写测试类

    注解实现删除操作

    创建删除方法

    编写测试类

     StudentMapper

    package com.itheima.mapper;
    
    import com.itheima.bean.Student;
    import org.apache.ibatis.annotations.Delete;
    import org.apache.ibatis.annotations.Insert;
    import org.apache.ibatis.annotations.Select;
    import org.apache.ibatis.annotations.Update;
    
    import java.util.List;
    
    public interface StudentMapper {
        //查询全部
        @Select("select * from Student")
        public abstract List<Student> selectAll();
        //新增操作
        @Insert("insert into Student values(#{id},#{name},#{age})")
        public abstract Integer insert(Student stu);
        //修改操作
        @Update("update Student set name=#{name},age=#{age} where id=#{id}")
        public abstract Integer update(Student stu);
        //删除操作
        @Delete("delete from Student where id=#{id}")
        public abstract Integer delete(Integer id);
    }
    

      Test01

    package com.itheima.test;
    
    import com.itheima.bean.Student;
    import com.itheima.mapper.StudentMapper;
    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.Test;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.List;
    
    public class Test01 {
           @Test
        public void selectAll() throws Exception {
            //1.加在核心配置文件
            InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
    
            //2.获取SqlSession工厂对象
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            //3.通过工厂对象获取SqlSession对象
            SqlSession sqlSession = sqlSessionFactory.openSession(true);
            //4.获取StudentMapper接口的实现类对象
            StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
            //5.调用实现类对象中的方法,接受结果
            List<Student> list = mapper.selectAll();
    
            //6.处理结果
            for (Student student : list) {
                System.out.println(student);
            }
    
            //7.释放资源
            sqlSession.close();
            is.close();
        }
        @Test
        public void insert() throws Exception {
            //1.加在核心配置文件
            InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
    
            //2.获取SqlSession工厂对象
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            //3.通过工厂对象获取SqlSession对象
            SqlSession sqlSession = sqlSessionFactory.openSession(true);
            //4.获取StudentMapper接口的实现类对象
            StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
            //5.调用实现类对象中的方法,接受结果
            Student stu=new Student(9,"王10",30);
            Integer insert = mapper.insert(stu);
    
            //6.处理结果
            System.out.println(insert);
    
            //7.释放资源
            sqlSession.close();
            is.close();
        }
        @Test
        public void update() throws Exception {
            //1.加在核心配置文件
            InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
    
            //2.获取SqlSession工厂对象
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            //3.通过工厂对象获取SqlSession对象
            SqlSession sqlSession = sqlSessionFactory.openSession(true);
            //4.获取StudentMapper接口的实现类对象
            StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
            //5.调用实现类对象中的方法,接受结果
            Student stu=new Student(9,"王11",40);
            Integer update = mapper.update(stu);
    
            //6.处理结果
            System.out.println(update);
    
            //7.释放资源
            sqlSession.close();
            is.close();
        }
        @Test
        public void delete() throws Exception {
            //1.加在核心配置文件
            InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
    
            //2.获取SqlSession工厂对象
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            //3.通过工厂对象获取SqlSession对象
            SqlSession sqlSession = sqlSessionFactory.openSession(true);
            //4.获取StudentMapper接口的实现类对象
            StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
            //5.调用实现类对象中的方法,接受结果
            Integer delete = mapper.delete(9);
    
            //6.处理结果
            System.out.println(delete);
    
            //7.释放资源
            sqlSession.close();
            is.close();
        }
    }
    

      MyBatisConfig.xml

    <?xml version="1.0" encoding="UTF-8" ?>
    <!--MyBatis的DTD约束-->
    <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
    
    <!--configuration 核心根标签-->
    <configuration>
    
        <!--引入数据库连接的配置文件-->
        <properties resource="jdbc.properties"/>
    
        <!--配置LOG4J-->
        <settings>
            <setting name="logImpl" value="log4j"/>
        </settings>
    
        <!--起别名-->
        <typeAliases>
            <package name="com.itheima.bean"/>
        </typeAliases>
    
        <!--environments配置数据库环境,环境可以有多个。default属性指定使用的是哪个-->
        <environments default="mysql">
            <!--environment配置数据库环境  id属性唯一标识-->
            <environment id="mysql">
                <!-- transactionManager事务管理。  type属性,采用JDBC默认的事务-->
                <transactionManager type="JDBC"></transactionManager>
                <!-- dataSource数据源信息   type属性 连接池-->
                <dataSource type="POOLED">
                    <!-- property获取数据库连接的配置信息 -->
                    <property name="driver" value="${driver}" />
                    <property name="url" value="${url}" />
                    <property name="username" value="${username}" />
                    <property name="password" value="${password}" />
                </dataSource>
            </environment>
        </environments>
        <!--配置映射关系-->
        <mappers>
            <package name="com.itheima.mapper"/>
        </mappers>
    
    </configuration>
    

      log4j.properties

    # Global logging configuration
    # ERROR WARN INFO DEBUG
    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=%5p [%t] - %m%n
    

      jdbc.properties

    driver=com.mysql.jdbc.Driver
    url=jdbc:mysql://192.168.23.129:3306/db3
    username=root
    password=root
    

      注解开发小结

    注解可以简化开发操作,省略映射配置文件的编写。

    常用注解

    @Select(”查询的SQL语句“):执行查询操作注解

    @Insert(”新增的SQL语句“):执行新增操作注解

    @Update(”修改的SQL语句“):执行修改的操作注解

    @Delete(”删除的SQL语句“):执行删除操作注解

    配置映射关系

    <mappers>

      <package name="接口所在包"/>

    </mappers>

  • 相关阅读:
    【CSS学习】--- 背景
    线程运行诊断
    Mysql变量、存储过程、函数、流程控制
    设计模式之外观模式(门面模式)
    Spring的JdbcTemplate使用教程
    @AspectJ注解的value属性
    自定义Yaml解析器替换Properties文件
    @Import导入自定义选择器
    Spring中Bean命名源码分析
    Java操作fastDFS
  • 原文地址:https://www.cnblogs.com/faded8679/p/14806303.html
Copyright © 2011-2022 走看看