MyBatis框架三 Li.065

注解开发MyBatis 操作 创建接口和查询方法 在核心配置文件中配置映射关系 编写测试类 package com.lizicai.mapper; import com.lizicai.bean.Student; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import java.util.List; public interface StudentMapper { // 查询 @Select( "SELECT * FROM student") public abstract List<Student> selectAll(); // 插入数据 @Insert("INSERT INTO student VALUES (#{id},#{name},#{age})") public abstract Integer insert(Student stu); // 修改数据 @Update("UPDATE student SET name=#{name},age=#{age} WHERE id=#{id}" ) public abstract Integer update(Student stu); // 删除数据 @Delete("DELETE FROM student WHERE id=#{id}") public abstract Integer delete(Integer id); } <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTA Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- 数据库账号配置--> <properties resource="jdbc.properties"></properties> <!-- 配置log4j--> <settings> <setting name="logImpl" value="log4j"/> </settings> <!-- 起别名 --> <typeAliases> <package name="com.lizicai.bean"/> </typeAliases> <!-- 集成分页助手插件 --> <plugins> <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin> </plugins> <environments default="mariadb"> <environment id="mariadb"> <!-- 事务管理, 默认采用JDBC默认的事务--> <transactionManager type="JDBC"></transactionManager> <!-- dataSource数据源信息 type属性 连接池--> <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> <environment id="mariadb2"> <transactionManager type="JDBC"></transactionManager> <dataSource type="POOLED"> <property name="driver" value="org.mariadb.jdbc.Driver"/> <property name="url" value="jdbc:mariadb://192.168.0.100:3306/db2"/> <property name="username" value="root"/> <property name="password" value="rootPassword"/> </dataSource> </environment> </environments> <mappers> <!-- 配置映射关系--> <package name="com.lizicai.mapper"/> </mappers> </configuration> package com.lizicai.test; import com.lizicai.bean.Student; import com.lizicai.mapper.StudentMapper; 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.jupiter.api.Test; import java.io.IOException; import java.io.InputStream; import java.util.List; public class Test01 { @Test public void selectAll() throws IOException { InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); SqlSession sqlSession = sqlSessionFactory.openSession(true); StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); List<Student> list = mapper.selectAll(); for(Student c : list){ System.out.println(c); } sqlSession.close(); is.close(); } @Test public void insert() throws IOException { InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); SqlSession sqlSession = sqlSessionFactory.openSession(true); StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); Student stu = new Student(9,"李大刀",20); Integer result = mapper.insert(stu); System.out.println(result); sqlSession.close(); is.close(); } @Test public void update() throws IOException { InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); SqlSession sqlSession = sqlSessionFactory.openSession(true); StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); Student stu = new Student(9,"李大刀",22); Integer result = mapper.update(stu); System.out.println(result); sqlSession.close(); is.close(); } @Test public void delete() throws IOException { InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); SqlSession sqlSession = sqlSessionFactory.openSession(true); StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); Integer result = mapper.delete(9); System.out.println(result); sqlSession.close(); is.close(); } } 一对一 环境准备 ...

November 4, 2021&nbsp;·&nbsp;7 分钟&nbsp;·&nbsp;Lizicai

MyBatis框架二 Li.064

接口代理方式实现Dao层 接口代理方式-实现规则 传统方式实现Dao 层,我们既要写接口,还要与实现类。而MyBatis框架可以帮助我们省略编写 Dao 层接口实现类的步骤 程序员只需要编写接口,由MyBatis 框架根据接口的定义来创建该接口的动态代理对象。 实现规则 映射配置文件中的名称空间必须和 Dao 层接口的全类名相同。 映射配置文件中的增删改查标签的 id 属性必须和 Dao 层接口的方法名相同。 映射配置文件中的增删改查标签的 parameterType 属性必须和 Dao 层接口方法的参数相同。 映射配置文件中的增删改查标签的 resultType 属性必须和 Dao 层接口方法的返回值相同。 获取动态代理对象 SqlSession功能类中的getMapper()方法 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTA Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!-- mapper: 核心根标签 namespace属性: 名称空间 --> <mapper namespace="com.lizicai.mapper.StudentMapper"> <!-- select: 查询功能的标签 id属性: 唯一标识 resultType属性: 指定结果映射对象类型 parameterType属性: 指定参数映射对象类型 --> <select id="selectAll" resultType="student"> SELECT * FROM student </select> <select id="selectById" resultType="student" parameterType="int"> SELECT * FROM student WHERE id = #{id} </select> <insert id="insert" parameterType="student"> INSERT INTO student VALUES (#{id},#{name},#{age}) </insert> <update id="update" parameterType="student"> UPDATE student SET name=#{name},age=#{age} WHERE id=#{id} </update> <delete id="delete" parameterType="int"> DELETE FROM student WHERE id=#{id}; </delete> </mapper package com.lizicai.service.impl; import com.lizicai.bean.Student; import com.lizicai.mapper.StudentMapper; import com.lizicai.service.StudentService; 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 java.io.IOException; import java.io.InputStream; import java.util.List; public class StudentServiceImpl implements StudentService { // 查询全部 @Override public List<Student> selectAll() { List<Student> list = null; InputStream is = null; SqlSession sqlSession = null; try{ // 1. 加载核心配置文件 is = Resources.getResourceAsStream("MyBatisConfig.xml"); // 2. 获取SqlSession工厂对象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); // 3. 通过工厂对象获取SqlSession对象 sqlSession = sqlSessionFactory.openSession(true); // 4. 获取StudentMapper接口的实现类对象 StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); // 5. 通过实现类对象调用方法, 接收结果 list = mapper.selectAll(); }catch (IOException e){ e.printStackTrace(); } finally { // 6. 释放资源 if( sqlSession != null){ sqlSession.close(); } if( is != null){ try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } // 7. 返回结果 return list; } // 根据id查询 @Override public Student selectById(Integer id) { Student stu = null; InputStream is = null; SqlSession sqlSession = null; try{ // 1. 加载核心配置文件 is = Resources.getResourceAsStream("MyBatisConfig.xml"); // 2. 获取SqlSession工厂对象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); // 3. 通过工厂对象获取SqlSession对象 sqlSession = sqlSessionFactory.openSession(true); // 4. 获取StudentMapper接口的实现类对象 StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); // 5. 通过实现类对象调用方法, 接收结果 stu = mapper.selectById(id); }catch (IOException e){ e.printStackTrace(); } finally { // 6. 释放资源 if( sqlSession != null){ sqlSession.close(); } if( is != null){ try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } // 7. 返回结果 return stu; } @Override public Integer insert(Student stu) { Integer result = null; InputStream is = null; SqlSession sqlSession = null; try{ // 1. 加载核心配置文件 is = Resources.getResourceAsStream("MyBatisConfig.xml"); // 2. 获取SqlSession工厂对象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); // 3. 通过工厂对象获取SqlSession对象 sqlSession = sqlSessionFactory.openSession(true); // 4. 获取StudentMapper接口的实现类对象 StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); // 5. 通过实现类对象调用方法, 接收结果 result = mapper.insert(stu); }catch (IOException e){ e.printStackTrace(); } finally { // 6. 释放资源 if( sqlSession != null){ sqlSession.close(); } if( is != null){ try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } // 7. 返回结果 return result; } @Override public Integer update(Student stu) { Integer result = null; InputStream is = null; SqlSession sqlSession = null; try{ // 1. 加载核心配置文件 is = Resources.getResourceAsStream("MyBatisConfig.xml"); // 2. 获取SqlSession工厂对象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); // 3. 通过工厂对象获取SqlSession对象 sqlSession = sqlSessionFactory.openSession(true); // 4. 获取StudentMapper接口的实现类对象 StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); // 5. 通过实现类对象调用方法, 接收结果 result = mapper.update(stu); }catch (IOException e){ e.printStackTrace(); } finally { // 6. 释放资源 if( sqlSession != null){ sqlSession.close(); } if( is != null){ try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } // 7. 返回结果 return result; } @Override public Integer delete(Integer id) { Integer result = null; InputStream is = null; SqlSession sqlSession = null; try{ // 1. 加载核心配置文件 is = Resources.getResourceAsStream("MyBatisConfig.xml"); // 2. 获取SqlSession工厂对象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); // 3. 通过工厂对象获取SqlSession对象 sqlSession = sqlSessionFactory.openSession(true); // 4. 获取StudentMapper接口的实现类对象 StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); // 5. 通过实现类对象调用方法, 接收结果 result = mapper.delete(id); }catch (IOException e){ e.printStackTrace(); } finally { // 6. 释放资源 if( sqlSession != null){ sqlSession.close(); } if( is != null){ try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } // 7. 返回结果 return result; } } 动态SQL 动态SQL介绍 MyBatis映射配置文件中, 前面SQL都是简单的, 有些业务逻辑复杂时, SQL是动态变化, 此时前面学习的SQL就不能满足要求了 多条件查询 SELECT * FORM student WHERE id=? AND name=? AND age=?; SELECT * FORM student WHERE id=? AND name=?; 动态SQL标签 : 条件判断标签 : 循环遍历标签 标签 : 条件标签. 如果有动态条件, 则使用访标签代替where关键字 : 条件判断标签 <if test="条件判断"> 查询条件拼接 </if> <select id="selectCondition" resultType="student" parameterType="student"> SELECT * FROM student <where> <if test="id != null"> id=#{id} </if> <if test="name != null"> AND name=#{name} </if> <if test="age != null"> AND age=#{age} </if> </where> </select> @Test public void selectCondition() throws IOException { InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); SqlSession sqlSession = sqlSessionFactory.openSession(true); StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); Student stu = new Student(); // stu.setId(2); stu.setName("李四"); stu.setAge(24); List<Student> list = mapper.selectCondition(stu); for(Student student : list){ System.out.println(student); } sqlSession.close(); is.close(); } 标签 foreach : 循环遍历标签, 适用于多个参数或者的关系 <froeach colloction="" open="" close="" item="" separator=""> 获取参数 </froeach> 属性 colloction: 参数容器,(list 集合, array 数组) open: 开始的SQL语句 close: 结束的SQL语句 item: 参数变量名 separator: 分隔符 <select id="selectByIds" resultType="student" parameterType="list"> SELECT * FROM student <where> <foreach collection="list" open="id IN (" close=")" item="id" separator=","> #{id} </foreach> </where> </select> StudentMapper ...

November 3, 2021&nbsp;·&nbsp;9 分钟&nbsp;·&nbsp;Lizicai

MyBatis框架一 Li.063

MyBatis 介绍 MyBatis 是一个优秀的基于Java 的特久层框架,它内部封装了JDBC,使开发者只需要关注SQL语句本身, 而不需要花费精力去处理加载驱动、创建连接、创建执行者等复杂的操作。 MyBatis通过xml 或注解的方式将要执行的各种Statement 配置起来,并通过Java对象和 Statement中 SQL 的动态参数进行映射生成最终要执行的SQL 语句。 最后MyBatis 框架执行完 SQL 并将结果映射为 Java 对象并返回。采用ORM 思想解决了实体和数据库映射的问题,对JDBC 进行了封装,屏蔽了 JDBC API 底层访问细节,使我们不用与JDBC API打交道,就可以 完成对数据库的持久化操作。 MyBatis 使用示例 导入mariadb-java-client-2.7.4.jar和mybatis-3.5.7.jar CREATE DATABASE db1; use db1; create table student( id int auto_increment primary key , NAME VARCHAR(20), age int ); INSERT INTO student VALUES (null,'张三',23),(null,'李四',24),(null,'王五',25); public class Student { private Integer id; private String name; private Integer age; ...略 } package com.lizicai.dao; import com.lizicai.bean.Student; 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 java.io.IOException; import java.io.InputStream; import java.util.List; public class StudentTest01 { /** * 查询全部 */ public static void main(String[] args) throws IOException { StudentTest01 s = new StudentTest01(); s.selectAll() ; } public void selectAll() throws IOException { // 1. 加载核心配置文件 InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml"); // 2.获取sqlSession工厂对象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); // 3.获取sqlSession SqlSession sqlSession = sqlSessionFactory.openSession(); // 4. 获取执行结果 List<Student> list = sqlSession.selectList("StudentMapper.selectAll"); // 5.打印结果 for(Student stu : list){ System.out.println(stu); } // 6. 关闭资源 sqlSession.close(); is.close(); } } <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTA Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <environments default="mariadb"> <environment id="mariadb"> <transactionManager type="JDBC"></transactionManager> <dataSource type="POOLED"> <property name="driver" value="org.mariadb.jdbc.Driver"/> <property name="url" value="jdbc:mariadb://192.168.0.100:3306/db1"/> <property name="username" value="root"/> <property name="password" value="rootPassword"/> </dataSource> </environment> </environments> <mappers> <mapper resource="StudentMapper.xml" /> </mappers> </configuration> MyBatis 相关API Resources: org.apache.ibatis.io.Resources 核心方法 返回值 方法名 说明 InputStream getResourceAsStream(String.fileName) 通过类加载器返回指定资源的字节输入流 SqlSessionFactoryBuilder: org.apache.ibatis.session.SqlSessionFactoryBuilder 获取SqlSessionFactory工厂对象的功能类 核心方法 返回值 方法名 说明 SqlSessionFactory build(InputStream.is) 通过指定资源字节输入流获取SqlSession工厂对象 SqlSessionFactory: org.apache.ibatis.session.SqlSessionFactory: 获取SqlSession构建者对象的工厂接口 核心方法 返回值 方法名 说明 SqlSession openSession() 获取SqlSession构建对象,并开户手动提交事务 SqlSession openSession(boolean.autoCommit) 获取SqlSession构建者对象,如果参数为true,则开户自动提交事务 SqlSession: org.apache.ibatis.session.SqlSession 构建者对象接口. 用于执行SQL, 管理事务, 接口代理. 返回值 方法名 说明 List<E> selectList(String.statement,Object.paramter) 执行查询语句,返回List集合 T selectOne(String.statement,Object.paramter) 执行查询语句,返回一个结果对象 int insert(String.statement,Object.paramter) 执行新增语句,返回影响行数 int update(String.statement,Object.paramter) 执行修改语句,返回影响行数 int delete(String.statement,Object.paramter) 执行删除语句,返回影响行数 void commit() 提交事务 void rollback() 回滚事务 T getMapper(Class<T>.cls) 获取指定接口的代理实现类对象 void close() 释放资源 public class Student { private Integer id; private String name; private Integer age; ...

October 29, 2021&nbsp;·&nbsp;7 分钟&nbsp;·&nbsp;Lizicai