• mybatis基础配置


    我这个写的比较简略,是自己短时间记录的可能只适合自己看,新手或者不懂的建议看看下面大神这篇:

    https://www.cnblogs.com/homejim/p/9613205.html

    1.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">
            <property name="" value=""/>
          </transactionManager>
          <dataSource type="UNPOOLED">
            <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="com/learn/mybatis/role.xml"/>
      </mappers>
    </configuration>

    2.映射文件Role.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.learn.mybatis.mapper.RoleMapper">
      <select id="getRole" parameterType="long" resultType="com.learn.mybatis.model.Role">
          select roleName form t_role where id=#{id} 
      </select>
    </mapper>

    3.定义一个调用接口RoleMapper.java

    public interface RoleMapper{
        public Role getRole(Long id);
    }

    4.建立SqlSessionFactory:MyBatisUtil.java

    public class MyBatisUtil {
        public static SqlSessionFactory getSqlSessionFactory() {
            // 通过配置文件获取数据库连接信息
            Reader reader = Resources.getResourceAsReader("com/learn/mybatis/mybatis_config.xml");
            // 通过配置信息构建一个SqlSessionFactory
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
            return sqlSessionFactory;
        }
    }

    5.实现按id查找姓名功能:test.java

    public class test {
        public static void main(String[] args) {
            // 通过sqlSessionFactory打开一个数据库会话
            SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory.openSession();
            RoleMapper roleMapper = sqlSession.getMapper(RoleMapper.class);
            Role role = roleMapper.getRole(1L);
          System.out.println(
    "role_name->" + role.getRoleName()); sqlSession.close(); } }

    这样便完成了mybatis一个完整流程操作。

    每天进步一点,积少以成多。

  • 相关阅读:
    GitHub入门教程
    转:使用ActiveX插件时object显示问题,div被object标签遮挡的解决方案
    windows集成资料
    转:获取windows凭证管理器明文密码
    转: OVER() 系列函数介绍
    SQL Prompt 快捷键
    转:敏捷开发之Scrum扫盲篇
    转:修改IIS虚拟目录名称bat脚本
    转:EditPuls 5.0 注册码
    转:RowVersion 用法
  • 原文地址:https://www.cnblogs.com/chao-zjj/p/9674435.html
Copyright © 2020-2023  润新知