java web 42 : MyBatis框架 ( 增删查改、占位符、动态标签 )
增删改查、占位符
package com.tedu; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; 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.Before; import org.junit.Test; import com.tedu.pojo.Emp; public class TestMybatis02 { SqlSession session = null; /*被@Before标记的方法,在每一个@Test方法执行之前都会执行*/ @Before public void testBefore() throws IOException { //1.读取mybatis的核心配置文件(mybatis-config.xml) 源码根目录的xml文件编译后会输出到classes目录下 InputStream in = Resources.getResourceAsStream("mybatis-config.xml"); //2.基于上面读取的配置信息获取一个SqlSessionFactory对象 SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); SqlSessionFactory factory = builder.build(in); //3.基于SqlSessionFactory对象获取一个SqlSession对象 session = factory.openSession(true); //true:设置自动提交事务,每次执行一条sql之后都会自动提交 } /*练习2:新增员工信息:赵云 保安 6000*/ @Test public void testInsert02() { //通过session执行SQL语句,返回执行结果 int rows = session.insert("EmpMapper.insert02"); //mybatis将自动提交事务关闭了,需要手动提交 //session.commit();设置手动提交事务,可以实现将多个sql语句绑定为一个事务 System.out.println("影响行数:"+rows); } /*练习3:修改员工信息:赵云 保镖 20000*/ @Test public void testUpdate03() { int row = session.update("EmpMapper.update03"); System.out.println(row+"row(s) affected"); } /*练习4:删除name为'赵云'的记录*/ public void testDelete04(){ } /*练习5:查询emp表中指定id的员工信息*/ @Test public void testFindById05() { Emp emp = session.selectOne("EmpMapper.findById05",8); System.out.println(emp); } /*练习6:新增员工信息:张飞Java开发工程师15000*/ @Test public void testInsert06() { //将SQL语句中的参数封装到集合中,再作为整体参数 Map map = new HashMap(); map.put("name", "张飞"); map.put("job","JAVA开发工程师"); map.put("salary",15000); int row = session.insert("EmpMapper.insert06",map); System.out.println(row+"row(s) affected"); } /*练习7:*/ @Test public void testUpdate07() { Emp emp = new Emp(); emp.setName("张飞"); emp.setJob("架构师"); emp.setSalary(25000.0); int row = session.update("EmpMapper.update07",emp); System.out.println(row+"row(s) affected"); } /*练习8:*/ @Test public void testDelete08() { int id = 11; int row = session.delete("EmpMapper.delete08",id); System.out.println(row+"row(s) affected"); } /*练习9:*/ @Test public void testFindAll09() { Map map = new HashMap(); map.put("cols", "name,job"); List<Emp> list = session .selectList("EmpMapper.findAll09",map); for (Emp emp:list) { System.out.println(emp); } } /* 练习10:模糊查询*/ @Test public void testFindByName10() { Emp emp = new Emp(); emp.setName("刘"); List<Emp> list = session.selectList("EmpMapper.findByName10",emp); for(Emp emp2: list) { System.out.println(emp2); } } }
动态标签
package com.tedu; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; 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.Before; import org.junit.Test; import com.tedu.pojo.Emp; public class TestMybatis03 { SqlSession session = null; /*被@Before标记的方法,在每一个@Test方法执行之前都会执行*/ @Before public void testBefore() throws IOException { //1.读取mybatis的核心配置文件(mybatis-config.xml) 源码根目录的xml文件编译后会输出到classes目录下 InputStream in = Resources.getResourceAsStream("mybatis-config.xml"); //2.基于上面读取的配置信息获取一个SqlSessionFactory对象 SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); SqlSessionFactory factory = builder.build(in); //3.基于SqlSessionFactory对象获取一个SqlSession对象 session = factory.openSession(true); //true:设置自动提交事务,每次执行一条sql之后都会自动提交 } /*动态SQL标签if*/ /* 练习12:根据薪资查询员工信息*/ @Test public void testFindBySal12() { Map map = new HashMap(); map.put("minSal", 3500); map.put("maxSal", 5000); List<Emp> list = session.selectList("EmpMapper.findBySal12",map); for(Emp emp2: list) { System.out.println(emp2); } } /*练习13:*//*动态SQL标签where*/ @Test public void testFindBySal13() { Map map = new HashMap(); map.put("minSal", 3500); map.put("maxSal", 5000); List<Emp> list = session.selectList("EmpMapper.findBySal13",map); for(Emp emp2: list) { System.out.println(emp2); } } /*练习14:批量删除员工*/ @Test public void testDeleteByIds14() { Integer[] ids = { 1,3,5,7}; int row = session.delete("EmpMapper.deleteByIds14",ids); } /* 练习15:为指定的员工信息增加指定的薪资*/ @Test public void testUpdateByIds15() { Integer[] ids = {2,4,6}; Double sal = 10000.0; Map<String,Object> map = new HashMap<String,Object>(); map.put("idsArray", ids); map.put("sal", sal); session.update("EmpMapper.updateByIds15", map); } }
package com.tedu.pojo; /** * 封装员工信息的实体类(POJO) */ public class Emp { /*声明4个变量,用于封装员工信息 * 尽量让Emp类中的变量名和emp表中的列名保持一致 * */ private Integer id; private String name; private String job; private Double salary; //提供对应的get和set方法 public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getJob() { return job; } public void setJob(String job) { this.job = job; } public Double getSalary() { return salary; } public void setSalary(Double salary) { this.salary = salary; } @Override public String toString() { return "Emp [id=" + id + ", name=" + name + ", job=" + job + ", salary=" + salary + "]"; } //提供toString(方便打印) }
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"> <!-- MyBatis的全局配置文件 --> <configuration> <!-- 1.配置环境,可配置多个环境(比如:develop开发、test测试) --> <environments default="develop"> <environment id="develop"> <!-- 1.1.配置事务管理方式:JDBC/MANAGED JDBC:将事务交给JDBC管理(推荐) MANAGED:自己管理事务 --> <transactionManager type="JDBC"></transactionManager> <!-- 1.2.配置数据源,即连接池 JNDI/POOLED/UNPOOLED JNDI:已过时 POOLED:使用连接池(推荐) UNPOOLED:不使用连接池 --> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/yonghedb?characterEncoding=utf-8" /> <property name="username" value="root" /> <property name="password" value="root" /> </dataSource> </environment> </environments> <!-- 2.导入Mapper配置文件,如果mapper文件有多个,可以通过多个mapper标签导入 --> <mappers> <mapper resource="EmpMapper.xml" /> </mappers> </configuration>
EmpMapper.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值应该保证唯一 在程序中通过[ namespace + id ]定位到要执行哪一条SQL语句 --> <mapper namespace="EmpMapper"> <!-- 通过select、insert、update、delete标签声明要执行的SQL --> <!-- 练习1: 查询emp表中的所有员工信息 resultType指定查询的结果将会封装到什么类型中 即使最终返回的结果是集合(List<Emp>),resultType也只需要指定集合中的泛型即可! --> <select id="findAll" resultType="com.tedu.pojo.Emp"> select * from emp </select> <!-- 练习2:新增员工信息:赵云 保安 6000 如果是查询的SQL,执行完后会返回查询的结果,需要通过resultType指定 将查询的结果封装到什么类型中; 但如果是增删改类型的SQL,执行后返回的结果是int值,所以不需要指定resultType --> <insert id="insert02"> insert into emp values(null, '赵云','保安',6000) </insert> <!-- 练习3:修改员工信息:赵云 保镖 20000 --> <update id="update03"> update emp set job='保镖',salary=20000 where name='赵云' </update> <!-- 练习5:查询emp表中指定id的员工信息 --> <select id="findById05" resultType="com.tedu.pojo.Emp"> select * from emp where id=#{id} <!-- 占位符,内部不能为空 --> </select> <!-- 练习6:新增员工信息 --> <insert id="insert06"> insert into emp value(null,#{name},#{job},#{salary}) </insert> <!-- --> <update id="update07"> update emp set job=#{job},salary=#{salary} where name='张飞' </update> <!-- --> <delete id="delete08"> delete from emp where id=#{id} </delete> <!-- 练习9:动态指定要显示的列,查询所有的员工信息,动态指定要显示的列 --> <select id="findAll09" resultType="com.tedu.pojo.Emp"> select ${cols} from emp </select> <!-- #{}占位符不仅仅是占位作用,替换占位符时会对内容进行转义(在字符串和日期类型的两边加上单引号)处理(相当于JDBC的?占位符), 此时应该使用${},${}只会拼接(可能存在注入攻击隐患),${}无论参数多少都必须封装,否则会抛出异常 --> <!-- 10 --> <select id="findByName10" resultType="com.tedu.pojo.Emp"> select * from emp where name like '%${name}%' </select> <!-- 练习12:动态SQL标签if --> <select id="findBySal12" resultType="com.tedu.pojo.Emp"> select * from emp where 1=1 <!-- 屏蔽and在其他分支的冗余 --> <if test="minSal != null"> and salary >= #{minSal} </if> <if test="maxSal != null"> and salary <= #{maxSal} </if> <!-- < 的转义为 < --> <!-- 判断结果为真,片段生效,否则不生效 --> </select> <!-- 练习13:动态SQL标签where --> <select id="findBySal13" resultType="com.tedu.pojo.Emp"> select * from emp <where> <if test="minSal != null"> and salary >= #{minSal} </if> <!-- 多余的连接词会自动去掉 --> <if test="maxSal != null"> and salary <= #{maxSal} </if> <!-- < 的转义为 < --> <!-- 判断结果为真,片段生效,否则不生效 --> <!-- 所有if条件都不生效时,where不生效 --> </where> </select> <!-- 练习14:foreach标签 --> <delete id="deleteByIds14" > delete from emp where id in <foreach collection="array" item="id" open="(" separator="," close=")"> <!-- array/list/或把array、list存入map时,collection=指定的key --> #{id} </foreach> </delete> <!-- 练习15: --> <update id="updateByIds15"> update emp set salary=salary+ #{sal} where id in <foreach collection="idsArray" item="id" open="(" separator="," close=")"> #{id} </foreach> </update> </mapper>