【Mybatis】(一)第一个mybatis实例

本文介绍如何使用MyBatis框架进行数据库操作。首先概述了MyBatis的基本概念,随后通过搭建开发环境、创建数据库表、定义实体类、配置MyBatis文件及编写测试代码等步骤,演示了如何实现数据查询。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、MyBatis简介

MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以对配置和原生Map使用简单的 XML 或注解,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。

2、Mybatis第一个程序

2.1 准备开发环境

这里写图片描述

2.2 添加jar包

【Mybatis】
      mybatis-3.4.6.jar

【MySQL】
      mysql-connector-java-5.1.42-bin.jar
这里写图片描述

2.3 创建数据库和表

数据库名为 mybatis,表名为 tb1_employee。

CREATE TABLE `tb1_employee` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `last_name` varchar(255) DEFAULT NULL,
  `gender` char(1) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8

insert  into `tb1_employee`(`id`,`last_name`,`gender`,`email`) values (2,'lhk','1','lhk@qq.com');

这里写图片描述

2.4 使用Mybatis查询数据

1、创建对应于数据库字段的实体类

package com.lhk.mybatis.beans;

public class Employee {

    private Integer id;
    private String lastName;
    private String email;
    private String gender;

    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
    @Override
    public String toString() {
        return "Employee [id=" + id + ", lastName=" + lastName + ", email=" + email + ", 
        gender=" + gender + "]";
    }
}

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>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <!-- 数据库连接的配置信息 驱动,URL,用户名,密码-->
            <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="13579" />
            </dataSource>
        </environment>
    </environments>

    <!-- 将我们写好的sql映射文件(EmployeeMapper.xml)一定要注册到全局配置文件(mybatis-config.xml)中 -->
    <mappers>
        <mapper resource="EmployeeMapper.xml" />
    </mappers>
</configuration>

3、定义操作表的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.lhk.mybatis.EmployeeMapper">

    <!-- namespace:名称空间
         id:sql的唯一标识
         resultType:返回值类型
         #{id}:从传递过来的参数中取出id值
     -->

    <select id="selectEmp" resultType="com.lhk.mybatis.beans.Employee">
        select id,last_name lastname,gender,email from tb1_employee where id = #{id}
    </select>
</mapper>

4、编写测试代码:执行定义的select语句

package com.lhk.mybatis.test;

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;
import org.junit.Test;

import com.lhk.mybatis.beans.Employee;

public class MyBatisTest {

    /**
     * 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 {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        /*2、获取sqlSession实例,能直接执行已经映射的sql语句*/
        SqlSession openSession = sqlSessionFactory.openSession();

        try {
            /* sql语句的唯一标识
               执行sql要用的参数 */                                           namespace+id
            Employee employee = openSession.selectOne("com.lhk.mybatis.EmployeeMapper.selectEmp", 2);
            System.out.println(employee);
        } finally {
            openSession.close(); // 关闭openSession       
        }   
    }
}

5、运行结果,成功查询出id为2的所有Employee数据
这里写图片描述

<?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.dao.BlogDao"> <resultMap type="Blog" id="blogResult"> <id column="blog_id" property="id" /> <result column="blog_title" property="subject"/> <result column="content" property="content"/> <!-- 映射关联的对象 --> <association property="author" javaType="Author"> <id column="id" property="blog_author_id"/> <result column="userName" property="userName"/> <result column="password" property="password"/> </association> <collection property="comments" ofType="Comment"> <id property="id" column="post_id"/> <result property="subject" column="post_subject"/> <result property="content" column="content"/> </collection> </resultMap> <sql id="where"> <where>userName =#{userName}</where> </sql> <select id="countAll" resultType="int"> select count(*) c from blog; </select> <select id="countSome" resultType="int" parameterType="String"> select count(*) c from blog <include refid="where"/>; </select> <select id="selectAll" parameterType="int" resultMap="blogResult"> select B.id as blog_id, B.subject as blog_title, B.author as blog_author_id, P.id as post_id, P.subject as post_subject, P.content as content from Blog B left outer join Comment P on B.id = P.blogid </select> <insert id="insert" parameterType="com.beans.Blog"> insert into blog(subject,content,author) values(#{subject},#{content},#{author}) </insert> <update id="update" parameterType="com.beans.User"> update blog set subject=#{subject},content=#{content},author=#{author} where userName=#{userName} </update> <delete id="delete" parameterType="int"> delete from blog where subject=#{subject} </delete> </mapper>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值