企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## 1.1 MyBatis简介 **有各种资源下载的网址** MyBatis官方GitHub地址为https://github.com/mybatis。 · mybatis-3(https://github.com/mybatis/mybatis-3):MyBatis 源码,也是本书中主要讲解和使用的内容。 · generator(https://github.com/mybatis/generator):代码生成器,可以生成一些常见的基本方法,提高工作效率。 · ehcache-cache(https://github.com/mybatis/ehcache-cache):默认集成Ehcache的缓存实现。 · redis-cache(https://github.com/mybatis/redis-cache):默认集成Redis的缓存实现。 · spring(https://github.com/mybatis/spring):方便和Spring集成的工具类。 · mybatis-spring-boot(https://github.com/mybatis/mybatis-spring-boot):方便和Spring Boot集成的工具类。 ## 1.2 创建Maven项目 ### 1.2索引 **1. 创建maven项目 2. 在pom.xml中添加编码方式配置信息 3. 在pom.xml中添加编译源码的jdk版本 4. 在pom.xml中添加Log4j、JUnit和MySql和mybatis的依赖jar包 5. 在项目上单击鼠标右键,在【Maven】中选择【Update Project...],下载项目需要的jar包 6. 通过http://search.maven.org/或http://mvnrepository.com/(推荐)来查找依赖jar包。** ###### 疑问: *1.关于maven更详细的使用??* ## 1.3 简单配置让MyBatis ### 1.3.2 配置MyBatis 在src/main/resources下面创建mybatis-config.xml配置文件 ``` <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <settings> <setting name="logImpl" value="LOG4J"/> </settings> <typeAliases> <!-- 配置了 tk.mybatis.simple.model包,这样配置后,在使用类的时候不需要写包名的部分--> <package name="tk.mybatis.simple.model"/> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"> <property name="" value=""/> </transactionManager> <dataSource type="UNPOOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <!--使用jdbc 8.0版本--> <property name="url" value="jdbc:mysql://localhost:3306/lian?serverTimezone=GMT"/> <property name="username" value="root"/> <property name="password" value="password"/> </dataSource> </environment> </environments> <mappers> <mapper resource="tk/mybatis/simple/mapper/CountryMapper.xml"/> </mappers> </configuration> ``` <settings>中的logImpl属性配置指定使用LOG4J输出日志。 <typeAliases> <package name="tk.mybatis.simple.model"/> </typeAliases> 这样配置后,在使用该包下的类时,只写类名就可以。 <environments>环境配置中主要配置了数据库连接,数据库的 url 为jdbc:mysql://localhost:3306/lian?serverTimezone=GMT,使用的是本机 MySQL 中的 mybatis数据库,后面的username和password分别是数据库的用户名和密码。 <mappers>中配置了一个包含完整类路径的CountryMapper.xml,这是一个MyBatis的SQL语句和映射配置文件。 ### 1.3.3 创建实体类和Mapper.xml文件 在src/main/java下创建一个基础的包tk.mybatis.simple.model包。 在model包下创建实体类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; } } ``` 在 src/main/resources 下面创建 tk/mybatis/simple/mapper 目录,再在该目录下面创建CountryMapper.xml文件。 ``` <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <!-- 通过namespace绑定mapper接口--> <mapper namespace="tk.mybatis.simple.mapper.CountryMapper"> <select id="selectAll" resultType="Country"> select id,countryname,countrycode from country </select> </mapper> ``` * mapper标签中的 namespace 属性值是mapper.xml对应的mapper.java的全限定名。 ### 1.3.4 配置Log4j以便查看MyBatis操作数据库的过程 ``` #全局配置 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.ConversionPattern=%5p [%t] - %m%n ``` * 操作数据库的sql语句在mapper.xml中 * log4j.logger.tk.mybatis.simple.mapper=TRACE,输出resource/tk.mybatis.simple.mapper包下的xml操作数据库的详细信息。 ### 1.3.5 编写测试代码让MyBatis跑起来 ``` public class CountryMapperTest {       private static SqlSessionFactory sqlSessionFactory;      @BeforeClass      public static void init(){            try {             Reader reader = Resources.getResourceAsReader("mybatis-config.xml");             sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);             reader.close();         } catch (IOException ignore) {             ignore.printStackTrace();         }      }            @Test      public void testSelectAll(){            SqlSession sqlSession = sqlSessionFactory.openSession();            try {                 List<Country> countryList = sqlSession.selectList("selectAll");                 printCountryList(countryList);            } finally {                 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());            }      } } ``` **1** 通过Resources工具类将mybatis-config.xml配置文件读入Reader。 **2** 再通过SqlSessionFactoryBuilder建造类使用Reader创建SqlSessionFactory工厂对象。在创建SqlSessionFactory对象的过程中,首先解析mybatis-config.xml配置文件,读取配置文件中的mappers配置后会读取全部的Mapper.xml进行具体方法的解析,在这些解析完成后,SqlSessionFactory就包含了所有的属性配置和执行SQL的信息。· 使用时通过SqlSessionFactory工厂对象获取一个SqlSession。 **3** 通过SqlSession的selectList方法查找到CountryMapper.xml中id="selectAll"的方法,执行SQL查询。 **4** MyBatis底层使用JDBC执行SQL,获得查询结果集ResultSet后,根据resultType的配置将结果映射为Country类型的集合,返回查询结果。 **5** 这样就得到了最后的查询结果countryList,简单将结果输出到控制台。· 最后一定不要忘记关闭 SqlSession,否则会因为连接没有关闭导致数据库连接数过多,造成系统崩溃。