Mybatis入门到精通:helloworld

官方地址:https://github.com/mybatis/mybatis-3

官方中文文档地址:http://www.mybatis.org/mybatis-3/zh/getting-started.html

项目代码: https://gitee.com/ganganbobo/mybatis-parent   里面的"mybatis-helloword模块"

一:准备工作

1、导入MyBatis的jar包和mysql连接驱动(maven):

<properties>
        <mybatis.version>3.4.1</mybatis.version>
        <mysql-connector.version>5.1.38</mysql-connector.version>
        <lombok.version>1.16.12</lombok.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatis.version}</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql-connector.version}</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

2、新建数据库和表,并在表中插入几条测试数据:

CREATE TABLE `tb_employee` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `last_name` varchar(20) DEFAULT NULL,
  `email` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

3、创建实体类对象:

import lombok.Data;

@Data
public class Employee {

    private Integer id;
    private String lastName;
    private String email;
}

二:以XML的方式构建SqlSessionFactory

public SqlSessionFactory getSqlSessionFactory() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        return new SqlSessionFactoryBuilder().build(inputStream);
    }

创建Employee实体类Sql映射文件:

EmployeeMapper.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.ganbo.mapper.EmployeeMapper">
    <select id="getEmpById" resultType="com.ganbo.entity.Employee">
		select id,last_name lastName,email from tb_employee where id = #{id}
	</select>

</mapper>

创建全局配置文件mybatis-conf.xml,该配置文件包含了对 MyBatis 系统的核心设置,包含获取数据库连接实例的数据源(DataSource)和决定事务作用域和控制方式的事务管理器(TransactionManager)。

<?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>
	<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:3306/mybatis" />
				<property name="username" value="root" />
				<property name="password" value="root" />
			</dataSource>
		</environment>
	</environments>
	<mappers>
		<mapper resource="EmployeeMapper.xml" />
	</mappers>
</configuration>

测试方法:

 /**
     * 1、根据xml配置文件(全局配置文件)创建一个SqlSessionFactory对象 有数据源一些运行环境信息
     * 2、sql映射文件;配置了每一个sql,以及sql的封装规则等。
     * 3、将sql映射文件注册在全局配置文件中
     * 4、写代码:
     * 1)、根据全局配置文件得到SqlSessionFactory;
     * 2)、使用sqlSession工厂,获取到sqlSession对象使用他来执行增删改查
     * 一个sqlSession就是代表和数据库的一次会话,用完关闭
     * 3)、使用sql的唯一标志来告诉MyBatis执行哪个sql。sql都是保存在sql映射文件中的。
     *
     * @throws IOException
     */
    @Test
    public void test() throws IOException {

        // 2、获取sqlSession实例,能直接执行已经映射的sql语句
        // sql的唯一标识:statement Unique identifier matching the statement to use.
        // 执行sql要用的参数:parameter A parameter object to pass to the statement.
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();

        SqlSession openSession = sqlSessionFactory.openSession();
        try {
            Employee employee = openSession.selectOne("com.ganbo.mapper.EmployeeMapper.getEmpById", 1);
            System.out.println(employee);
        } finally {
            openSession.close();
        }
    }

输出

Employee(id=1, lastName=ganbo, email=946211284@qq.com)

到此完毕,这是最原始的方式构建查询语句

 

现在比较流行的是以接口的方式使用Mybatis,创建接口Mapper:

import com.ganbo.entity.Employee;

public interface EmployeeMapper {

    Employee getEmpById(Integer id);

}

测试代码:

 @Test
    public void test01() throws IOException {
        // 1、获取sqlSessionFactory对象
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
        // 2、获取sqlSession对象
        SqlSession openSession = sqlSessionFactory.openSession();
        try {
            // 3、获取接口的实现类对象
            //会为接口自动的创建一个代理对象,代理对象去执行增删改查方法
            EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
            Employee employee = mapper.getEmpById(1);
            System.out.println(mapper.getClass());
            System.out.println(employee);
        } finally {
            openSession.close();
        }

    }

会得到跟上面同样的运行结果.

 

如有疑问,请在底部留言,我会一一回复大家!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值