(一)MyBatis快速入门
通过一个案例快速入门Mybatis框架
案例:查询user表中所有数据1) 创建user表,添加数据2) 创建模块,导入坐标3) 编写MyBatis核心配置文件-->替换连接信息,解决硬编码问题4) 编写SQL映射文件-->统一管理sql语句,解决硬编码问题5) 编码i. 定义POJO类ii. 加载核心配置文件,获取SqlSessionFactory对象iii. 获取SqlSession对象,执行SQL语句iv. 释放资源
–
1、创建user表,添加数据
DROP table IF exists tb_user;CREATE TABLE tb_user(id int primary key auto_increment,username varchar(20),password varchar(30),gender char(1),addr varchar(20)
);insert into tb_user(id, username, password, gender, addr) values
(1, 'zhangsan', '123', '男', '广州'),
(2, '李四', '234', '女', '天津'),
(3, '王五', '11', '男', '北京');
sql语句执行结果
2.创建模块,导入坐标
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"><modelVersion>4.0.0</modelVersion><groupId>com.itheima</groupId><artifactId>mybatis-demo</artifactId><version>1.0-SNAPSHOT</version><repositories><repository><id>JBoss repository</id><url>https://repository.jboss.org/nexus/content/repositories/releases/</url></repository></repositories><dependencies><!--mybatis依赖--><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.4.5</version></dependency><!--mysql驱动--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.46</version></dependency><!--单元测试--><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.13</version><scope>test</scope></dependency><!--添加slf4j日志API--><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId><version>1.7.20</version></dependency><!--添加logback-classic依赖--><dependency><groupId>ch.qos.logback</groupId><artifactId>logback-classic</artifactId><version>1.2.3</version></dependency><!--添加logback-core依赖--><dependency><groupId>ch.qos.logback</groupId><artifactId>logback-core</artifactId><version>1.2.3</version></dependency></dependencies></project>
logback文件的配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false"><!--定义日志文件的存储地址--><property name="LOG_HOME" value="/home" /><!--控制台日志, 控制台输出 --><appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"><encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"><!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度,%msg:日志消息,%n是换行符--><pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern></encoder></appender><!--文件日志 --><appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"><rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"><!--日志文件输出的文件名--><FileNamePattern>${LOG_HOME}/TestWeb.log.%d{yyyy-MM-dd}.log</FileNamePattern><!--日志文件保留天数--><MaxHistory>30</MaxHistory></rollingPolicy><encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"><!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度--><pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern></encoder><triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"><MaxFileSize>10MB</MaxFileSize></triggeringPolicy></appender><logger name="org.hibernate.type.descriptor.sql.BasicBinder" level="TRACE" /><logger name="org.hibernate.type.descriptor.sql.BasicExtractor" level="DEBUG" /><logger name="org.hibernate.SQL" level="DEBUG" /><logger name="org.hibernate.engine.QueryParameters" level="DEBUG" /><logger name="org.hibernate.engine.query.HQLQueryPlan" level="DEBUG" /><logger name="com.apache.ibatis" level="TRACE"/><logger name="java.sql.Connection" level="DEBUG"/><logger name="java.sql.Statement" level="DEBUG"/><logger name="java.sql.PreparedStatement" level="DEBUG"/><root level="DEBUG"><appender-ref ref="STDOUT" /><appender-ref ref="FILE"/></root>
</configuration>
3.编写MyBatis核心配置文件–>替换连接信息,解决硬编码问题
mybatis核心配置文件参考官网给出的示例
官网:https://mybatis.org/mybatis-3/zh/getting-started.html红色框框中的内容是需要根据自己的设置更改的
我自己的配置如下:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//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.jdbc.Driver"/><property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis?useSSL=false"/><property name="username" value="root"/><property name="password" value="111111"/></dataSource></environment></environments><mappers><mapper resource="UserMapper.xml"/></mappers>
</configuration>
4.编写SQL映射文件–>统一管理sql语句,解决硬编码问题
sql映射配置文件参考官网给出的示例
官网:https://mybatis.org/mybatis-3/zh/getting-started.html红色框框中的内容是需要根据自己的设置更改的
我的sql映射文件 UserMapper.xml配置如下
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><!--namespace:名称空间
-->
<mapper namespace="test"><select id="selectAll" resultType="com.itheima.Pojo.User">select * from tb_user;</select>
</mapper>
5. 编码
首先创建User类包含表中的所有字段
public class User {private Integer id;private String username;private String passWord;private String gender;private String addr;public User() {}public User(Integer id, String username, String passWord, String gender, String addr) {this.id = id;this.username = username;this.passWord = passWord;this.gender = gender;this.addr = addr;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassWord() {return passWord;}public void setPassWord(String passWord) {this.passWord = passWord;}public String getGender() {return gender;}public void setGender(String gender) {this.gender = gender;}public String getAddr() {return addr;}public void setAddr(String addr) {this.addr = addr;}@Overridepublic String toString() {return "User{" +"id=" + id +", username='" + username + '\'' +", passWord='" + passWord + '\'' +", gender='" + gender + '\'' +", addr='" + addr + '\'' +'}';}
}
测试类:main方法
public static void main(String[] args) throws Exception {//1.加载mybatis核心配置文件,获取SqlSessionFactoryString resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//2.获取SqlSession对象,用它来执行sqlSqlSession sqlSession = sqlSessionFactory.openSession();//3.执行sqlList<User> users = sqlSession.selectList("test.selectAll");System.out.println(users);//4.释放资源sqlSession.close();}