Java进阶知识32 mybatis(ibatis)入门CRUD操作【简单演示,只测DAO层】

本文知识点(目录):

      1、导读
          1.1、技术概述
          1.2、本文使用的jar包、项目结构图
      2、本文所有代码
          2.1、数据库脚本(oracle.sql)
          2.2、mybatis.xml 核心配置文件
          2.3、MyBatisUtils 工具类(用于连接数据库)
          2.4、Student 实体类
          2.5、Student 实体类的配置文件(StudentMapper.xml)
          2.6、DAO层 (StudentDao)
          2.7、测试类(StudentDaoTest)



1、导读              

1.1、技术概述

    a.本文使用的是Oracle+mybatis框架,只是演示/测试DAO层(连接数据库,进行数据测试);

    b.实现了CURD等操作:新增、修改、查询所有、根据id查询、删除、批量删除

    c.本项目的使用环境:MyEclipse10.7 + JDK1.8 + Oracle11g + mybatis3.1.1

1.2、本文使用的jar包、项目结构图

2、本文所有代码     

2.1、数据库脚本(oracle.sql)

 1 -- 创建表
 2 create table student(
 3     id number(6) primary key,
 4     name varchar2(20),
 5     sex number(1),
 6     age number(3),
 7     telphone varchar2(16)
 8 );
 9 
10 -- 创建序列
11 create sequence student_seq
12 minvalue 1    --最小值
13 maxvalue 99999    -- 最大值
14 increment by 1    --从1开始计数
15 start with 1    --每次加1
16 nocycle        --一直累加,不循环
17 nocache;    --不建缓冲区。
18 
19 create or replace trigger student_tg
20   before insert on student for each row 
21     begin
22       select student_seq.Nextval into:new.id from dual;
23   end;
24 
25 -- 插入数据
26 insert into student(name,sex,age,telphone) values('zhangsan',1,23,'18795901366');

2.2、mybatis.xml 核心配置文件

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 3 "http://mybatis.org/dtd/mybatis-3-config.dtd">
 4 <configuration>
 5     <environments default="development">
 6         <environment id="development">
 7             <transactionManager type="JDBC" />
 8             <dataSource type="POOLED">
 9                 <property name="driver" value="oracle.jdbc.driver.OracleDriver" />
10                 <property name="url" value="jdbc:oracle:thin:@localhost:1521:shoreid" />
11                 <property name="username" value="zhangsan" />
12                 <property name="password" value="123456" />
13             </dataSource>
14         </environment>
15     </environments>
16 
17     <mappers>
18         <mapper resource="com/shore/entity/StudentMapper.xml"/>
19     </mappers>
20 </configuration>

2.3、MyBatisUtils 工具类(用于连接数据库)

 1 package com.shore.utils;
 2 
 3 import java.io.Reader;
 4 
 5 import org.apache.ibatis.io.Resources;
 6 import org.apache.ibatis.session.SqlSession;
 7 import org.apache.ibatis.session.SqlSessionFactory;
 8 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
 9 
10 /**
11  * @author DSHORE/2020-3-11
12  *
13  */
14 public class MyBatisUtils {
15     private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
16     private static SqlSessionFactory sqlSessionFactory;
17     
18     static{
19         try {
20             //1、读取配置
21             Reader reader = Resources.getResourceAsReader("mybatis.xml");
22             //2、创建SqlSessionFactory
23             sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
24         } catch (Exception e) {
25             e.fillInStackTrace();
26             throw new RuntimeException(e);
27         }
28     }
29     
30     private MyBatisUtils() { }
31     
32     //获取SqlSession
33     public static SqlSession getSqlSession(){
34         SqlSession sqlSession = threadLocal.get();
35         if (sqlSession == null) {//如果上面获取不到SQLSession,将通过下面的方式来获取
36             sqlSession = sqlSessionFactory.openSession();
37         }
38         return sqlSession;
39     }
40     
41     //关闭SqlSession
42     public static void closeSqlSession() {
43         SqlSession sqlSession = threadLocal.get();
44         if (sqlSession != null) {
45             sqlSession.close();
46             threadLocal.remove();
47         }
48     }
49 }

2.4、Student 实体类

 1 package com.shore.entity;
 2 
 3 /**
 4  * @author DSHORE/2020-3-11
 5  *
 6  */
 7 public class Student {
 8     private Integer id;
 9     private String name;
10     private Integer sex;
11     private Integer age;
12     private String telphone;
13     
14     public Integer getId() {
15         return id;
16     }
17 
18     public void setId(Integer id) {
19         this.id = id;
20     }
21 
22     public String getName() {
23         return name;
24     }
25 
26     public void setName(String name) {
27         this.name = name;
28     }
29 
30     public Integer getSex() {
31         return sex;
32     }
33 
34     public void setSex(Integer sex) {
35         this.sex = sex;
36     }
37 
38     public Integer getAge() {
39         return age;
40     }
41 
42     public void setAge(Integer age) {
43         this.age = age;
44     }
45 
46     public String getTelphone() {
47         return telphone;
48     }
49 
50     public void setTelphone(String telphone) {
51         this.telphone = telphone;
52     }
53 
54     @Override
55     public String toString() {
56         return "Student [id=" + id + ", name=" + name + ", sex=" + sex
57                 + ", age=" + age + ", telphone=" + telphone + "]";
58     }
59 }

