zoukankan      html  css  js  c++  java
  • Mybatis入门1

    关于Mybatis的快速入门可以分为这样几步:

    1.引入依赖或者引入jar包

    2.编写全局配置文件(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>
          <!-- 加载外部配置文件 -->
          <properties resource="jdbc.properties"></properties>
          <settings>
          <!--开启驼峰命名法-->
             <setting name="mapUnderscoreToCamelCase" value="true"/>
         </settings>
         
       <environments default="development">
         <environment id="development">
           <transactionManager type="JDBC"/>
           <dataSource type="POOLED">
             <property name="driver" value="${jdbc.driver}"/>
             <property name="url" value="${jdbc.url}"/>
             <property name="username" value="${jdbc.username}"/>
             <property name="password" value="${jdbc.password}"/>
           </dataSource>
         </environment>
       </environments>
       
       <!-- 指定mapper的配置文件 -->
       <mappers>
         <mapper resource="mapper.xml"/>
       </mappers>
     </configuration>

    属性文件:

     jdbc.driver=com.mysql.jdbc.Driver
     jdbc.url=jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true
     jdbc.username=root
     jdbc.password=123

    3.编写映射文件(mapper.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="userMapper">
       <select id="queryUserById" parameterType="java.lang.Long" resultType="cn.mybatis.pojo.User">
         select * from tb_user where id = #{id}
       </select>
     </mapper>

    4.编写测试代码

      String resource = "mybatis-config.xml";
              InputStream inputStream;
              SqlSessionFactory sqlSessionFactory;
              SqlSession sqlSession;
              
              inputStream = Resources.getResourceAsStream(resource);
              
              sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
              
             sqlSession = sqlSessionFactory.openSession();
             
             User user = sqlSession.selectOne("userMapper.queryUserById", 1L);
             
             System.out.println(user);
  • 相关阅读:
    常用正则
    存储过程里循环读取Array
    倒倒系列1
    利用HttpHandler生成静态页面
    古代人用拼音吗?
    确认Email无法复制粘贴
    C#调用OpenCV(一) 配置VS+OpenCV+Emgu cv
    ArcGIS Desktop9.3 (需要双击注册文件的破解包)在64位操作系统上的安装方法
    WebLogic console页面,localhost能登陆,IP不能登录
    javascript prototype学习(一)prototype的用处
  • 原文地址:https://www.cnblogs.com/lichangyun/p/8507686.html
Copyright © 2011-2022 走看看