MyBatis(3.2.3) - hello world

1. 创建数据表(MySQL):

DROP TABLE IF EXISTS `department`;
CREATE TABLE `department` (
  `did` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `dept_name` varchar(127) DEFAULT NULL,
  `address` varchar(127) DEFAULT NULL,
  `tel` varchar(16) DEFAULT NULL,
  PRIMARY KEY (`did`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

2. 新建 Maven 工程,配置 Maven 依赖:

<dependencies>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.2.3</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.22</version>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.14.4</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.5</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.5</version>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.8.1</version>
    </dependency>
</dependencies>

3. JavaBean:

package com.huey.hello.mybatis.beans;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Department {
    private int did;
    private String deptName;
    private String address;
    private String tel;
}

3. Mapper 接口:

package com.huey.hello.mybatis.mapper;

import com.huey.hello.mybatis.beans.Department;

public interface DepartmentMapper {

    public int insertDepartment(Department department);

    public Department getDepartmentById(int did);

}

4. 配置映射文件:

<?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">

<!--注意:此处的命名空间是 DepartmentMapper 的全限定类名-->
<mapper namespace="com.huey.hello.mybatis.mapper.DepartmentMapper">

    <!-- ResultMaps 被用来将 SQL SELECT 语句的结果集映射到 JavaBean 的属性中 -->
    <resultMap type="Department" id="deptMap">
        <!-- 映射主键 -->
        <id property="did" column="did" />
        <!-- 映射普通字段 -->
        <result property="deptName" column="dept_name"/>
        <result property="address" column="address"/>
        <result property="tel" column="tel"/>
    </resultMap>

    <!-- 添加部门记录 -->
    <!-- id 名称需要与 DepartmentMapper 中的方法签名一致 -->
    <!-- Department 这一别名在 mybatis-config.xml 中配置 -->
    <insert id="insertDepartment" parameterType="Department">
        insert into department(did, dept_name, address, tel)
        values(#{did}, #{deptName}, #{address}, #{tel})
    </insert>

    <!-- 根据 ID 查询部门记录 -->
    <select id="getDepartmentById" parameterType="int" resultMap="deptMap">
        select * from department where did=#{did}
    </select>

</mapper>

5. 配置 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>

    <!-- 设置别名 -->
    <typeAliases>
        <typeAlias type="com.huey.hello.mybatis.beans.Department" alias="Department" />
    </typeAliases>

    <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/mybatis" />
                <property name="username" value="root" />
                <property name="password" value="root" />
            </dataSource>
        </environment>
    </environments>

    <!-- mapper 对应的 xml 配置文件 -->
    <mappers>
        <mapper resource="com/huey/hello/mybatis/mapper/DepartmentMapper.xml" />
    </mappers>

</configuration>

6. 创建 SqlSessionFactory 单例类:

package com.huey.hello.mybatis.utils;

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

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

public class MyBatisSqlSessionFactory {

    private static SqlSessionFactory sqlSessionFactory;

    /**
     * 加载 mybatis-config.xml,创建 SqlSessionFactory 实例
     * 每个数据库环境应该就只有一个 SqlSessionFactory 对象实例
     * 所以使用单例模式只创建一个 SqlSessionFactory 实例
     * @return
     */
    public synchronized static SqlSessionFactory getSqlSessionFactory() {
        if (sqlSessionFactory == null) {
            InputStream inputStream;
            try {
                inputStream = Resources.getResourceAsStream("mybatis-config.xml");
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            } catch (IOException e) {
                throw new RuntimeException(e.getCause());
            }
        }
        return sqlSessionFactory;
    }

    public static SqlSession openSqlSession() {
        return getSqlSessionFactory().openSession();
    }
}

7. 业务逻辑:

package com.huey.hello.mybatis.serv;

import org.apache.ibatis.session.SqlSession;

import com.huey.hello.mybatis.beans.Department;
import com.huey.hello.mybatis.mapper.DepartmentMapper;
import com.huey.hello.mybatis.utils.MyBatisSqlSessionFactory;

public class DepartmentService {

    public int createDepartment(Department department) {
        int result = 0;
        /**
         * SqlSession 对象实例不是线程安全的,并且不被共享。
         * 每一个线程应该有它自己的 SqlSession 实例。
         * 所以 SqlSession 的作用域最好就是其所在方法的作用域。
         * 从 Web 应用程序角度上看,SqlSession 应该存在于 request 级别作用域上。
         */
        SqlSession sqlSession = MyBatisSqlSessionFactory.openSqlSession();
        try {
            DepartmentMapper deptMapper = sqlSession.getMapper(DepartmentMapper.class);
            result = deptMapper.insertDepartment(department);
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
        return result;
    }

    public Department getDepartmentById(int did) {
        Department department = null;
        SqlSession sqlSession = MyBatisSqlSessionFactory.openSqlSession();
        try {
            DepartmentMapper deptMapper = sqlSession.getMapper(DepartmentMapper.class);
            department = deptMapper.getDepartmentById(did);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
        return department;
    }

}

8. 单元测试:

package com.huey.hello.mybatis.serv;

import org.junit.Test;

import com.huey.hello.mybatis.beans.Department;

public class DepartmentServiceTest {

    DepartmentService deptService = new DepartmentService();

    @Test
    public void testCreateDepartment() {
        Department department = new Department(1001, "研发部", "XX 路 YY 号", "010-55551234");
        deptService.createDepartment(department);
    }

    @Test
    public void testGetDepartmentById() throws Exception {
        int did = 1001;
        Department department = deptService.getDepartmentById(did);
        if (department != null) {
            System.out.println(department);
        }
    }

}
时间: 2024-07-28 20:24:02

MyBatis(3.2.3) - hello world的相关文章

使用MyBatis Generator自动生成实体、mapper和dao层

通过MyBatis Generator可以自动生成实体.mapper和dao层,记录一下怎么用的. 主要步骤: 关于mybatis从数据库反向生成实体.DAO.mapper: 参考文章:http://www.cnblogs.com/wangkeai/p/6934683.html第一种方式:main方法运行(推荐) 1.在pom.xml中加入插件依赖: 2.写mbgConfiguration.xml文件,jdbc.properties文件 3.写/SSM/src/main/java/main/Ge

SSM整合(spring,spirngmvc,mybatis)

整合思路   准备环境:导入jar包(spring mybatis  dbcp连接池  mysql驱动包 log4j) 工程结构: --------------------------- 1.  整合dao mybatis和spring进行整合   applicationContext-dao.xml 配置: 1.数据源 2.SqlSessionFactory 3.mapper扫描器 创建po以及mapper(通过逆向工程,这里不再演示) 针对综合查询mapper,一般情况会有关联查询,建议自定

SpringBoot 2.SpringBoot整合Mybatis

一.创建Springboot的配置文件:application.properties SpringApplication 会从 application.properties 文件中加载配置信息,下面是添加Spring配置信息的文件目录顺序: 当前目录下的/config子目录中 当前目录中 一个 classpath 包下的 /config 目录中 classpath 根目录中 大家根据自己习惯来即可. /application.properties 文件配置如下: spring.datasourc

springMVC+MyBatis+Spring 整合(3)

spring mvc 与mybatis 的整合. 加入配置文件: spring-mybaits.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xm

MyBatis学习(四)XML配置文件之SQL映射的XML文件

SQL映射文件常用的元素: 1.select 查询语句是MyBatis最常用的语句之一. 执行简单查询的select元素是非常简单的: <select id="selectUser" parameterType="int" resultType="hashmap"> SELECT * FROM PERSON WHERE ID = #{id} </select> 这个语句被称作selectUser,接受一个int类型的参数,

MyBatis框架中Mapper映射配置的使用及原理解析(七) MapperProxy,MapperProxyFactory

从上文<MyBatis框架中Mapper映射配置的使用及原理解析(六) MapperRegistry> 中我们知道DefaultSqlSession的getMapper方法,最后是通过MapperRegistry对象获得Mapper实例: public <T> T getMapper(Class<T> type, SqlSession sqlSession) { final MapperProxyFactory<T> mapperProxyFactory =

2017年9月3日 Spring及Mybatis中连接数据库的不同方式

连接数据库用spring和mybatis中使用的方法可以不同,mybaits可以不用写数据库的配置文件 Spring的连接方法 <!-- 读取属性文件(.properties)的内容 --> <!-- location:指定要读取的属性文件的位置及文件名. 注: classpath:表示依据类路径去查找 容器依据路径读取属性文件的内容, 并且将这些内容存放到Properties对象上 --> //数据库的登入数据文件 //文件名db.properties #db connectio

mybatis中&quot;#&quot;和&quot;$&quot;的区别

mybatis中"#"和"$"的区别 动态 sql 是 mybatis 的主要特性之一,在 mapper 中定义的参数传到 xml 中之后,在查询之前 mybatis 会对其进行动态解析.mybatis 为我们提供了两种支持动态 sql 的语法:#{} 以及 ${}. 在下面的语句中,如果 username 的值为 zhangsan,则两种方式无任何区别: select * from user where name = #{name}; select * from

mybatis中的mapper接口文件以及example类的实例函数以及详解

##Example example = new ##Example(); example.setOrderByClause("字段名 ASC"); //升序排列,desc为降序排列. example.setDistinct(false)//去除重复,boolean型,true为选择不重复的记录. Criteria criteria = new Example().createCriteria(); is null;is not null; equal to(value);not equ

mybatis与hibernate的区别

本文转载自:http://blog.csdn.net/wangpeng047/article/details/17038659 以前没怎么用过mybatis,只知道与hibernate一样是个orm数据库框架.随着使用熟练度的增加,发现它与hibernate区别是非常大的,结合至今为止的经验,总结出以下几点: 1. hibernate是全自动,而mybatis是半自动. hibernate完全可以通过对象关系模型实现对数据库的操作,拥有完整的JavaBean对象与数据库的映射结构来自动生成sql