2.5、Student 实体类的配置文件(StudentMapper.xml)

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 3 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 4 
 5 <mapper namespace="student">
 6     <!--=======================查询============================= -->
 7     <!-- 1、查询所有 -->
 8     <select id="selectAll" resultType="com.shore.entity.Student">
 9         select * from student
10     </select>
11     
12     <!-- 2、根据id查询 -->
13     <select id="findById" parameterType="int" resultType="com.shore.entity.Student">
14         select * from student where id=#{id}
15     </select>
16 
17     <!-- 3、动态条件查询 -->
18     <select id="dynamicSelect" parameterType="map" resultType="com.shore.entity.Student">
19         select * from student
20         <where>
21             <if test="name != null">
22                 and name = #{name}
23             </if>
24             <if test="telphone != null">
25                 and telphone = #{telphone}
26             </if>
27         </where>
28     </select>
29 
30     <!--=======================4、新增============================= -->
31     <insert id="dynamicInsert" parameterType="com.shore.entity.Student">
32         insert into student(name,sex,age,telphone)
33          values(#{name},#{sex},#{age},#{telphone})
34     </insert>
35 
36     <!--=======================5、更新============================= -->
37     <update id="dynamicUpdate" parameterType="com.shore.entity.Student">
38         update student
39         set name=#{name},
40         sex=#{sex},
41         age=#{age},
42         telphone=#{telphone}
43         where id=#{id}
44     </update>
45 
46     <!--=======================6、删除============================= -->
47     <delete id="deleteById" parameterType="int">
48         delete from student where id=#{id}
49     </delete>
50     
51     <!--=======================7、批量删除============================= -->
52     <delete id="batchDeleteById">
53         delete from student where id in 
54         <foreach item="ids" collection="list" open="(" separator="," close=")">
55             #{ids}
56         </foreach>
57     </delete>
58 </mapper>

2.6、DAO层 (StudentDao)

为了方便,此处不写接口,我直接写实现类

  1 package com.shore.dao;
  2 
  3 import java.util.ArrayList;
  4 import java.util.HashMap;
  5 import java.util.List;
  6 import java.util.Map;
  7 
  8 import org.apache.ibatis.session.SqlSession;
  9 
 10 import com.shore.entity.Student;
 11 import com.shore.utils.MyBatisUtils;
 12 
 13 /**
 14  * @author DSHORE/2020-3-11
 15  *
 16  */
 17 public class StudentDao {
 18     // 1、查询全部
 19     public List<Student> listAll() {
 20         List<Student> bosses = new ArrayList<Student>();
 21         SqlSession sqlSession = MyBatisUtils.getSqlSession();
 22         try {
 23             bosses = sqlSession.selectList("student.selectAll");
 24         } catch (Exception e) {
 25             // sqlSession.rollback(); //事务回滚
 26             System.out.println("error:" + e.getMessage());//获取异常信息,打印到控台
 27         } finally {
 28             // sqlSession.commit(); //查询操作不用提交、不用回滚
 29             MyBatisUtils.closeSqlSession();//关闭SqlSession
 30         }
 31         return bosses;
 32     }
 33     
 34     // 2、根据id查询
 35     public Student findById(int id) {
 36         Student student = null;
 37         SqlSession sqlSession = MyBatisUtils.getSqlSession();
 38         try {
 39             List<Student> students = sqlSession.selectList("student.findById", id);
 40             if (students != null && students.size() > 0) {
 41                 student = students.get(0);
 42             }
 43         } catch (Exception e) {
 44             System.out.println("error:" + e.getMessage());//获取异常信息,打印到控台
 45         } finally {
 46             MyBatisUtils.closeSqlSession();//关闭SqlSession
 47         }
 48         return student;
 49     }
 50     
 51     // 3、动态条件查询
 52     public List<Student> dynamicSelect(String name, String telphone) {
 53         List<Student> students = new ArrayList<Student>();
 54         SqlSession sqlSession = MyBatisUtils.getSqlSession();
 55         try {
 56             Map<String, String> map = new HashMap<String, String>();
 57             map.put("name", name);
 58             map.put("telphone", telphone);
 59             students = sqlSession.selectList("student.dynamicSelect", map);
 60         } catch (Exception e) {
 61             System.out.println("error:" + e.getMessage());
 62         } finally {
 63             MyBatisUtils.closeSqlSession();
 64         }
 65         return students;
 66     }
 67     
 68     // 4、动态插入
 69     public int dynamicInsert(Student student) {
 70         SqlSession sqlSession = MyBatisUtils.getSqlSession();
 71         try {
 72             return sqlSession.insert("student.dynamicInsert", student);
 73         } catch (Exception e) {
 74             sqlSession.rollback();//如果出现异常,则事务回滚
 75         } finally {
 76             sqlSession.commit();//提交事务
 77             MyBatisUtils.closeSqlSession();//关闭SqlSession
 78         }
 79         return 0;
 80     }
 81     
 82     // 5、动态更新
 83     public int dynamicUpdate(Student student) {
 84         SqlSession sqlSession = MyBatisUtils.getSqlSession();
 85         try {
 86             return sqlSession.update("student.dynamicUpdate", student);
 87         } catch (Exception e) {
 88             sqlSession.rollback();
 89         } finally {
 90             sqlSession.commit();
 91             MyBatisUtils.closeSqlSession();
 92         }
 93         return 0;
 94     }
 95     
 96     // 6、删除(根据id删除)
 97     public int deleteByInt(int id) {
 98         SqlSession sqlSession = MyBatisUtils.getSqlSession();
 99         try {
100             return sqlSession.delete("student.deleteById", id);
101         } catch (Exception e) {
102             sqlSession.rollback();
103         } finally {
104             sqlSession.commit();
105             MyBatisUtils.closeSqlSession();
106         }
107         return 0;
108     }
109     
110     // 7、批量删除
111     public int batchDeleteById(List<Integer> ids) {
112         SqlSession sqlSession = MyBatisUtils.getSqlSession();
113         try {
114             return sqlSession.delete("student.batchDeleteById", ids);
115         } catch (Exception e) {
116             sqlSession.rollback();
117             System.out.println("error:"+e.getMessage());
118         } finally {
119             sqlSession.commit();
120             MyBatisUtils.closeSqlSession();
121         }
122         return 0;
123     }
124 }

2.7、测试类(StudentDaoTest)

 1 package com.shore.test;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 
 6 import org.junit.Test;
 7 
 8 import com.shore.dao.StudentDao;
 9 import com.shore.entity.Student;
10 
11 /**
12  * @author DSHORE/2020-3-11
13  *
14  */
15 public class StudentDaoTest {
16     StudentDao studentDao = new StudentDao();
17     
18     @Test // 1、查询全部
19     public void testListAll() {
20         List<Student> students = studentDao.listAll();
21         if (students == null) {
22             System.out.println("students is null。");
23         } else {
24             //返回值:Student [id=1, name=zhangsan, sex=0, age=26, telphone=12345678900]
25             System.out.println(students.get(0));
26         }
27     }
28     
29     @Test // 2、根据id查询
30     public void testFindById() {
31         Student student = studentDao.findById(1);
32         //返回值:Student [id=1, name=zhangsan, sex=0, age=26, telphone=12345678900]
33         System.out.println(student);
34     }
35     
36     @Test // 3、动态条件查询
37     public void testDynamicSelect() {
38         List<Student> students = studentDao.dynamicSelect(null, "18795901366");
39         List<Student> students2 = studentDao.dynamicSelect("zhangsan","12345678900");
40         System.out.println(students.size());//返回值:1
41         //返回值:Student [id=1, name=zhangsan, sex=0, age=26, telphone=12345678900]
42         System.out.println(students2.get(0));
43     }
44     
45     // 4、动态插入
46     @Test
47     public void testDynamicInsert() {
48         Student student = new Student();
49         student.setName("王五");
50         student.setSex(1);//0代表男,1代表女
51         student.setAge(26);
52         student.setTelphone("13859501266");
53         System.out.println(studentDao.dynamicInsert(student));//返回值:1     说明插入数据成功
54     }
55     
56     // 5、动态更新
57         @Test
58     public void testDynamicUpdate() {
59         Student student = new Student();
60         student.setId(7);
61         student.setName("李四");
62         student.setSex(0);
63         student.setAge(23);
64         student.setTelphone("18795901366");
65         System.out.println(studentDao.dynamicUpdate(student));//返回值:1     说明更新数据成功
66     }
67     
68     // 6、删除
69     @Test
70     public void testDelete() {
71         System.out.println(studentDao.deleteByInt(3));//返回值:1    说明删除数据成功
72     }
73     
74     // 7、批量删除
75     @Test
76     public void testBatchDelete() {
77         List<Integer> ids = new ArrayList<Integer>();
78         ids.add(4);
79         ids.add(5);
80         ids.add(6);
81         System.out.println(studentDao.batchDeleteById(ids));//返回值:3    说明批量删除数据成功
82     }
83 }

 

到此已完结!有任何问题,可留言。

 

 

mybatis单向一对一关联映射:https://www.cnblogs.com/dshore123/p/12489304.html
mybatis单向一对多关联映射:https://www.cnblogs.com/dshore123/p/12493450.html
mybatis单向多对多关联映射:https://www.cnblogs.com/dshore123/p/12526016.html

 

 

 

 

 

原创作者:DSHORE

作者主页:http://www.cnblogs.com/dshore123/

原文出自:https://www.cnblogs.com/dshore123/p/12463550.html

版权声明:欢迎转载,转载务必说明出处。(如果本文对您有帮助,可以点击一下右下角的 推荐,或评论,谢谢!

posted @ 2020-03-11 17:03  DSHORE  阅读(250)  评论(0编辑  收藏  举报