IDEA下一個簡單的mybaties測試程式,適合初學者閱讀。 目錄結構及lib: 在src>main>java 下 根據資料庫表創建實體類:com.itheima.domain.User 註意:表欄位名和實體屬性要對應一致 package com.itheima.domain; import ja ...
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文件頭