• Mybatis使用Dao代码方式CURD


    Mybatis 使用Dao代码方式进行增、删、改、查。

    1、Maven的pom.xml

     1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
     2     <modelVersion>4.0.0</modelVersion>
     3     <groupId>com.mcs</groupId>
     4     <artifactId>mybatis01</artifactId>
     5     <version>0.0.1-SNAPSHOT</version>
     6 
     7     <properties>
     8         <!-- Generic properties -->
     9         <java.version>1.8</java.version>
    10         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    11         <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    12         <!-- Custom properties -->
    13         <mybatis.version>3.3.0</mybatis.version>
    14     </properties>
    15 
    16     <dependencies>
    17         <!-- junit -->
    18         <dependency>
    19             <groupId>junit</groupId>
    20             <artifactId>junit</artifactId>
    21             <scope>test</scope>
    22         </dependency>
    23         <!-- log4j -->
    24         <dependency>
    25             <groupId>log4j</groupId>
    26             <artifactId>log4j</artifactId>
    27         </dependency>
    28         <dependency>
    29             <groupId>org.slf4j</groupId>
    30             <artifactId>slf4j-log4j12</artifactId>
    31         </dependency>
    32         <!-- 数据库连接驱动 -->
    33         <dependency>
    34             <groupId>mysql</groupId>
    35             <artifactId>mysql-connector-java</artifactId>
    36         </dependency>
    37         <!-- c3p0 -->
    38         <dependency>
    39             <groupId>com.mchange</groupId>
    40             <artifactId>c3p0</artifactId>
    41         </dependency>
    42 
    43         <!-- mybatis -->
    44         <dependency>
    45             <groupId>org.mybatis</groupId>
    46             <artifactId>mybatis</artifactId>
    47             <version>${mybatis.version}</version>
    48         </dependency>
    49         <dependency>
    50             <groupId>org.mybatis</groupId>
    51             <artifactId>mybatis-spring</artifactId>
    52             <version>1.2.3</version>
    53         </dependency>
    54         <dependency>
    55             <groupId>org.mybatis</groupId>
    56             <artifactId>mybatis-ehcache</artifactId>
    57             <version>1.0.0</version>
    58         </dependency>
    59     </dependencies>
    60 
    61     <dependencyManagement>
    62         <dependencies>
    63             <dependency>
    64                 <groupId>io.spring.platform</groupId>
    65                 <artifactId>platform-bom</artifactId>
    66                 <version>2.0.0.RELEASE</version>
    67                 <type>pom</type>
    68                 <scope>import</scope>
    69             </dependency>
    70         </dependencies>
    71     </dependencyManagement>
    72 
    73     <build>
    74         <finalName>mybatis</finalName>
    75         <plugins>
    76             <plugin>
    77                 <groupId>org.apache.maven.plugins</groupId>
    78                 <artifactId>maven-surefire-plugin</artifactId>
    79                 <version>2.19</version>
    80                 <configuration>
    81                     <!-- Maven 跳过运行 Test 代码的配置 -->
    82                     <skipTests>true</skipTests>
    83                 </configuration>
    84             </plugin>
    85         </plugins>
    86     </build>
    87 
    88 </project>
    View Code

    2、配置文件

    2.1、db.properties

    1 jdbc.driverClass = com.mysql.jdbc.Driver
    2 jdbc.jdbcUrl = jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8
    3 jdbc.user = root
    4 jdbc.password = root
    View Code

    2.2、mybatis.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 
     7     <!-- 配置属性,加载数据库配置参数 -->
     8     <properties resource="db.properties"></properties>
     9 
    10      <!-- 使用别名 -->
    11     <typeAliases>
    12         <!-- 为包下的所有文件设置别名,别名为类名,不分大小写 -->
    13         <package name="com.mcs.entity"/>
    14     </typeAliases>
    15 
    16     <!-- 和Spring整合后environments配置将废除 -->
    17     <environments default="mysql_developer">
    18         <environment id="mysql_developer">
    19             <!-- mybatis使用jdbc事务管理方式 -->
    20             <transactionManager type="JDBC" />
    21             <!-- mybatis使用连接池方式来获取连接 -->
    22             <dataSource type="POOLED">
    23                 <!-- 配置与数据库交互的4个必要属性 -->
    24                 <property name="driver" value="${jdbc.driverClass}" />
    25                 <property name="url" value="${jdbc.jdbcUrl}" />
    26                 <property name="username" value="${jdbc.user}" />
    27                 <property name="password" value="${jdbc.password}" />
    28             </dataSource>
    29         </environment>
    30     </environments>
    31     
    32     <!-- 加载映射文件     -->
    33     <mappers>        
    34         <mapper resource="com/mcs/mapper/EmployeeMapper.xml" />
    35         <mapper resource="com/mcs/mapper/DepartmentMapper.xml" />
    36         
    37         <!-- 自动加载包下的所有映射文件 -->
    38         <package name="com.mcs.mapper"/>
    39     </mappers>
    40 
    41 </configuration>
    View Code

    2.3、log4j.xml

     1 <?xml version="1.0" encoding="UTF-8" ?>
     2 <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
     3 <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
     4     <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
     5         <layout class="org.apache.log4j.PatternLayout">
     6             <param name="ConversionPattern" 
     7                 value="%-5p %d{MM-dd HH:mm:ss,SSS} %m  (%F:%L) 
    " />
     8         </layout>
     9     </appender>
    10     <logger name="java.sql">
    11         <level value="debug" />
    12     </logger>
    13     <logger name="org.apache.ibatis">
    14         <level value="debug" />
    15     </logger>
    16     <root>
    17         <level value="debug" />
    18         <appender-ref ref="STDOUT" />
    19     </root>
    20 </log4j:configuration>
    View Code

    3、MybatisUtil工具类

     1 package com.mcs.util;
     2 
     3 import java.io.IOException;
     4 import java.io.Reader;
     5 import java.sql.Connection;
     6 
     7 import org.apache.ibatis.io.Resources;
     8 import org.apache.ibatis.session.SqlSession;
     9 import org.apache.ibatis.session.SqlSessionFactory;
    10 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    11 
    12 /**
    13  * Mybatis 工具类
    14  */
    15 public class MybatisUtil {
    16     
    17     private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
    18     private static SqlSessionFactory sqlSessionFactory;
    19     
    20     /**
    21      * 加载位于src/mybatis.xml配置文件
    22      */
    23     static{
    24         try {
    25             Reader reader = Resources.getResourceAsReader("mybatis.xml");
    26             sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
    27         } catch (IOException e) {
    28             e.printStackTrace();
    29             throw new RuntimeException(e);
    30         }
    31     }
    32     /**
    33      * 禁止外界通过new方法创建 
    34      */
    35     private MybatisUtil(){}
    36     
    37     /**
    38      * 获取SqlSession
    39      */
    40     public static SqlSession getSqlSession(){
    41         //从当前线程中获取SqlSession对象
    42         SqlSession sqlSession = threadLocal.get();
    43         //如果SqlSession对象为空
    44         if(sqlSession == null){
    45             //在SqlSessionFactory非空的情况下,获取SqlSession对象
    46             sqlSession = sqlSessionFactory.openSession();
    47             //将SqlSession对象与当前线程绑定在一起
    48             threadLocal.set(sqlSession);
    49         }
    50         //返回SqlSession对象
    51         return sqlSession;
    52     }
    53     
    54     /**
    55      * 关闭SqlSession与当前线程分开
    56      */
    57     public static void closeSqlSession(){
    58         //从当前线程中获取SqlSession对象
    59         SqlSession sqlSession = threadLocal.get();
    60         //如果SqlSession对象非空
    61         if(sqlSession != null){
    62             //关闭SqlSession对象
    63             sqlSession.close();
    64             //分开当前线程与SqlSession对象的关系,目的是让GC尽早回收
    65             threadLocal.remove();
    66         }
    67     }
    68 
    69     public static void main(String[] args) {
    70         Connection conn = MybatisUtil.getSqlSession().getConnection();
    71         System.out.println(conn!=null?"连接成功":"连接失败");
    72     }
    73 }
    View Code

    4、Mapper映射文件

     1 <?xml version="1.0" encoding="UTF-8" ?>
     2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
     3 <mapper namespace="EmployeeMapper">
     4     <resultMap id="employeeResultMap" type="com.mcs.entity.Employee">
     5         <id column="id" property="id" jdbcType="INTEGER" />
     6         <result column="name" property="name" jdbcType="VARCHAR" />
     7         <result column="sex" property="sex" jdbcType="VARCHAR" />
     8         <result column="birthday" property="birthday" jdbcType="DATE" />
     9         <result column="email" property="email" jdbcType="VARCHAR" />
    10         <result column="telephone" property="telephone" jdbcType="VARCHAR" />
    11         <result column="cellphone" property="cellphone" jdbcType="VARCHAR" />
    12         <result column="address" property="address" jdbcType="VARCHAR" />
    13         <result column="department_id" property="departmentId" jdbcType="INTEGER" />
    14     </resultMap>
    15 
    16     <!-- 新增职员,并返回插入后的ID值 -->
    17     <insert id="add" keyColumn="id" keyProperty="id" useGeneratedKeys="true" parameterType="Employee">
    18         insert into t_employee
    19         ( name, sex, birthday, email, telephone, cellphone, address, department_id )
    20         values
    21         ( #{name}, #{sex}, #{birthday}, #{email}, #{telephone}, #{cellphone}, #{address}, #{departmentId} )
    22     </insert>
    23     
    24     <update id="updateById" parameterType="Employee">
    25         update t_employee
    26         set name = #{name,jdbcType=VARCHAR},
    27             sex = #{sex,jdbcType=VARCHAR},
    28             birthday = #{birthday,jdbcType=DATE},
    29             email = #{email,jdbcType=VARCHAR},
    30             telephone = #{telephone,jdbcType=VARCHAR},
    31             cellphone = #{cellphone,jdbcType=VARCHAR},
    32             address = #{address,jdbcType=VARCHAR},
    33             department_id = #{departmentId,jdbcType=INTEGER}
    34         where id = #{id,jdbcType=INTEGER}
    35     </update>
    36     
    37     <delete id="deleteById" parameterType="Integer" >
    38         delete from t_employee
    39         where id = #{id}
    40     </delete>
    41 
    42     <select id="findById"  parameterType="Integer" resultMap="employeeResultMap">
    43         select *
    44         from t_employee
    45         where id = #{id}
    46     </select>
    47     
    48     <select id="findAll" resultMap="employeeResultMap">
    49         select * 
    50         from t_employee
    51     </select>
    52     
    53 </mapper>
    View Code

    5、Dao层接口

     1 package com.mcs.dao;
     2 
     3 import java.util.List;
     4 
     5 import com.mcs.entity.Employee;
     6 
     7 public interface EmployeeDao {
     8     
     9     public Employee add(Employee employee) throws Exception;
    10     public void edit(Employee employee) throws Exception;
    11     public void deleteById(Integer id) throws Exception;
    12     public Employee findById(Integer id) throws Exception;
    13     public List<Employee> findAll() throws Exception; 
    14     
    15 }
    View Code

    6、Dao层实现类

     1 package com.mcs.dao.impl;
     2 
     3 import java.util.ArrayList;
     4 import java.util.List;
     5 
     6 import org.apache.ibatis.session.SqlSession;
     7 
     8 import com.mcs.dao.EmployeeDao;
     9 import com.mcs.entity.Employee;
    10 import com.mcs.util.MybatisUtil;
    11 
    12 public class EmployeeDaoImpl implements EmployeeDao {
    13 
    14     public Employee add(Employee employee) throws Exception {
    15         SqlSession sqlSession = null;
    16         try {
    17             sqlSession = MybatisUtil.getSqlSession();
    18             sqlSession.insert("EmployeeMapper.add", employee);
    19             sqlSession.commit();
    20         } catch (Exception e) {
    21             e.printStackTrace();
    22             sqlSession.rollback();
    23             throw e;
    24         } finally {
    25             MybatisUtil.closeSqlSession();
    26         }
    27         return employee;
    28     }
    29 
    30     public void edit(Employee employee) throws Exception {
    31         SqlSession sqlSession = null;
    32         try {
    33             sqlSession = MybatisUtil.getSqlSession();
    34             sqlSession.insert("EmployeeMapper.updateById", employee);
    35             sqlSession.commit();
    36         } catch (Exception e) {
    37             e.printStackTrace();
    38             sqlSession.rollback();
    39             throw e;
    40         } finally {
    41             MybatisUtil.closeSqlSession();
    42         }
    43     }
    44 
    45     public void deleteById(Integer id) throws Exception {
    46         SqlSession sqlSession = null;
    47         try {
    48             sqlSession = MybatisUtil.getSqlSession();
    49             sqlSession.insert("EmployeeMapper.deleteById", id);
    50             sqlSession.commit();
    51         } catch (Exception e) {
    52             e.printStackTrace();
    53             sqlSession.rollback();
    54             throw e;
    55         } finally {
    56             MybatisUtil.closeSqlSession();
    57         }
    58     }
    59 
    60     public Employee findById(Integer id) throws Exception {
    61         SqlSession sqlSession = null;
    62         Employee employee = new Employee();
    63         try {
    64             sqlSession = MybatisUtil.getSqlSession();
    65             employee = sqlSession.selectOne("EmployeeMapper.findById", id);
    66         } catch (Exception e) {
    67             e.printStackTrace();
    68             throw e;
    69         } finally {
    70             MybatisUtil.closeSqlSession();
    71         }
    72         return employee;
    73     }
    74 
    75     public List<Employee> findAll() throws Exception {
    76         SqlSession sqlSession = null;
    77         List<Employee> employees = new ArrayList<Employee>();
    78         try {
    79             sqlSession = MybatisUtil.getSqlSession();
    80             employees = sqlSession.selectList("EmployeeMapper.findAll");
    81         } catch (Exception e) {
    82             e.printStackTrace();
    83             throw e;
    84         } finally { 
    85             MybatisUtil.closeSqlSession();
    86         }
    87         return employees;
    88     }
    89 
    90 }
    View Code

    7、测试代码

     1 package com.mcs.test;
     2 
     3 import java.util.Date;
     4 import java.util.List;
     5 
     6 import org.apache.log4j.Logger;
     7 import org.junit.Before;
     8 import org.junit.Test;
     9 
    10 import com.mcs.dao.EmployeeDao;
    11 import com.mcs.dao.impl.EmployeeDaoImpl;
    12 import com.mcs.entity.Employee;
    13 
    14 public class TestEmployeeDao {
    15     /**
    16     * Logger for this class
    17     */
    18     private static final Logger logger = Logger.getLogger(TestEmployeeDao.class);
    19     
    20     
    21     private EmployeeDao employeeDao;
    22     
    23     @Before
    24     public void init() {
    25         employeeDao = new EmployeeDaoImpl();
    26     }
    27     
    28     @Test
    29     public void testFindById() throws Exception {
    30         Employee employee = employeeDao.findById(1);
    31         logger.debug(employee);
    32     }
    33     
    34     @Test
    35     public void testFindAll() throws Exception {
    36         List<Employee> employees = employeeDao.findAll();
    37         logger.debug(employees);
    38     }
    39     
    40     @Test
    41     public void testAdd() throws Exception {
    42         Employee employee = new Employee();
    43         employee.setName("赵小凤");
    44         employee.setSex("female");
    45         employee.setBirthday(new Date());
    46         employee.setEmail("xiaofeng@126.com");
    47         
    48         employee = employeeDao.add(employee);
    49         
    50         logger.debug(employee);
    51     }
    52     
    53     @Test
    54     public void testEditById() throws Exception {
    55         Employee employee = employeeDao.findById(7);
    56         employee.setDepartmentId(7);
    57         employee.setAddress("天津");
    58         
    59         employeeDao.edit(employee);
    60         
    61         logger.debug(employee);
    62     }
    63     
    64     @Test
    65     public void testDeleteById() throws Exception {
    66         Employee employee = employeeDao.findById(7);
    67         
    68         employeeDao.deleteById(7);
    69         
    70         logger.debug("已成功删除员工:"  + employee.getName());
    71     }
    72 
    73 }
    View Code
  • 相关阅读:
    How To Build CyanogenMod Android for smartphone
    CentOS安装Code::Blocks
    How to Dual boot Multiple ROMs on Your Android SmartPhone (Upto Five Roms)?
    Audacious——Linux音乐播放器
    How to Dual Boot Multiple ROMs on Your Android Phone
    Everything You Need to Know About Rooting Your Android Phone
    How to Flash a ROM to Your Android Phone
    什么是NANDroid,如何加载NANDroid备份?
    Have you considered compiled a batman-adv.ko for android?
    BATMAN—Better Approach To Mobile Adhoc Networking (B.A.T.M.A.N.)
  • 原文地址:https://www.cnblogs.com/maocs/p/5047860.html
Copyright © 2020-2023  润新知