Mybaties简单实例测试及注意问题

2020-06-07 16:05:14来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

Mybaties简单实例测试及注意问题

IDEA下一个简单的mybaties测试程序,适合初学者阅读。

目录结构及lib:

 

 

在src>main>java 下

根据数据库表创建实体类:com.itheima.domain.User

注意:表字段名和实体属性要对应一致

package com.itheima.domain;

import java.io.Serializable;

public class User implements Serializable {

    private Integer id;
    private String sname;
    private Integer age;
    private String sex;
    private String phone;
    private Integer javascore;
    private String birth;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public Integer getJavascore() {
        return javascore;
    }

    public void setJavascore(Integer javascore) {
        this.javascore = javascore;
    }

    public String getBirth() {
        return birth;
    }

    public void setBirth(String birth) {
        this.birth = birth;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", sname='" + sname + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                ", phone='" + phone + '\'' +
                ", javascore=" + javascore +
                ", birth='" + birth + '\'' +
                '}';
    }
}
View Code

创建dao方法:com.itheima.dao.IUserDao

package com.itheima.dao;

import com.itheima.domain.User;

import java.util.List;

public interface IUserDao {
    /*
    查询所有操作
     */
    List<User>findAll();
}
View Code

---------------------------------------------------------

然后在src>main>resources下

创建dao方法的xml文件:resources>com.itheima.dao>IUserDao.xml

注意:目录结构要与dao的接口方法目录对应

<?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">
<!-- namespace:命名空间,用于隔离sql,还有一个很重要的作用,后面会讲 -->

<mapper namespace="com.itheima.dao.IUserDao">
    <select id="findAll" resultType="com.itheima.domain.User">select * from student</select>
</mapper>
View Code

在resources文件下配置SqlMapConfig.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>
    <!-- 和spring整合后 environments配置将废除-->
    <environments default="development">
        <environment id="development">
            <!-- 使用jdbc事务管理,事务控制由mybatis-->
            <transactionManager type="JDBC"/>
            <!-- 数据库连接池,由mybatis管理-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/school"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <!-- 配置映射文件的位置 -->
    <mappers>
        <mapper resource="com/itheima/dao/IUserDao.xml"></mapper>
    </mappers>

</configuration>
View Code

导入相应的log4j.properties文件(必须)

log4j.rootLogger=WARN, stdout, R
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# Pattern to output the caller's file name and line number.
#log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
# Print the date in ISO 8601 format
log4j.appender.stdout.layout.ConversionPattern=%d [%t] %-5p %c - %m%n
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=example.log
log4j.appender.R.MaxFileSize=100KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
# Print only messages of level WARN or above in the package com.foo.
log4j.logger.com.foo=WARN
View Code

 

以上完成后进行测试,编写测试类:

在src>test下

创建测试方法类:

package com.itheima.test;



import com.itheima.dao.IUserDao;
import com.itheima.domain.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.InputStream;
import java.util.List;

public class MybatiesTest {
    public static void main(String[] args)throws  Exception {
        System.out.println("hello");
        //读取配置文件
        InputStream in= Resources.getResourceAsStream("SqlMapConfig.xml");
        //创建SqlSessionFactory工厂
        SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();
        SqlSessionFactory factory=builder.build(in);
        //
        SqlSession sqlSession = factory.openSession();
        //
        IUserDao userDao = sqlSession.getMapper(IUserDao.class);

        //
        List<User> users = userDao.findAll();
        for (User user : users) {
            System.out.println(user);

        }
        //
        sqlSession.close();
        in.close();
    }
}

运行结果:

 一个简单的mybaties测试程序完成。

-----------------------------------------------------------------------------------------------------------------------------------

遇到的错误及解决办法:

1.Cause: org.apache.ibatis.builder.BuilderException: Error creating document instance.  Cause: org.xml.sax.SAXParseException; lineNumber: 25; columnNumber: 18; 元素类型为 "mapper" 的内容必须匹配 "EMPTY"。

 

 

 原因及解决方法:

 

 将空格换行删除,然后改成这样就能运行了

 

 2.

log4j:WARN No appenders could be found for logger (org.apache.ibatis.logging.LogFactory).

log4j:WARN Please initialize the log4j system properly.

 

 

 这个是没有导入log4j.properties文件

 

 3.

 Cause: org.apache.ibatis.executor.ExecutorException: A query was run and no Result Maps were found for the Mapped Statement 'com.itheima.dao.IUserDao.findAll'.  It's likely that neither a Result Type nor a Result Map was specified.

 

 xml文件没有指定resultType

 

4.mapper的resources值地址要用“/”

 

 5.SqlMapConfig.xml和dao实现类的xml文件头

 

 


原文链接:https://www.cnblogs.com/springa/p/13061796.html
如有疑问请与原作者联系

标签:PS方法word文件数据接口

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:【Java-jxl插件】【Excel文件读写报错】jxl.read.biff.BiffExcep

下一篇:Spring11_JdbcTemplate