创建maven项目(略),并引入依赖(pom.xml文件内容如下)
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>common-parent</artifactId> <groupId>com.ghq.boot</groupId> <version>1.0-SNAPSHOT</version> <relativePath>../common-parent/pom.xml</relativePath> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>common-dao</artifactId> <packaging>jar</packaging> <dependencies> <dependency> <artifactId>common-utils</artifactId> <groupId>com.ghq.boot</groupId> <version>1.0-SNAPSHOT</version> </dependency> <dependency> <artifactId>common-pojo</artifactId> <groupId>com.ghq.boot</groupId> <version>1.0-SNAPSHOT</version> </dependency> <!-- mybatis的核心jar包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.4</version> </dependency> <!-- 连接mysql数据库的包 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.41</version> </dependency> <!-- https://mvnrepository.com/artifact/c3p0/c3p0 --> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> <!-- https://mvnrepository.com/artifact/junit/junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.25</version> </dependency> <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.25</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/log4j/log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> </dependencies> <!-- 定义全局变量,指定编码格式 --> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> </resources> <plugins> <!-- 设置编译版本为1.8 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>1.8</source> <target>1.8</target> <encoding>${project.build.sourceEncoding}</encoding> </configuration> </plugin> </plugins> </build> </project>
准备数据库
CREATE TABLE country( `id` INT NOT NULL AUTO_INCREMENT, `countryname` VARCHAR(255) NULL, `countrycode` VARCHAR(255) NULL, PRIMARY KEY(`id`) ) DEFAULT CHARSET=utf8; INSERT country(`countryname`,`countrycode`) VALUES('中国','CN'); INSERT country(`countryname`,`countrycode`) VALUES('美国','US'); INSERT country(`countryname`,`countrycode`) VALUES('俄罗斯','RU'); INSERT country(`countryname`,`countrycode`) VALUES('英国','GB'); INSERT country(`countryname`,`countrycode`) VALUES('法国','FR');
配置mybatis,这里采用xml的配置方式
首先在src/main/resources下创建mybatis-config.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> <settings> <!-- ctrl+shift+u 大小写转换 该属性配置执行LOG4J日志输出 --> <setting name="logImpl" value="LOG4J"/> </settings> <typeAliases> <!-- 配置了一个包的全名 com.ghq.mapper 使用该包下的类的时候,不需要写包的全限定名,只需要写类名即可 譬如说:全限定名tk.mybatis.simple.model.UserMapper,那么只写UserMapper即可 --> <package name="tk.mybatis.simple.model"/> </typeAliases> <environments default="development"> <environment id="development"> <!-- 配置事务管理器 --> <transactionManager type="JDBC"> <property name="" value=""/> </transactionManager> <!-- 配置数据库的连接池 --> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://47.104.136.162:3306/mydb? useUnicode=true&characterEncoding=UTF8"/> <property name="username" value="root"/> <property name="password" value="MyNewPass4!"/> </dataSource> </environment> </environments> <!-- 指定要读取的mapper.xml配置文件 --> <mappers> <mapper resource="tk/mybatis/simple/mapper/CountryMapper.xml"/> </mappers> </configuration>
创建实体类和mapper.xml配置文件
实体类是和数据库表有映射关系(略)
package tk.mybatis.simple.model; import java.io.Serializable; /** * * @author snow */ public class Country implements Serializable{ 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; } }
在src/main/resources下创建tk/mybatis/simple/mapper的目录,再在该目录下创建CountryMapper.xml配置文件,内容如下:
<?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对应一个dao namespace相当于xml的命名空间 该namespace必须和接口的全限定类名相同 --> <mapper namespace="tk.mybatis.simple.mapper.CountryMapper"> <!-- 定义一个select查询 id:定义当前select的唯一标识 resultType:这里指定返回值的类型, 虽然该处返回的集合,但是返回值类型写集合中存储元素的类型 --> <select id="selectAll" resultType="Country"> /*这里面写查询的sql语句*/ SELECT id, countryname, countrycode from country </select> </mapper>
配置log4j,查看mybatis执行sql的过程
在src/main/resources下创建log4j.properties配置文件,内容如下:
#全局配置 log4j.rootLogger = ERROR,stdout #mybatis日志配置 # tk.mybatis.simple.mapper 对应的是java中的包:tk.mybatis.simple.mapper # 但是在java包下并没有这个包 # 在mybatis日志实现中,所谓的包名实际是mapper.xml中namespace的一部分 # 而namespace必须和接口的全限定类名一致,因此才会对应到java中的包 # 当使用纯注解方式时,使用的就是纯碎的包名 # mybatis日志输出的最低级别为trace,这个级别下会输出sql执行的详细信息 # 特别适合在开发中使用 log4j.logger.tk.mybatis.simple.mapper=TRACE ### 输出信息到控制抬 ### log4j.appender.stdout = org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target = System.out log4j.appender.stdout.layout = org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n
编写测试代码
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.Before; import org.junit.BeforeClass; import org.junit.Test; import tk.mybatis.simple.model.Country; import java.io.IOException; import java.io.InputStream; import java.util.List; public class CountryMapperTest { private static SqlSessionFactory sqlSessionFactory; @BeforeClass public static void init(){ try { //使用输入流将配置文件读入程序中 InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml"); // 创建sqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //释放资源 inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } @Test public void testSelect(){ //创建session SqlSession sqlSession = sqlSessionFactory.openSession(); try { List<Country> countryList = sqlSession.selectList("selectAll"); printCountryList(countryList); }finally { //千万不要忘记关闭sqlSession sqlSession.close(); } } /** * 打印集合 */ private static void printCountryList(List<Country> countrylist){ countrylist.forEach((country)->{ System.out.printf("%-4d%4s%4s\n", country.getId(),country.getCountryname(),country.getCountrycode()); }); } }
整个代码的执行过程
- 通过Resources工具类将mabatis-config.xml配置文件读入inputstream
- 通过SqlSessionFactoryBuilder使用Buider创建SqlSessionFactory,在该过程重,首先解析mybatis-config.xml文件,读取配置文件中的mappers配置后会读取全部的mapper.xml进行具体方法的解析,在这些解析完成后,SqlSessionFactory就包含了所有的属性配置和执行的SQL的信息
- 使用SqlSessionFactory工厂对象获取一个SqlSession
- 通过SqlSession的selectList方法查找到CountryMapper.xml中id=“selectAll”的方法,执行SQL查询
- MyBatis底层使用了JDBC执行SQL,获得查询结果集ResultSet后,根据resultType的配置将结果映射为Country类型的集合,返回查询结果
- 这样就得到了最后的查询的List集合对象
- 最后一定不要忘记关闭SqlSession,否则会因为连接没有关闭导致数据库连接数过多,造成系统崩溃。
输出结果如下:
[DEBUG] 2018-04-24 15:56:34,020 method:org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:159) ==> Preparing: /*这里面写查询的sql语句*/ SELECT id, countryname, countrycode from country [DEBUG] 2018-04-24 15:56:34,083 method:org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:159) ==> Parameters: [TRACE] 2018-04-24 15:56:34,130 method:org.apache.ibatis.logging.jdbc.BaseJdbcLogger.trace(BaseJdbcLogger.java:165) <== Columns: id, countryname, countrycode [TRACE] 2018-04-24 15:56:34,130 method:org.apache.ibatis.logging.jdbc.BaseJdbcLogger.trace(BaseJdbcLogger.java:165) <== Row: 1, 中国, CN [TRACE] 2018-04-24 15:56:34,130 method:org.apache.ibatis.logging.jdbc.BaseJdbcLogger.trace(BaseJdbcLogger.java:165) <== Row: 2, 美国, US [TRACE] 2018-04-24 15:56:34,130 method:org.apache.ibatis.logging.jdbc.BaseJdbcLogger.trace(BaseJdbcLogger.java:165) <== Row: 3, 俄罗斯, RU [TRACE] 2018-04-24 15:56:34,130 method:org.apache.ibatis.logging.jdbc.BaseJdbcLogger.trace(BaseJdbcLogger.java:165) <== Row: 4, 英国, GB [TRACE] 2018-04-24 15:56:34,130 method:org.apache.ibatis.logging.jdbc.BaseJdbcLogger.trace(BaseJdbcLogger.java:165) <== Row: 5, 法国, FR [DEBUG] 2018-04-24 15:56:34,130 method:org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:159) <== Total: 5 1 中国 CN 2 美国 US 3 俄罗斯 RU 4 英国 GB 5 法国 FR Process finished with exit code 0
参考书籍:mybatis从入门到精通
Mybatis入门系列之(一)——入门案例
最新推荐文章于 2023-03-21 08:55:49 发布