【MyBatis】01.入门案例

一、引入MyBatis依赖

<dependency>
	<groupId>org.mybatis</groupId>
	<artifactId>mybatis</artifactId>
	<version>3.4.6</version>
</dependency>

二、新建实体类User

package com.mybatisdemo.demo1.entity;

import lombok.Data;

@Data
public class User {
    private String name;
    private Integer age;
}

三、编写UserMapper.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.mybatis.demo1.mapper.UserMapper" >
    <select id="findUserByName" resultType="com.mybatisdemo.demo1.entity.User" parameterType="java.lang.String">
        SELECT NAME,AGE FROM USER WHERE NAME = #{name}
    </select>
</mapper>

四、编写配置文件conf.xml

  1. 配置数据源
  2. 配置映射文件
<?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.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/springdb?useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=GMT%2B8&amp;useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <!-- 配置映射文件 -->
    <mappers>
        <mapper resource="mybatis.mapper\UserMapper.xml"/>
    </mappers>
</configuration>

五、编写测试代码

package com.mybatisdemo.demo1;

import com.mybatisdemo.demo1.entity.User;
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 java.io.IOException;
import java.io.InputStream;

public class MyBatisApp {

    public static void main(String[] args) throws IOException {

        //加载配置,创建SqlSessionFactory
        String resource = "mybatis.mapper/conf.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //查询name为小明的记录
        SqlSession sqlSession = sessionFactory.openSession();
        User user = sqlSession.selectOne("com.mybatis.demo1.mapper.UserMapper.findUserByName", "xiaoming");
        sqlSession.close();

        System.out.println(user.toString());
    }
}

六、运行测试代码

在这里插入图片描述

七、工程目录结构

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值