MyBatis(一)

  • 使用myBatis步骤
  1. 创建maven工程,添加依赖jar包
     1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     2     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
     3     <modelVersion>4.0.0</modelVersion>
     4     <groupId>cn.zjr</groupId>
     5     <artifactId>MyBatis-day01-config</artifactId>
     6     <version>0.0.1-SNAPSHOT</version>
     7     <dependencies>
     8           <dependency>
     9               <groupId>org.mybatis</groupId>
    10               <artifactId>mybatis</artifactId>
    11               <version>3.4.6</version>
    12           </dependency>
    13         <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    14         <dependency>
    15             <groupId>mysql</groupId>
    16             <artifactId>mysql-connector-java</artifactId>
    17             <version>5.1.47</version>
    18         </dependency>
    19         <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    20           <dependency>
    21               <groupId>junit</groupId>
    22               <artifactId>junit</artifactId>
    23               <version>4.12</version>
    24           </dependency>
    25     </dependencies>
    26 </project>


      

 

  2.创建全局配置文件  

  该配置文件包含了对 MyBatis 系统的核心设置,包含获取数据库连接实例的数据源(DataSource)和决定事务作用域和控制方式的事务管理器  TransactionManager)。    

<?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>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url"
                    value="jdbc:mysql://localhost:3306/testbatis?characterEncoding=utf-8" />
                <property name="username" value="root" />
                <property name="password" value="1234" />
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!-- 关联映射文件 -->
    <mapper resource="cn/zjr/pojo/UserMapper.xml"/>

    </mappers>

</configuration>

      

  3.定义User实体类

    

  4.创建映射文件UserMapper.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 <!-- namespace 名称空间:作用是用来区分各个xml映射文件的 -->
 6 <mapper namespace="cn.zjr.pojo.User">
 7     <select id="query" resultType="cn.zjr.pojo.User">
 8         select * from t_user
 9     </select>
