1 DAO层框架
- 框架:是一种整体的解决方案。
1.1 JDBC的步骤
1.2 Hibernate执行的步骤
1.3 MyBaits
2 Mybatis简介
- Mybatis是支持定制化SQL、存储过程以及高级映射的优秀的持久层框架。
- Mybatis避免了几乎所有的JDBC代码和手动设置参数以及获取结果集。
- Mybatis可以使用简单的XML或者注解用于配置和原始映射,将接口和Java的POJO映射成数据库中的记录。
3 为什么需要Mybatis?
- Mybatis是一个半自动的持久层框架。
- JDBC
- SQL夹在Java代码中,耦合度高导致硬编码内伤。
- 维护不易且实际开发需求中SQL是有变化的,频繁修改的情况多见。
- Hibernate和JPA
- 长难复杂的SQL,对于Hibernate而言处理并不容易。
- 内部自动生成的SQL,不容易做优化处理。
- 基于全映射的全自动框架,大量字段的POJO进行部分映射的时候比较困难,导致数据库性能下降。
- 对于开发人员而言,核心SQL还是需要自己优化的。
- SQL和Java代码分开,功能边界清晰,一个专注业务,一个专注数据。
4 下载Mybatis
5 Mybatis之HelloWorld
5.1 编写SQL脚本
DROP DATABASE mybatis; CREATE DATABASE mybatis; USE mybatis; DROP TABLE employee; CREATE TABLE employee( id INT PRIMARY KEY AUTO_INCREMENT, last_name VARCHAR(255), gender CHAR(1), email VARCHAR(255) ); INSERT INTO employee (last_name,gender,email) VALUES (‘许威威‘,‘男‘,‘1975356467@qq.com‘);
5.2 创建javabean
- Employee.java
package com.xuweiwei.mybatis.pojo; public class Employee { private Integer id; private String lastName; private String gender; private String email; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
5.3 在src下加入log4j.properties文件
og4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.err log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n ### direct messages to file mylog.log ### log4j.appender.file=org.apache.log4j.FileAppender log4j.appender.file.File=c\:mylog.log log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n ### set log levels - for more verbose logging change ‘info‘ to ‘debug‘ ### log4j.rootLogger=debug, stdout
5.4 在src下新建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> <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://localhost:3306/mybatis"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <mappers> </mappers> </configuration>
5.5 新建EmployeeMapper.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="com.xuweiwei.mybatis.pojo.Employee"> <select id="selectEmployeeById" resultType="com.xuweiwei.mybatis.pojo.Employee"> select id,last_name lastName,gender,email from employee where id = #{id} </select> </mapper>
5.6 将EmployeeMapper.xml文件加入到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> <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://localhost:3306/mybatis"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/xuweiwei/mybatis/mapper/EmployeeMapper.xml"/> </mappers> </configuration>
5.7 测试
package com.xuweiwei.mybatis.test; import com.xuweiwei.mybatis.pojo.Employee; 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.Test; import java.io.IOException; import java.io.InputStream; public class MybatisTest { @Test public void test() throws IOException { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession session = sqlSessionFactory.openSession(); try { Employee employee = (Employee) session.selectOne("com.xuweiwei.mybatis.pojo.Employee.selectEmployeeById", 1); System.out.println(employee); } finally { session.close(); } } }
6 接口编程
6.1 编写EmployeeMapper.java
package com.xuweiwei.mybatis.mapper; import com.xuweiwei.mybatis.pojo.Employee; public interface EmployeeMapper { public Employee getEmployeeById(Integer id); }
6.2 修改EmployeeMapper.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="com.xuweiwei.mybatis.mapper.EmployeeMapper"> <select id="getEmployeeById" resultType="com.xuweiwei.mybatis.pojo.Employee"> select id,last_name lastName,gender,email from employee where id = #{id} </select> </mapper>
6.3 测试
package com.xuweiwei.mybatis.test; import com.xuweiwei.mybatis.mapper.EmployeeMapper; 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.Test; import java.io.IOException; import java.io.InputStream; public class MybatisTest { @Test public void test() throws IOException { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession session = sqlSessionFactory.openSession(); try { EmployeeMapper employeeMapper = session.getMapper(EmployeeMapper.class); System.out.println(employeeMapper.getEmployeeById(1)); } finally { session.close(); } } }
7 SqlSession
- SqlSession的实例不是线程安全的,因此不能共享。
- SqlSession每次使用完之后必须正确的关闭。