zoukankan      html  css  js  c++  java
  • Mybatis 入门()基本使用方法

    1.添加jar包

    【mybatis】
    mybatis-3.1.1.jar
    【MYSQL 驱动包】
    mysql-connector-java-5.1.7-bin.jar
     
    2.建库+建表
    create database mybatis;
    use mybatis;
    CREATE TABLE users(id INT PRIMARY KEY AUTO_INCREMENT, NAME
    VARCHAR(20), age INT);
    INSERT INTO users(NAME, age) VALUES('Tom', 12);
    INSERT INTO users(NAME, age) VALUES('Jack', 11);
     
    3.添加Mybatis的配置文件conf.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" />
    <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>
    </configuration>
     
    4.定义表对应的实体类
    public class User {
    private int id;
    private String name;
    private int age;
    //get,set 方法
    }
     
    5.定义操作users表的sql映射文件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.atguigu.mybatis_test.test1.userMapper">
    <select id="getUser" parameterType="int"
    resultType="com.atguigu.mybatis_test.test1.User">
    select * from users where id=#{id}
    </select>
    </mapper>
     
    6.在conf.xml文件中注册userMapper.xml文件
    <mappers>
    <mapper resource="com/atguigu/mybatis_test/test1/userMapper.xml"/>
    </mappers>
     
    7.编写测试代码:执行定义的语句
     
    public class Test {
    public static void main(String[] args) throws IOException {
    String resource = "conf.xml";
    //加载 mybatis 的配置文件(它也加载关联的映射文件)
    Reader reader = Resources.getResourceAsReader(resource);
    //构建 sqlSession 的工厂
    SqlSessionFactory sessionFactory = new
    SqlSessionFactoryBuilder().build(reader);
    //创建能执行映射文件中 sql 的 sqlSession
    SqlSession session = sessionFactory.openSession();
    //映射 sql 的标识字符串
    String statement = "com.atguigu.mybatis.bean.userMapper"+".selectUser";
    //执行查询返回一个唯一 user 对象的 sql
    User user = session.selectOne(statement, 1);
    System.out.println(user);
    }
    }
     
  • 相关阅读:
    Android SwitchButton(滑动开关)
    创建您自己的Maven模板
    Bag标签成一条线的代码来实现中国字
    rabbitmq的java简单的实现
    【七】注入框架RoboGuice使用:(Your First Custom Binding)
    Sqlmap渗透测试是常用语句
    Android NOtification 使用(震动 闪屏 铃声)
    Android loader 详解
    Android实现获取本机中所有图片
    Android保存图片到系统图库
  • 原文地址:https://www.cnblogs.com/sh-0131/p/11439251.html
Copyright © 2011-2022 走看看