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.0modelVersion>
  <groupId>com.selfgroupId>
  <artifactId>mybatisartifactId>
  <version>0.0.1-SNAPSHOTversion>
  <packaging>jarpackaging>
  
    
     
    <dependencies>  
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>4.3.7.RELEASEversion>
        dependency> 
         
        <dependency>
            <groupId>org.hibernategroupId>
            <artifactId>hibernate-validatorartifactId>
            <version>5.4.1.Finalversion>
        dependency> 
         
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>4.3.7.RELEASEversion>
        dependency> 
         
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-testartifactId>
            <version>4.3.7.RELEASEversion>
        dependency>


         
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-aspectsartifactId>
            <version>4.3.7.RELEASEversion>
        dependency>

         
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.4.2version>
        dependency>
         
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatis-springartifactId>
            <version>1.3.1version>
        dependency>

         
        <dependency>
            <groupId>c3p0groupId>
            <artifactId>c3p0artifactId>
            <version>0.9.1version>
        dependency> 
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.41version>
        dependency>  
         
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.12version>
        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">
 
    
    
    <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>

    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        
        <property name="configLocation" value="classpath:mybatis-config.xml">property>
        <property name="dataSource" ref="pooledDataSource">property>
        
        <property name="mapperLocations" value="classpath:mapper/*.xml">property>
    bean>

    
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        
        <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>
    
    <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="*"/>
            
            <tx:method name="get*" read-only="true"/>
        tx:attributes>
    tx:advice>
    
    
    
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", "人力资源部")); 
    }

}

 

你可能感兴趣的:(Mybatis 快速入门)