zoukankan      html  css  js  c++  java
  • 深入理解MyBatis的原理(一): 独立的入门demo

    前言:不结合spring,只有 mybatis+maven。数据库使用 oracle。不尝试永远不知道会发生什么事,其中遇到两个小问题,也记录下来了。转载请注明出处:https://www.cnblogs.com/yuxiaole/p/9429807.html

    一、创建用户表,用于这次的demo

    -- Create table
    create table t_user
    (
      id   number not null,
      name varchar2(1000),
      age  number
    )
    ;
    -- Add comments to the table 
    comment on table t_user
      is '用户表';
    -- Add comments to the columns 
    comment on column t_user.id
      is '主键';
    comment on column t_user.name
      is '用户名';
    comment on column t_user.age
      is '年龄';
    -- Create/Recreate primary, unique and foreign key constraints 
    alter table t_user
      add constraint t_user_id primary key (ID);

      创建完表结构,就可以新增数据了

    insert into T_USER (ID, NAME, AGE)
    values (1, 'yule', 18);
    insert into T_USER (ID, NAME, AGE)
    values (2, 'xiaohua', 24);
    insert into T_USER (ID, NAME, AGE)
    values (3, '小明', 30);
    insert into T_USER (ID, NAME, AGE)
    values (4, '小小', 24);

    二、pom.xml 中引入 MyBatis

        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis</artifactId>
          <version>3.4.5</version>
        </dependency>

    三、创建实体

    package com.yule.user.entity;
    
    /**
     * 用户实体
     * Created by yule on 2018/8/6 21:51.
     */
    public class User {
        private String id;
        private String name;
        private String age;
    
        public String getId() {
            return id;
        }
    
        public void setId(String id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getAge() {
            return age;
        }
    
        public void setAge(String age) {
            this.age = age;
        }
    }

    四、创建映射器和 sql

      dao 接口

    package com.yule.user.dao;
    
    import com.yule.user.entity.User;
    
    import java.util.List;
    
    /**
     * 用户 Dao 层
     * Created by yule on 2018/8/6 22:06.
     */
    public interface UserDao {
        List<User> queryUserList();
    }

      sql

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
            PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
            "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
    <mapper namespace="com.yule.user.dao.UserDao">
    
        <select id="queryUserList" resultType="com.yule.user.entity.User" >
            select t.id, t.name, t.age from t.user t
        </select>
    
    </mapper>

    五、配置 MyBatis

    <?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="oracle.jdbc.OracleDriver"/>
                    <property name="url" value="jdbc:oracle:thin:@localhost:1521:ORCL"/>
                    <property name="username" value="testdev"/>
                    <property name="password" value="test1234"/>
                </dataSource>
            </environment>
        </environments>
    
        <!-- 引入映射器 -->
        <mappers>
            <!--<mapper class="com.yule.user.dao.UserDao"/>-->
            <mapper resource="com/yule/user/dao/UserDao.xml"/>
        </mappers>
    
    </configuration>

    六、写个单测来看看

    package com.yule.user.dao;
    
    import com.yule.user.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 org.junit.Test;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.List;
    
    import static org.junit.Assert.*;
    
    public class UserDaoTest {
    
        private static SqlSessionFactory sqlSessionFactory;
    
        @Test
        public void test() throws IOException {
    
            SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
    
            SqlSession sqlSession = sqlSessionFactory.openSession();
    
            UserDao userDao = sqlSession.getMapper(UserDao.class);
            List<User> userList = userDao.queryUserList();
    
            for (User user : userList) {
                System.out.println(user.getName());
            }
    
            sqlSession.close();
        }
    
        private static SqlSessionFactory getSqlSessionFactory() {
            //单例
            if (sqlSessionFactory == null) {
                InputStream inputStream;
                try {
                    inputStream = Resources.getResourceAsStream("configuration.xml");
                    sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
                } catch (IOException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e.getCause());
                }
            }
            return sqlSessionFactory;
        }
    
    }

    七、运行结果

      

    八、错误1:pom 中需要加如下代码

      运行单测报错

    D:Javajdk1.8.0_144injava -ea -Didea.test.cyclic.buffer.size=1048576 "-javaagent:D:Program FilesJetBrainsIntelliJ IDEA 2017.1.5libidea_rt.jar=51056:D:Program FilesJetBrainsIntelliJ IDEA 2017.1.5in" -Dfile.encoding=UTF-8 -classpath "D:Program FilesJetBrainsIntelliJ IDEA 2017.1.5libidea_rt.jar;D:Program FilesJetBrainsIntelliJ IDEA 2017.1.5pluginsjunitlibjunit-rt.jar;D:Javajdk1.8.0_144jrelibcharsets.jar;D:Javajdk1.8.0_144jrelibdeploy.jar;D:Javajdk1.8.0_144jrelibextaccess-bridge-64.jar;D:Javajdk1.8.0_144jrelibextcldrdata.jar;D:Javajdk1.8.0_144jrelibextdnsns.jar;D:Javajdk1.8.0_144jrelibextjaccess.jar;D:Javajdk1.8.0_144jrelibextjfxrt.jar;D:Javajdk1.8.0_144jrelibextlocaledata.jar;D:Javajdk1.8.0_144jrelibext
    ashorn.jar;D:Javajdk1.8.0_144jrelibextsunec.jar;D:Javajdk1.8.0_144jrelibextsunjce_provider.jar;D:Javajdk1.8.0_144jrelibextsunmscapi.jar;D:Javajdk1.8.0_144jrelibextsunpkcs11.jar;D:Javajdk1.8.0_144jrelibextzipfs.jar;D:Javajdk1.8.0_144jrelibjavaws.jar;D:Javajdk1.8.0_144jrelibjce.jar;D:Javajdk1.8.0_144jrelibjfr.jar;D:Javajdk1.8.0_144jrelibjfxswt.jar;D:Javajdk1.8.0_144jrelibjsse.jar;D:Javajdk1.8.0_144jrelibmanagement-agent.jar;D:Javajdk1.8.0_144jrelibplugin.jar;D:Javajdk1.8.0_144jrelib
    esources.jar;D:Javajdk1.8.0_144jrelib
    t.jar;F:IDEAworkspacesdemo	arget	est-classes;F:IDEAworkspacesdemo	argetclasses;F:mavenRepositoryjunitjunit4.12junit-4.12.jar;F:mavenRepositoryorghamcresthamcrest-core1.3hamcrest-core-1.3.jar;F:mavenRepositoryorgspringframeworkspring-test4.3.14.RELEASEspring-test-4.3.14.RELEASE.jar;F:mavenRepositoryorgspringframeworkspring-context4.3.14.RELEASEspring-context-4.3.14.RELEASE.jar;F:mavenRepositoryorgspringframeworkspring-aop4.3.14.RELEASEspring-aop-4.3.14.RELEASE.jar;F:mavenRepositoryorgspringframeworkspring-expression4.3.14.RELEASEspring-expression-4.3.14.RELEASE.jar;F:mavenRepositoryorgspringframeworkspring-beans4.3.14.RELEASEspring-beans-4.3.14.RELEASE.jar;F:mavenRepositoryorgspringframeworkspring-core4.3.14.RELEASEspring-core-4.3.14.RELEASE.jar;F:mavenRepositorycommons-loggingcommons-logging1.2commons-logging-1.2.jar;F:mavenRepositoryorgspringframeworkspring-web4.3.14.RELEASEspring-web-4.3.14.RELEASE.jar;F:mavenRepositoryorgspringframeworkspring-webmvc4.3.14.RELEASEspring-webmvc-4.3.14.RELEASE.jar;F:mavenRepositoryorgspringframeworkspring-jdbc4.3.14.RELEASEspring-jdbc-4.3.14.RELEASE.jar;F:mavenRepositoryorgspringframeworkspring-tx4.3.14.RELEASEspring-tx-4.3.14.RELEASE.jar;F:mavenRepositoryjavaxservletjavax.servlet-api3.1.0javax.servlet-api-3.1.0.jar;F:mavenRepositoryjavaxservletjspjsp-api2.2jsp-api-2.2.jar;F:mavenRepositoryjavaxservletjstl1.2jstl-1.2.jar;F:mavenRepositorycommons-fileuploadcommons-fileupload1.2.1commons-fileupload-1.2.1.jar;F:mavenRepositorycommons-iocommons-io2.4commons-io-2.4.jar;F:mavenRepositoryorgslf4jslf4j-api1.7.25slf4j-api-1.7.25.jar;F:mavenRepositoryorgslf4jslf4j-log4j121.7.25slf4j-log4j12-1.7.25.jar;F:mavenRepositorylog4jlog4j1.2.17log4j-1.2.17.jar;F:mavenRepositorychqoslogbacklogback-classic1.2.3logback-classic-1.2.3.jar;F:mavenRepositorychqoslogbacklogback-core1.2.3logback-core-1.2.3.jar;F:mavenRepositoryorgmybatismybatis3.4.5mybatis-3.4.5.jar;F:mavenRepositorycomoracleojdbc611.2.0.1.0ojdbc6-11.2.0.1.0.jar" com.intellij.rt.execution.junit.JUnitStarter -ideVersion5 com.yule.user.dao.UserDaoTest,test
    SLF4J: Class path contains multiple SLF4J bindings.
    SLF4J: Found binding in [jar:file:/F:/mavenRepository/org/slf4j/slf4j-log4j12/1.7.25/slf4j-log4j12-1.7.25.jar!/org/slf4j/impl/StaticLoggerBinder.class]
    SLF4J: Found binding in [jar:file:/F:/mavenRepository/ch/qos/logback/logback-classic/1.2.3/logback-classic-1.2.3.jar!/org/slf4j/impl/StaticLoggerBinder.class]
    SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
    SLF4J: Actual binding is of type [org.slf4j.impl.Log4jLoggerFactory]
    log4j:WARN No appenders could be found for logger (org.apache.ibatis.logging.LogFactory).
    log4j:WARN Please initialize the log4j system properly.
    log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
    
    org.apache.ibatis.exceptions.PersistenceException: 
    ### Error building SqlSession.
    ### The error may exist in com/yule/user/dao/UserDao.xml
    ### Cause: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: java.io.IOException: Could not find resource com/yule/user/dao/UserDao.xml
    
        at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)
        at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:80)
        at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:64)
        at com.yule.user.dao.UserDaoTest.getSqlSessionFactory(UserDaoTest.java:42)
        at com.yule.user.dao.UserDaoTest.test(UserDaoTest.java:23)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
        at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
        at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
        at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
        at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
        at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
        at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
        at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
        at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
        at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
        at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
        at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
        at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
        at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
        at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
    Caused by: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: java.io.IOException: Could not find resource com/yule/user/dao/UserDao.xml
        at org.apache.ibatis.builder.xml.XMLConfigBuilder.parseConfiguration(XMLConfigBuilder.java:121)
        at org.apache.ibatis.builder.xml.XMLConfigBuilder.parse(XMLConfigBuilder.java:99)
        at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:78)
        ... 25 more
    Caused by: java.io.IOException: Could not find resource com/yule/user/dao/UserDao.xml
        at org.apache.ibatis.io.Resources.getResourceAsStream(Resources.java:114)
        at org.apache.ibatis.io.Resources.getResourceAsStream(Resources.java:100)
        at org.apache.ibatis.builder.xml.XMLConfigBuilder.mapperElement(XMLConfigBuilder.java:371)
        at org.apache.ibatis.builder.xml.XMLConfigBuilder.parseConfiguration(XMLConfigBuilder.java:119)
        ... 27 more
    
    
    Process finished with exit code -1

      解决方案:为了编译之后,能读取到 xml 文件,所以在 pom.xml 中 <build></build>加如下代码。

    <resources>
          <resource>
            <directory>src/main/java</directory>
            <includes>
              <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
          </resource>
        </resources>

    九、错误2:添加 pom 的 oracle 依赖

      运行单测报错:报找不到驱动;java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver

      解决方案:https://www.cnblogs.com/yuxiaole/p/9479536.html

    转载请注明出处: https://www.cnblogs.com/yuxiaole/p/9429807.html

      

  • 相关阅读:
    lambda表达式
    PAT 1071. Speech Patterns
    PAT 1070. Mooncake
    1069. The Black Hole of Numbers
    PAT 1068. Find More Coins
    背包问题(动态规划)
    PAT 1067. Sort with Swap(0,*)
    PAT 1066. Root of AVL Tree
    PAT 1065. A+B and C
    PAT 1064. Complete Binary Search Tree
  • 原文地址:https://www.cnblogs.com/yuxiaole/p/9429807.html
Copyright © 2011-2022 走看看