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

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

目录结构及lib:

Mybaties简单实例测试及注意问题_第1张图片Mybaties简单实例测试及注意问题_第2张图片

 

 

在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 {
    /*
    查询所有操作
     */
    ListfindAll();
}
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">


<mapper namespace="com.itheima.dao.IUserDao">
    <select id="findAll" resultType="com.itheima.domain.User">select * from studentselect>
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>
    
    <environments default="development">
        <environment id="development">
            
            <transactionManager type="JDBC"/>
            
            <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 users = userDao.findAll();
        for (User user : users) {
            System.out.println(user);

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

运行结果:

Mybaties简单实例测试及注意问题_第3张图片

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

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

遇到的错误及解决办法:

1.Cause: org.apache.ibatis.builder.BuilderException: Error creating document instance.  Cause: org.xml.sax.SAXParseException; lineNumber: 25; columnNumber: 18; 元素类型为 "mapper" 的内容必须匹配 "EMPTY"。Mybaties简单实例测试及注意问题_第4张图片

 

Mybaties简单实例测试及注意问题_第5张图片

 

 原因及解决方法:

Mybaties简单实例测试及注意问题_第6张图片

 

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

Mybaties简单实例测试及注意问题_第7张图片

 

 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文件

Mybaties简单实例测试及注意问题_第8张图片

 

 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.

Mybaties简单实例测试及注意问题_第9张图片

 

 xml文件没有指定resultType

 

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

Mybaties简单实例测试及注意问题_第10张图片

 

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

Mybaties简单实例测试及注意问题_第11张图片

 Mybaties简单实例测试及注意问题_第12张图片

 

你可能感兴趣的:(Mybaties简单实例测试及注意问题)