Mybatis 快速入门

      MyBatis 是支持普通 SQL 查询,存储过程和高级映射的优秀持久层框架。MyBatis 可以使用简单的 XML 或注解用于配置和原始映射,将接口和 Java 的 POJO映射成数据库中的记录.

1.创建Maven工程,编写pom.xml配置文件,引入jar

<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">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.self</groupId>
  <artifactId>mybatis</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>
  
    <!--引入项目依赖的jar包 -->
    <!-- SpringMVC、Spring --> 
    <dependencies>  
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.7.RELEASE</version>
        </dependency> 
        <!--JSR303数据校验支持  --> 
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>5.4.1.Final</version>
        </dependency> 
        <!-- Spring-Jdbc --> 
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.7.RELEASE</version>
        </dependency> 
        <!--Spring-test --> 
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.3.7.RELEASE</version>
        </dependency>


        <!-- Spring面向切面编程 --> 
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>4.3.7.RELEASE</version>
        </dependency>

        <!--MyBatis --> 
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.2</version>
        </dependency>
        <!-- MyBatis整合Spring的适配包 --> 
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>

        <!-- 数据库连接池、驱动 --> 
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1</version>
        </dependency> 
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.41</version>
        </dependency>  
        <!-- junit --> 
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies> 
</project>

2.Spring整合mybatis

  2.1  数据库连接信息db.properties

jdbc.jdbcUrl=jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=UTF-8
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=000111

  2.2 mybatis配置文件mybatis-config.xml

<?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>
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    
    <typeAliases>
        <package name="com.ssm.bean"/>
    </typeAliases> 
</configuration>

 2.3 Spring整合

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
 
    <!-- Spring的配置文件,这里主要配置和业务逻辑有关的 -->
    <!--=================== 数据源,事务控制,xxx ================-->
    <context:property-placeholder location="classpath:db.properties" />
    <bean id="pooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
        <property name="driverClass" value="${jdbc.driverClass}"></property>
        <property name="user" value="${jdbc.user}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

    <!--================== 配置和MyBatis的整合=============== -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 指定mybatis全局配置文件的位置 -->
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
        <property name="dataSource" ref="pooledDataSource"></property>
        <!-- 指定mybatis,mapper文件的位置 -->
        <property name="mapperLocations" value="classpath:mapper/*.xml"></property>
    </bean>

    <!-- 配置扫描器,将mybatis接口的实现加入到ioc容器中 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--扫描所有dao接口的实现,加入到ioc容器中 -->
        <property name="basePackage" value="com.ssm.dao"></property>
    </bean>
   
    <!-- ===============事务控制的配置 ================-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--控制住数据源  -->
        <property name="dataSource" ref="pooledDataSource"></property>
    </bean>
    <!--开启基于注解的事务,使用xml配置形式的事务(必要主要的都是使用配置式)  -->
    <aop:config>
        <!-- 切入点表达式 -->
        <aop:pointcut expression="execution(* com.ssm.service..*(..))" id="txPoint"/>
        <!-- 配置事务增强 -->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/>
    </aop:config>
    
    <!--配置事务增强,事务如何切入  -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- 所有方法都是事务方法 -->
            <tx:method name="*"/>
            <!--以get开始的所有方法  -->
            <tx:method name="get*" read-only="true"/>
        </tx:attributes>
    </tx:advice>
    
    <!-- Spring配置文件的核心点(数据源、与mybatis的整合,事务控制) -->
    
</beans>

3.编写测试模块

  3.1 JavaBean

 1 package com.ssm.bean;
 2 
 3 public class Department {
 4     private Integer deptId;
 5     private String deptNo;
 6 
 7     private String deptName;  
 8 
 9     public String getDeptNo() {
10         return deptNo;
11     }
12 
13     public void setDeptNo(String deptNo) {
14         this.deptNo = deptNo;
15     }
16 
17     public Department() {
18         super();
19         // TODO Auto-generated constructor stub
20     }
21 
22      
23 
24     public Department(Integer deptId, String deptNo, String deptName) {
25         super();
26         this.deptId = deptId;
27         this.deptNo = deptNo;
28         this.deptName = deptName;
29     }
30 
31     public Integer getDeptId() {
32         return deptId;
33     }
34 
35     public void setDeptId(Integer deptId) {
36         this.deptId = deptId;
37     }
38 
39     public String getDeptName() {
40         return deptName;
41     }
42 
43     public void setDeptName(String deptName) {
44         this.deptName = deptName == null ? null : deptName.trim();
45     }
46 
47     @Override
48     public String toString() {
49         return "Department [deptId=" + deptId + ", deptNo=" + deptNo + ", deptName=" + deptName + "]";
50     }
51     
52     
53 }
View Code

  3.2 Dao层接口

 1 package com.ssm.dao;
 2 
 3 import com.ssm.bean.Department;
 4 
 5 public interface DepartmentMapper { 
 6 
 7    
 8     /**
 9      * 添加记录
10      * @param dept
11      * @return
12      */
13     int insertSelective(Department dept);
14  
15 
16     /**
17      * 查询记录
18      * @param deptId
19      * @return
20      */
21     Department selectByPrimaryKey(Integer deptId);
22 
23   
24 }
View Code

  3.3 mapper.xml映射文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ssm.dao.DepartmentMapper">
  <resultMap id="BaseResultMap" type="com.ssm.bean.Department">
    <id column="dept_id" jdbcType="INTEGER" property="deptId" />
    <result column="dept_name" jdbcType="VARCHAR" property="deptName" />
  </resultMap>

  <sql id="Base_Column_List">
    dept_id, dept_name,dept_no
  </sql>  
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from tbl_dept
    where dept_id = #{deptId,jdbcType=INTEGER}
  </select>
  
  <insert id="insertSelective" parameterType="com.ssm.bean.Department">
    insert into tbl_dept
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="deptId != null">
        dept_id,
      </if>
      <if test="deptNo != null">
        dept_no,
      </if>
      <if test="deptName != null">
        dept_name,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="deptId != null">
        #{deptId,jdbcType=INTEGER},
      </if>
      <if test="deptName != null">
        #{deptNo,jdbcType=VARCHAR},
      </if>
      <if test="deptName != null">
        #{deptName,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
 
</mapper>
View Code

  3.4运行 

package com.ssm.test; 

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.ssm.bean.Department;
import com.ssm.dao.DepartmentMapper;

/** 
 *  使用Spring的单元测试,自动注入需要的组件
 *
 */ 
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:applicationContext.xml"})
public class TestOper {
    
    @Autowired
    DepartmentMapper departmentMapper; 
    
    /**
     * 查询数据
     */
    @Test
    public void testSelect(){ 
    Department department = departmentMapper.selectByPrimaryKey(4);
    System.out.println(department);
    }
    
    /**
     * 新增部门
     */
    @Test
    public void testInsert(){  
    departmentMapper.insertSelective(new Department(null,"002", "人力资源部")); 
    }

}

 

posted @ 2019-07-13 14:22  彩虹消失了  阅读(449)  评论(0编辑  收藏  举报