• 02.Mybatis的动态代理方式实现增删改查


    动态代理的方式实现增删改查:

    通过约定的方式定位sql语句

    约定 > 配置文件 > 硬编码

    约定的目标是省略掉通过硬编码的方式定位sql的代码,通过接口直接定位出sql语句,以下代码为通过硬编码的方法定位sql:

     1      //读取conf.xml 配置文件
     2         Reader reader = Resources.getResourceAsReader("conf.xml");
     3         //创建sqlSessionFactory
     4         SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
     5         //创建session---> connection
     6         SqlSession session = sessionFactory.openSession();
     7         //statement ---> statement
     8         String sql = "com.offcn.entity.personMapper." + "selectPersonById";
     9         //查询一条数据
    10         Person person = session.selectOne(sql,1);
    11         //提交事务
    12         session.commit();
    13         System.out.println(person);
    14         //关闭连接
    15         session.close();

    通过约定的方式定位sql:

     1  Reader reader = Resources.getResourceAsReader("conf.xml");
     2 //创建一个sqlSessionFactory
     3 SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
     4 //创建一个sqlSession
     5 SqlSession session = sessionFactory.openSession();
     6 //用sqlSession定位sql
     7 PersonMapper personMapper = session.getMapper(PersonMapper.class);
     8 //通过接口中的方法找到sql语句并执行
     9 Person person = personMapper.queryPersonById(3);
    10 //提交事务
    11 session.commit();
    12 System.out.println(person);
    13 //关闭连接
    14 session.close();    

    接口定义的规则:

    1.方法名和mapper.xml文件中标签的id值相同

    2.方法的输入参数类型和mapper.xml文件中标签的parameterType类型一致

    3.方法的返回值和mapper.xml文件中标签的resultType类型一致

    定义接口的代码如下:

     1 package com.offcn.mapper;
     2 
     3 
     4 import java.util.List;
     5 
     6 import com.offcn.entity.Person;
     7 
     8 public interface PersonMapper {
     9     Person queryPersonById(int id);
    10     List<Person> queryAllPersons();
    11     void insertPerson(Person person);
    12     void deletePersonById(int id);
    13     void updatePersonById(Person person);
    14 }

    接口和映射文件的对应关系图示:

    匹配过程;(约定的过程)

    1.根据接口名找到mapper.xml文件(根据的是namespace=接口的全类名)

    2.根据接口的方法名找到mapper.xml文件中的sql标签(方法名=sql标签中的id值)

    以上两点可以保证当调用接口中的方法时,程序能自动定位到某一个Mapper.xml文件中的sql标签

     习惯:sql映射文件(mapper.xml)和接口放在同一个包中

    具体实现:

    1.实体类代码:

     1 package com.offcn.entity;
     2 
     3 import java.util.Date;
     4 
     5 public class Person {
     6     private int id;
     7     private String name;
     8     private Date dir;
     9     private String address;
    10     public Person() {
    11         super();
    12         // TODO Auto-generated constructor stub
    13     }public Person( String name, Date dir, String address) {
    14         this.name = name;
    15         this.dir = dir;
    16         this.address = address;
    17     }
    18     public Person(int id, String name, Date dir, String address) {
    19         super();
    20         this.id = id;
    21         this.name = name;
    22         this.dir = dir;
    23         this.address = address;
    24     }
    25     public int getId() {
    26         return id;
    27     }
    28     public void setId(int id) {
    29         this.id = id;
    30     }
    31     public String getName() {
    32         return name;
    33     }
    34     public void setName(String name) {
    35         this.name = name;
    36     }
    37     public Date getDir() {
    38         return dir;
    39     }
    40     public void setDir(Date dir) {
    41         this.dir = dir;
    42     }
    43     public String getAddress() {
    44         return address;
    45     }
    46     public void setAddress(String address) {
    47         this.address = address;
    48     }
    49     @Override
    50     public String toString() {
    51         return "Person [id=" + id + ", name=" + name + ", dir=" + dir + ", address=" + address + "]";
    52     }
    53     
    54 }

    2.映射文件mapper.xml代码:

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <!DOCTYPE mapper
     3   PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
     4   "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
     5 <mapper namespace="com.offcn.mapper.PersonMapper">
     6     <!-- 根据id查询 -->
     7   <select id="queryPersonById" parameterType="int" resultType="com.offcn.entity.Person">
     8     select * from person where id = #{id}
     9   </select>
    10   <!-- 查询所有 -->
    11   <select id="queryAllPersons"  resultType="com.offcn.entity.Person">
    12     select * from person
    13   </select>
    14   <!-- 增加 -->
    15   <insert id="insertPerson" parameterType="com.offcn.entity.Person">
    16       insert into person (name,bir,address) value (#{name},#{dir},#{address})
    17   </insert>
    18   <!-- 删除 -->
    19   <delete id="deletePersonById" parameterType="int">
    20       delete from person where id = #{id}
    21   </delete>
    22   <!-- 修改 -->
    23   <update id="updatePersonById" parameterType="com.offcn.entity.Person">
    24       update person set name = #{name},bir = #{dir},address = #{address} where id = #{id}
    25   </update>
    26 </mapper>

    3.接口代码:

     1 package com.offcn.mapper;
     2 import java.util.List;
     3 import com.offcn.entity.Person;
     4 public interface PersonMapper {
     5     Person queryPersonById(int id);
     6     List<Person> queryAllPersons();
     7     void insertPerson(Person person);
     8     void deletePersonById(int id);
     9     void updatePersonById(Person person);
    10 }

    4.全局配置文件conf.xml:

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <!DOCTYPE configuration
     3   PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
     4   "http://mybatis.org/dtd/mybatis-3-config.dtd">
     5 <configuration>
     6   <environments default="development">
     7     <environment id="development">
     8       <transactionManager type="JDBC"/>
     9       <dataSource type="POOLED">
    10         <property name="driver" value="com.mysql.jdbc.Driver"/>
    11         <property name="url" value="jdbc:mysql://localhost:3306/person?serverTimezone=UTC"/>
    12         <property name="username" value="root"/>
    13         <property name="password" value="root"/>
    14       </dataSource>
    15     </environment>
    16   </environments>
    17   <mappers>
    18     <mapper resource="com/offcn/mapper/personMapper.xml"/>
    19   </mappers>
    20 </configuration>

    5.测试类代码:

      1 package com.offcn.test;
      2 
      3 import java.io.IOException;
      4 import java.io.Reader;
      5 import java.util.Date;
      6 import java.util.List;
      7 
      8 import org.apache.ibatis.io.Resources;
      9 import org.apache.ibatis.session.SqlSession;
     10 import org.apache.ibatis.session.SqlSessionFactory;
     11 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
     12 
     13 import com.offcn.entity.Person;
     14 import com.offcn.mapper.PersonMapper;
     15 
     16 public class Test {
     17     public static void main(String[] args) throws IOException {
     18         //queryPersonById();
     19         //insertPerson();
     20         //deletePerson();
     21         updatePerosnById();
     22         queryAllPersons();
     23     }
     24     //根据id查询
     25     public static void queryPersonById() throws IOException {
     26         //读取conf.xml文件
     27         Reader reader = Resources.getResourceAsReader("conf.xml");
     28         //创建一个sqlSessionFactory
     29         SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
     30         //创建一个sqlSession
     31         SqlSession session = sessionFactory.openSession();
     32         //用sqlSession定位sql
     33         PersonMapper personMapper = session.getMapper(PersonMapper.class);
     34         //通过接口中的方法找到sql语句并执行
     35         Person person = personMapper.queryPersonById(3);
     36         //提交事务
     37         session.commit();
     38         System.out.println(person);
     39         //关闭连接
     40         session.close();
     41     }
     42     //查询所有的方法
     43     public static void queryAllPersons() throws IOException {
     44         //读取conf.xml文件
     45         Reader reader = Resources.getResourceAsReader("conf.xml");
     46         //创建sqlSessionFactory
     47         SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
     48         //创建一个sqlSession
     49         SqlSession session = sessionFactory.openSession();
     50         //通过session定位映射文件
     51         PersonMapper personMapper = session.getMapper(PersonMapper.class);
     52         //通过接口中的方法定位sql语句并执行
     53         List<Person> persons = personMapper.queryAllPersons();
     54         //提交事务
     55         session.commit();
     56         for (Person person : persons) {
     57             System.out.println(person);
     58         }
     59         //关闭连接
     60         session.close();
     61     }
     62     //增加的方法
     63     public static void insertPerson() throws IOException {
     64         //读取conf.xml文件
     65         Reader reader = Resources.getResourceAsReader("conf.xml");
     66         //创建sqlSessionFactory
     67         SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
     68         //创建sqlSession
     69         SqlSession session = sessionFactory.openSession();
     70         //通过sqlSession定位映射文件
     71         PersonMapper personMapper = session.getMapper(PersonMapper.class);
     72         //通过接口中的方法定位sql语句
     73         Person person = new Person("王大拿",new Date(),"天津");
     74         personMapper.insertPerson(person);
     75         //提交事务
     76         session.commit();
     77         System.out.println("增加成功");
     78         //关闭连接
     79         session.close();
     80     }
     81     //删除的方法
     82     public static void deletePerson() throws IOException {
     83         //读取conf.xml
     84         Reader reader = Resources.getResourceAsReader("conf.xml");
     85         //创建一个sqlSessionFactory
     86         SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
     87         //创建一个sqlSession
     88         SqlSession session = sessionFactory.openSession();
     89         //通过session定位映射文件
     90         PersonMapper personMapper = session.getMapper(PersonMapper.class);
     91         //通过接口中的方法定位sql语句
     92         personMapper.deletePersonById(1);
     93         //提交事务
     94         session.commit();
     95         System.out.println("删除成功");
     96         //关闭连接
     97         session.close();
     98     }
     99     //修改的方法
    100     public static void updatePerosnById() throws IOException {
    101         //读取conf.xml
    102         Reader reader = Resources.getResourceAsReader("conf.xml");
    103         //创建sqlSessionFactory
    104         SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
    105         //创建一个sqlSession
    106         SqlSession session = sessionFactory.openSession();
    107         //通过sqlSession定位樱色号文件
    108         PersonMapper personMapper = session.getMapper(PersonMapper.class);
    109         //通过接口中的方法定位sql
    110         Person person = new Person(3,"张三",new Date(),"江苏");
    111         personMapper.updatePersonById(person);
    112         //提交事务
    113         session.commit();
    114         System.out.println("修改成功");
    115         session.close();
    116     }
    117 }

     需要注意的注意事项:

    在全局配置文件conf.xml文件中,引入配置文件的方式有四种,常用以下两种:

    第一种:

    <mapper resource="com/offcn/mapper/studentMapper.xml"/>

    第二种:(要求接口和映射文件必须在同一个包下而且必须同名

    <package name="com.offcn.mapper"/>

    常见错误:

  • 相关阅读:
    机器学习:SVM(核函数、高斯核函数RBF)
    机器学习:SVM(非线性数据分类:SVM中使用多项式特征和核函数SVC)
    LeetCode566. Reshape the Matrix
    LeetCode 128. Longest Consecutive Sequence
    # 线程安全 & 线程安全函数 & 线程不安全函数
    Linux进程状态
    C++ 4种强制类型转换
    TCP超时重传、滑动窗口、拥塞控制、快重传和快恢复
    LeetCode 69. Sqrt(x)
    LeetCode543. Diameter of Binary Tree
  • 原文地址:https://www.cnblogs.com/man-tou/p/11333019.html
Copyright © 2020-2023  润新知