10     <insert id="addUser" parameterType="cn.zjr.pojo.User">
11         insert into t_user(name,gender) values(#{name},#{gender})
12     </insert>
13     <update id="updateUser" parameterType="cn.zjr.pojo.User">
14         update t_user set name=#{name},gender=#{gender} where id=#{id}
15     </update>
16     <delete id="deleteUserById" parameterType="int">
17         delete from t_user where id=#{id}
18     </delete>
19 </mapper>

  5.将映射文件添加到主配置文件中

  

  6. 编写测试类(增删改查)

 1 package cn.zjr.test;
 2 import java.io.IOException;
 3 import java.io.InputStream;
 4 import java.util.List;
 5 
 6 import org.apache.ibatis.io.Resources;
 7 import org.apache.ibatis.session.SqlSession;
 8 import org.apache.ibatis.session.SqlSessionFactory;
 9 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
10 import org.junit.Test;
11 
12 import cn.zjr.pojo.User;
13 
14 public class MyBatisTest {
15     //查询
16     @Test
17     public void query() throws IOException {
18         //加载全局配置文件
19     InputStream in = Resources.getResourceAsStream("MyBatis-config.xml");
20     //获取SqlSessionFactory
21     SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
22     //获取SqlSession对象
23     SqlSession session = factory.openSession();
24     
25     //执行数据库操作   namespace+"."+id
26     List<User> list = session.selectList("cn.zjr.pojo.User.query");
27     for (User user : list) {
28         System.out.println(user);
29     }
30     //关闭
31     in.close();
32     
33     
34     }
35     //添加
36     @Test
37     public void addUser() throws IOException {
38         InputStream in = Resources.getResourceAsStream("MyBatis-config.xml");
39         SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
40         SqlSession session = factory.openSession();
41         //执行数据库操作
42         User user = new User();
43         user.setName("花花");
44         user.setGender("男");
45         int count = session.insert("cn.zjr.pojo.User.addUser", user);
46         session.commit();
47         System.out.println("影响的行数"+count);
48         session.close();
49     }
50     //修改
51     @Test
52     public void updateUser() throws IOException {
53         
54         InputStream in = Resources.getResourceAsStream("MyBatis-config.xml");
55         SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
56         SqlSession session = factory.openSession();
57         //执行数据库操作
58         User user = new User();
59         user.setId(3);
60         user.setName("Tony");
61         user.setGender("男");
62         int count = session.update("cn.zjr.pojo.User.updateUser", user);
63         session.commit();
64         System.out.println("影响的行数"+count);
65         session.close();
66     }
67     //删除
68     @Test
69     public void deleteUserById() throws IOException {
70         InputStream in = Resources.getResourceAsStream("MyBatis-config.xml");
71         SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
72         SqlSession session = factory.openSession();
73         int count = session.update("cn.zjr.pojo.User.deleteUserById", 7);
74         session.commit();
75         System.out.println("影响的行数"+count);
76         session.close();
77     }
81 }

  7.优化:

    封装获取Session和SqlSessionFactory对象的工具类 

package cn.zjr.util;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class Dbutils {
    private static InputStream in;
    private static SqlSessionFactory factory =null;
    
    public static SqlSessionFactory getSqlSessionFactory(){
        try {
            in=Resources.getResourceAsStream("mybatis-config.xml");
            factory = new SqlSessionFactoryBuilder().build(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return factory;
        
    } 
}

   通过代理模式实现对象创建

   

 1 package cn.zjr.test;
 2 
 3 import java.lang.reflect.InvocationHandler;
 4 import java.lang.reflect.Method;
 5 import java.lang.reflect.Proxy;
 6 import java.util.List;
 7 
 8 import org.apache.ibatis.session.SqlSession;
 9 
10 import cn.zjr.dao.IUserDao;
11 import cn.zjr.pojo.User;
12 import cn.zjr.util.Dbutils;
13 
14 public class TestProxy {
15     public static void main(String[] args) {
16         IUserDao proxy = (IUserDao) Proxy.newProxyInstance(TestProxy.class.getClassLoader(), new Class[] {IUserDao.class}, new InvocationHandler() {
17             
18             public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
19             SqlSession session = Dbutils.getSqlSessionFactory().openSession(true);
20             String methodName = method.getName();
21             String statement = IUserDao.class.getName()+"."+methodName;
22             if (methodName.contains("query")) {
23                 
24                 return session.selectList(statement,args);
25                 }
26             return null;
27             }
28         });
29         List<User> users = proxy.query();
30         for (User user : users) {
31             System.out.println(user);
32         }
33     
34     
35     }
36     
37 }

    对代理模式进行优化:使用MyBatis封装好的代理   

 1 package cn.zjr.test;
 2 
 3 import java.util.List;
 4 
 5 import org.apache.ibatis.session.SqlSession;
 6 
 7 import cn.zjr.dao.IUserDao;
 8 import cn.zjr.pojo.User;
 9 import cn.zjr.util.Dbutils;
10 
11 public class TestMyBatisProxy {
12     public static void main(String[] args) {
13         SqlSession session = Dbutils.getSqlSessionFactory().openSession();
14         IUserDao userDao = session.getMapper(IUserDao.class);
15         List<User> list = userDao.query();
16         for (User user : list) {
17             System.out.println(user);
18         }
19     }
20 }

  对映射文件UserMapper.xml进行优化,改写为IUserDao.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="cn.zjr.dao.IUserDao">
 6      <select id="query" resultType="cn.zjr.pojo.User">
 7          select * from t_user
 8      </select>
 9      <insert id="addUser" parameterType="cn.zjr.pojo.User">
10      
11          insert into t_user(name,gender) values(#{name},#{gender})
12      </insert>
13      <update id="updateUserById" parameterType="cn.zjr.pojo.User">
14          update t_user set name=#{name},gender=#{gender} where id=#{id}
15      </update>
16      <delete id="deleteById" parameterType="int">
17          delete from t_user where id=#{id}
18      
19      </delete>
20      <select id="queryById" resultType="cn.zjr.pojo.User">
21          select * from t_user where id=#{uid}
22      </select>
23  
24  </mapper>

  

 

posted on 2019-07-11 21:36  大魔王老Z  阅读(178)  评论(0编辑  收藏  举报

导航