mybatis实战:一、mybatis入门(配置、一些问题的解决)
mybatis实战:一、mybatis入门(配置、一些问题的解决)
出自《MyBatis从入门到精通》刘增辉,精简
1.pom.xml
1.设置源码编码方式为 UTF -8 2.设置编译源代码的 JDK 版本 3.添加mybatis依赖 4.还需要添加会用到的 Log4j JUnit ySql 驱动的依赖。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns=".0.0"xmlns:xsi=""xsi:schemaLocation=".0.0 .0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>org.example</groupId><artifactId>One_MyBatisPrimary</artifactId><version>1.0-SNAPSHOT</version><!-- 1.设置源码编码方式为 UTF -8 ,配置如下--><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><!--2.设置编译源代码的 JDK 版本--><build><plugins><plugin><artifactId>maven-compiler-plugin</artifactId><configuration><source>1.8</source><target>1.8</target></configuration></plugin></plugins></build><dependencies><!-- 3.添加mybatis依赖--><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.3.0</version></dependency><!-- 4.还需要添加会用到的 Log4j JUnit ySql 驱动的依赖。--><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.3.0</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.38</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId><version>1.7.12</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId><version>1.7.12</version></dependency><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version></dependency><!-- !一其他依赖一--></dependencies></project>
2.创建表
插入数据
INSERT INTO country(countryname,countrycode) VALUES ('中国','CN'),('美国','us'),('俄罗斯','RU'),('英国','GB'),('法国', 'FR');
3.创建Country类
package tk.mybatis.simple.model;
public class Country {private Long id;private String countryname;private String countrycode;public Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getCountryname() {return countryname;}public void setCountryname(String countryname) {this.countryname = countryname;}public String getCountrycode() {return countrycode;}public void setCountrycode(String countrycode) {this.countrycode = countrycode;}
}
4.配置mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN"".dtd">
<configuration>
<!-- logimp 属性配置指定使用 LOG4J 输出日志--><settings><setting name="logImpl" value="LOG4J"/></settings>
<!-- 配置了一个包的别名,通常确定一个类的时候需要使用类的时候全限定名称,
例如 tk.mybatis.simple.model.Country 。
在 MyBatis 需要频繁用到类的全限定名称,为了方便使用,
我们配置了 tk.mybatis.simple.model包,-->
<!-- 这样配置后,在使用类的时候不需要写包名的部分,只使用 Country 即可。--><typeAliases><package name="tk.mybatis.simple.model"/></typeAliases><!--环境 配置中 主要 配置了数据库连接,数据库的 urljdbc:mysql://localhost:3306/mybatis ,使用的是本机 MySQL 中的 mybatis数据库,后面的 username password 分别是数据库的用户名和密码(如果你的数据库用户名及密码和这里的不 样,请修改为自己数据库可用的用户名和密码〉--><environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="UNPOOLED"><property name="driver" value="com.mysql.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/mybatis_study"/><property name="username" value="root"/><property name="password" value="password"/></dataSource></environment></environments>
<!-- 配置了一个包含完整类路径的 CountryMapper.xml,这是MyBatisSQL 语句和映射配置文件--><mappers><mapper resource="mapper/CountryMapper.xml"/></mappers>
</configuration>
我的存放路径:
5.log4j.properties
#全局面配置
log4j.rootLogger=ERROR, stdout
#MyBatis 日志配置
log4j.logger.tk.mybatis.simple.mapper=TRACE
#控制台输出配置
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversonPattern = %5p [%t] - %m%n#用过 Log4j 日志组件的人可能都会知道,配直中的 log4j.logger.tk.mybatis.simple.mapper 对应的是 tk mybatis simple .mapper包,
# 但是在这个例子中,Java目录下并没有这个包名,只在资源目录下有 mapper目录#MyBatis 的日志实现中,所谓的包名实际上是 XML 配直中的 namespace 属性值的一部分#由于namespace性值必须和接口全限定类名相同 ,
# 因此才会真正对应到Java 中的包 当使用纯注解方式时,使用的就是纯粹的包名#MyBatis 日志的 最低级 TRACE ,
# 在这个日志级别下,MyBatis会输出执行 SQL 过程中的详细信息,这个级别特别适合在开发时使用
6.CountryMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"".dtd">
<!--XML 的根元素 属性 ηamespace 定义了当 XML 的命名空间。-->
<mapper namespace="mapper.CountryMapper">
<!-- 我们所定义的一个 SELECT 查询。-->
<!--id 属性:定义了当前 SELECT 查询的唯一一个result Type :定义了当前查询的返回值类型 ,此处就是指 Country ,前面配
置中提到的别名主要用于这里,如果没有设置 ,此处就需要写 resultType=”tk.
mybatis simple model Countryselect id, ...: 查询 SQL 语句。--><select id="selectAll" resultType="Country">select * from country</select>
</mapper>
7.测试:CountryMapperTest
package tk.mybatis.simple.mapper;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.BeforeClass;
import org.junit.Test;
import tk.mybatis.simple.model.Country;import java.io.IOException;
import java.io.Reader;
import java.util.List;public class CountryMapperTest {private static SqlSessionFactory sqlSessionFactory;@BeforeClasspublic static void init() {try {
// 通过 Resources 工具类将 ti -config.xm 配置文件读入 ReaderReader reader = Resources.getResourceAsReader("mybatis-config.xml");
// 再通过 SqlSessionFactoryBuilder 建造类使用 Reader 创建 SqlSessionFactory工厂对象。
// 在创建 SqlSessionFactory 对象的过程中
// 首先解 mybatis-config.xml 配置文件,读取配置文件中的 mappers 配置后会读取全部的 Mapper xml 进行具体方法的解析,
// 在这些解析完成后, SqlSessionFactory 就包含了所有的属性配置和执行 SQL 的信息。sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
// 使用时通过 SqlSessionFactory 工厂对象获取 splSessionreader.close();} catch (IOException ignore) {ignore.printStackTrace();}}@Testpublic void testSelectAll() {
// 通过 SqlSession selectList 方法查 Coun Mapper nl id selectAll的方法,执行 查询SqlSession sqlSession = sqlSessionFactory.openSession();
// mybaatis底层使用 JDBC 执行 SQL ,获得查询结果集 ResultSet 后,根据 resultType的配置将结果映射为 Country 类型的集合 返回查询结果。try {List<Country> countryList = sqlSession.selectList("selectAll");
// 这样就得到了最后的查询结果 countryList ,简单将结果输出到控制台。printCountryList(countryList);} finally {//最后 定不要忘记关闭 SqlSession ,否 会因为连接没有关闭导致数据库连接数过多,造成系统崩旗。sqlSession.close();}}private void printCountryList(List<Country> countryList) {for (Country country : countryList) {System.out.printf("%-4d%4s%4s\n", country.getId(), country.getCountryname(), country.getCountrycode());}}
}
8.遇到的问题、困难
(1)jar包有,但是找不到,也不报错!
解决:
(1)这个我勾选了但还是有没有成功IDEA提示java: 程序包org.apache.ibatis.session不存在_小白学CS的博客-CSDN博客_程序包org.apache.ibatis.session不存在
(2)成功解决error:java :程序包org.apache.ibatis.io不存在org.apache.ibatis.session不存在 解决方法_北哑的博客-CSDN博客_程序包org.apache.ibatis.session不存在
(2)CountryMapper.xml路径问题
解决:复制的路径是\,改成/
9.运行结果
最新文章
- 性能测试报告(方案)模板
- 俞敏洪的一分钟励志演讲
- 汇纳科技张宏俊:加强布局AI大数据,为实体商业服务
- component动态组件
- Platform机制
- #includelt;和#include
- iis网站服务器+sql server数据库服务器安全
- 前途迷茫不知.NET与JAVA那个好
- 【职场感言】为什么会感觉到前途迷茫
- WindowsForm 入门
- schedulewithfixeddelay
- 粒子群算法(PSO)优化最小二乘支持向量机回归预测,PSO
- 【JAVA】使用intellij IDEA将项目打包为jar包
- CC++
- jmeter性能测试脚本录制不了的几种情况
- 统计学,机器学习,深度学习,数据挖掘的联系
- Qt SQL:QSqlField、QSqlRecord、QSqlIndex、QSqlError