第一章、认识框架
1. MyBatis框架介绍
Mybatis最大的特点是把Sql语句写在XML配置文件当中。而且Mybatis执行完Sql语句之后可以以对象形式返回(POJO/POJO集合等)。
2. 从 XML 中构建 SqlSessionFactory
SqlSessionFactory 的实例可以通过 SqlSessionFactoryBuilder 获得。而 SqlSessionFactoryBuilder 则可以从 XML 配置文件或一个预先配置的 Configuration 实例来构建出 SqlSessionFactory 实例。
String resource = "org/mybatis/example/mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
3. 从 SqlSessionFactory 中获取 SqlSession
SqlSession session = sqlSessionFactory.openSession()
第二章、Mybatis框架快速入门案例
1. 添加依赖、配置编译环境
<dependencies> <!--mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.49</version> </dependency> <!--junit--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <!--mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.5</version> </dependency> <!--lombok--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.12</version> </dependency> <!--log4j--> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.2</version> <!--编译插件,配置信息--> <configuration> <source>1.8</source> <target>1.8</target> <encoding>utf-8</encoding> </configuration> </plugin> </plugins> </build>
2. 添加 db.properties、log4.j.properties、mybatis-config.xml、EmployeeMapper.xml
(1) db.properties
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf8&useSSL=false username=root password=root
(2)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> <!-- properties标签:引入外部配置文件 resource:配置properties配置文件的路径 --> <properties resource="db.properties"/> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <mappers> <!-- mapper:配置SQL语句配置文件的路径,resource配置SQL语句的文件路径和文件名 --> <mapper resource="EmployeeMapper.xml"/> </mappers> </configuration>
(3) 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"> <!-- namespace:命名空间,值可以随意写 当有多个xxxMapper时,需要确保namespace唯一性 --> <mapper namespace="com.atguigu.pojo.EmployeeMapper"> <select id="queryEmployeeById" parameterType="Integer" resultType="com.atguigu.pojo.Employee"> select * from employee where id = 1 </select> </mapper>
3. 创建pojo类
@Data public class Employee { private Integer id; private String name; private Double salary; }
4. 测试类
@Test public void testQueryEmployeeById() throws IOException { InputStream is = Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); SqlSession sqlSession = sqlSessionFactory.openSession(); Object o = sqlSession.selectOne("com.atguigu.pojo.EmployeeMapper.queryEmployeeById"); System.out.println(o); }
第三章、Mybatis框架实现数据的CURD
1. 导入依赖和maven编译环境插件
<dependencies> <!--mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.49</version> </dependency> <!--mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.3</version> </dependency> <!--lombook--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.8</version> </dependency> <!--junit--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!--log4j--> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <source>1.8</source> <target>1.8</target> <encoding>utf-8</encoding> </configuration> </plugin> </plugins> </build>
2. 添加配置文件
db.properties、EmployeeMapper.xml、log4j.properties、mybatis-config.xml
(1) db.properties
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf8&useSSL=false username=root password=root
(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="employeeMapper"> <!--1.1查询所有员工信息--> <!-- select标签:配置查询语句 resultType属性:"查询数据表后的结果集" parameterType属性:"SQL语句的参数的数据类型",8个基本数据类,及其包装类,和字符串类型,直接写类名即可 (不区分大小写) SQL语句的参数: 有2种写法 #{} ${} #{} 防止SQL的注入攻击,提供SQL的执行效率 ${} 一般不使用,${}直接做了字符串拼接 --> <select id="queryEmployee" resultType="Employee"> select * from employee </select> <!--1.2查询员工信息,根据id刷选--> <select id="queryEmployeeById" parameterType="Integer" resultType="Employee"> select * from employee where id = #{id} </select> <!--1.3查询员工,根据名字模糊查询--> <select id="queryEmployeeByLikeName" parameterType="String" resultType="Employee"> select * from employee where name like #{name} </select> <!--2.1修改员工数据--> <update id="updateEmployeeById" parameterType="Employee"> update employee set name = #{name},salary = #{salary} where id = #{id} </update> <!--3.1删除员工数据--> <update id="deleteEmployeeById" parameterType="Integer"> delete from employee where id = #{id} </update> <!-- insert:配置新增的SQL语句 insert,update,delete 执行结果都是行数,数据类型固定位int无需配置结果集 parameterType属性: SQL语句有参数的,参数存储在JavaBean对象 注意: SQL语句的参数占位符 #{},参数是引用数据类型, JavaBean对象的字段名字 --> <!--4.1 插入数据--> <insert id="insertEmployee" parameterType="Employee"> insert into Employee values(#{id},#{name},#{salary}) </insert> <!--4.2 插入数据获取自动增长的主键列--> <!-- 配置新增的SQL语句,获取新增的主键值,MySQL支持自动增长 useGeneratedKeys属性: 是否使用新增的主键,属性的默认值是false,写成true keyProperty属性: 获取新增主键的存储位置,填写"javaBean对象的字段名" --> <insert id="insertEmployeeGetAutoKey" parameterType="Employee" keyProperty="id" useGeneratedKeys="true"> insert into Employee values(#{id},#{name},#{salary}) </insert> <!--4.3 插入数据,获取不自动增长的主键列--> <!-- selectKey:配置获取新增的主键,数据库不支持自动增长的配置方式 keyProperty属性: 获取新增主键的存储位置,填写"javaBean对象的字段名" resultType属性: 配置新增主键的数据类型 order属性:顺序,获取新增主键的SQL语句的执行顺序,在insert之前还是之后 --> <insert id="insertEmployeeGetNoAutoKey" parameterType="Employee"> <selectKey keyProperty="id" resultType="Integer" order="AFTER" > select last_insert_id() </selectKey> insert into employee values(#{id},#{name},#{salary}) </insert> </mapper>
(3) 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> <!--引入外部配置文件--> <properties resource="db.properties"></properties> <!--配置包扫描--> <typeAliases> <package name="com.atguigu.pojo"/> <!--<typeAlias type="com.atguigu.pojo.Employee" alias="Employee"/>--> </typeAliases> <!-- environments:配置数据源环境 数据源环境分为:开发环境(development)、测试环境(test)、生产环境(produce) default属性:配置默认的数据源环境 --> <environments default="development"> <!-- environments:配置单个开发环境 id属性:配置开发环境 --> <environment id="development"> <!-- transactionManager:事务管理器 type属性: type="JDBC":配置含义,MyBatis框架使用的是最原始的JDBC事务管理 Connection接口的方法:setAutoCommit,commit,rollback type="MANAGERED":的含义:MyBaits框架不使用事物 将框架事务管理抛出去,交给其他框架处理,Spring框架AOP,切面编程 --> <transactionManager type="JDBC"/> <!-- dataSource:配置连接池 type="POOLED" 使用连接池 type="UNPOOLED" 不使用连接池,使用第三方连接池,druid,c3p0,dbcp --> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <mappers> <!--配置Mapper映射文件路径--> <mapper resource="EmployeeMapper.xml"/> </mappers> </configuration>
2. 创建pojo类
package com.atguigu.pojo; import lombok.Data; @Data public class Employee { private Integer id; private String name; private Double salary; }
3. 测试类
public class MainTest { private SqlSessionFactory sqlSessionFactory; @Before public void test() throws IOException { InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } //1.1查询所有员工信息 @Test public void queryEmployee(){ SqlSession sqlSession = sqlSessionFactory.openSession(); List<Employee> employeeList = sqlSession.selectList("employeeMapper.queryEmployee"); for (Employee employee : employeeList) { System.out.println("employee = " + employee); } sqlSession.close(); } //1.2查询员工信息,根据id刷选 @Test public void queryEmployeeById(){ SqlSession sqlSession = sqlSessionFactory.openSession(); Employee employee = sqlSession.selectOne("employeeMapper.queryEmployeeById", 1); System.out.println("employee = " + employee); sqlSession.close(); } //1.3查询员工,根据名字模糊查询 @Test public void queryEmployeeByLikeName(){ SqlSession sqlSession = sqlSessionFactory.openSession(); List<Employee> employeeList = sqlSession.selectList("employeeMapper.queryEmployeeByLikeName", "%o%"); for (Employee employee : employeeList) { System.out.println("employee = " + employee); } sqlSession.close(); } //2.1修改员工数据 @Test public void updateEmployeeById(){ SqlSession sqlSession = sqlSessionFactory.openSession(); Employee employee = new Employee(); employee.setId(6); employee.setName("孙尚香"); employee.setSalary(890D); sqlSession.insert("employeeMapper.updateEmployeeById",employee); sqlSession.commit(); sqlSession.close(); } //3.1删除员工数据 @Test public void deleteEmployeeById(){ SqlSession sqlSession = sqlSessionFactory.openSession(); sqlSession.delete("employeeMapper.deleteEmployeeById",11); sqlSession.commit(); sqlSession.close(); } //4.1 插入数据 @Test public void insertEmployee(){ SqlSession sqlSession = sqlSessionFactory.openSession(); Employee employee = new Employee(); employee.setName("孙权"); employee.setSalary(6879D); sqlSession.insert("employeeMapper.insertEmployee",employee); System.out.println("employee = " + employee); sqlSession.commit(); sqlSession.close(); } //4.2 插入数据获取自动增长的主键列 @Test public void insertEmployeeGetAutoKey(){ SqlSession sqlSession = sqlSessionFactory.openSession(); Employee employee = new Employee(); employee.setName("孙权"); employee.setSalary(6879D); sqlSession.insert("employeeMapper.insertEmployeeGetAutoKey",employee); System.out.println("employee = " + employee); sqlSession.commit(); sqlSession.close(); } //4.3 插入数据,获取不自动增长的主键列 @Test public void insertEmployeeGetNoAutoKey(){ SqlSession sqlSession = sqlSessionFactory.openSession(); Employee employee = new Employee(); employee.setName("孙权"); employee.setSalary(6879D); sqlSession.insert("employeeMapper.insertEmployeeGetNoAutoKey",employee); System.out.println("employee = " + employee); sqlSession.commit(); sqlSession.close(); } }
原文:
https://www.cnblogs.com/pdjdghrs/p/15509278.html