2.MyBatis的增删查改
1.创建数据库
2.数据库连接测试
3.导入依赖:mysql、mybatis、junit
4.编写mybatis-config.xml核心配置文件
5.编写Utils工具类
6.编写实体类
7.编写Mapper
8.Mapper文件注册
9.资源过滤
10.测试
11.map传参
12.模糊查询
13.${}和#{}的区别
依赖代码
<!--导入依赖-->
<dependencies>
<!--MySql驱动架包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--MyBatis架包-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<!--单元测试架包-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
</dependency>
</dependencies>
Mybatis核心配置文件
<?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核心配置文件-->
<!-- 配置文件的根元素 -->
<configuration>
<!-- 和spring整合后 environments配置将废除 -->
<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?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
</configuration>
1.通过Mybatis的Resources工具类将MyBatis核心配置文件转为流,再通过局部对象SqlSessionFactoryBuilder使用build方法将MyBatis核心对象SqlSessionFactory得到,SqlSessionFactoryBuilder使用了mybatis-config.xml的配置参数得到了单例SqlSession后将mybatis-config.xml释放。
点击查看代码
package com.user102;
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.InputStream;
public class Utils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
String resources="mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resources);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}catch (Exception e){
System.out.println(e.getMessage());
}
}
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
点击查看代码
package com.user102.pojo;
public class Student {
private String sno;
private String sname;
private int age;
private String sex;
private String address;
public Student(String sno, String sname, int age, String sex, String address) {
this.sno = sno;
this.sname = sname;
this.age = age;
this.sex = sex;
this.address = address;
}
@Override
public String toString() {
return "Student{" +
"sno='" + sno + '\'' +
", sname='" + sname + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
", address='" + address + '\'' +
'}'+"\n";
}
public String getSno() {
return sno;
}
public void setSno(String sno) {
this.sno = sno;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
Mapper接口
public interface StudentMapper {
public int addStudent(Student student);
public int subStudent(String sno);
public int updateStudent(Student student);
public Student getStudentForSno(String sno);
}

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.user102.dao.StudentMapper">
<insert id="addStudent" parameterType="com.user102.pojo.Student">
insert into mybatis.student values('${sno}','${sname}',${age},'${sex}','${address}')
</insert>
<delete id="subStudent" parameterType="String">
delete from mybatis.student where sno='${sno}'
</delete>
<update id="updateStudent" parameterType="com.user102.pojo.Student">
update mybatis.student set sno='${sno}',sname='${sname}',age=${age},sex='${sex}',address='${address}'
where sno='${sno}'
</update>
<select id="getStudentForSno" parameterType="String" resultType="com.user102.pojo.Student">
select * from mybatis.student where sno='${sno}'
</select>
</mapper>
XML文件代码其实就是接口的实现类。
在dao层有一个接口,还有一个XML配置文件(接口的实现);将XML进行注册时,便能让SqlSession找到Mapper(SqlSession通过类名得到Mapper),XML通过指定命名空间namespace表明了实例化哪个接口
若不将XML文件进行注册,sqlSession.getMapper(XXX.class)时,便找不到Mapper。
点击查看代码
<mappers>
<mapper resource="com/user102/dao/StudentMapper.xml"></mapper>
</mappers>
不进行资源过滤,非resource文件夹的文件将不会视为资源文件
资源过滤
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
①增加



增加测试代码
public void addStudent(){
SqlSession sqlSession = Utils.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
mapper.addStudent(new Student("160121454125","愚公公",60,"男","太行山"));
sqlSession.commit();
sqlSession.close();
}
②删除



删除测试代码
public void subStudent(){
SqlSession sqlSession = Utils.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
mapper.subStudent("160121454124");
sqlSession.commit();
sqlSession.close();
}
③改



修改测试代码
public void updateStudent(){
SqlSession sqlSession = Utils.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
mapper.updateStudent(new Student("160121454125","姜太公",80,"男","湖中亭"));
sqlSession.commit();
sqlSession.close();
}
④查


查询测试代码
public void getStudentForId(){
SqlSession sqlSession = Utils.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
Student studentForSno = mapper.getStudentForSno("160121454125");
System.out.println(studentForSno);
sqlSession.commit();
sqlSession.close();
}
文件目录

11.map传参
当一个对象有很多属性时,只使用其中某几个属性,可以使用map传参,也是工作中常用的方法

删除sname为“愚公公”,address为“太行山”的所有数据
编写Mapper接口及XML文件

点击查看代码
public int deleteStudent(Map map);

点击查看代码
<delete id="deleteStudent" parameterType="map">
delete from mybatis.student where sname='${mySname}' and address='${myAddress}'
</delete>
测试


点击查看代码
SqlSession sqlSession = Utils.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
HashMap <String, Object> map = new HashMap <String, Object>();
map.put("mySname","愚公公");
map.put("myAddress","太行山");
mapper.deleteStudent(map);
sqlSession.commit();
sqlSession.close();

查询包含李的所有学生数据
编写Mapper接口及XML文件
第一种方式:

点击查看代码
public List <Student> likeThisName1(String name);

点击查看代码
<select id="likeThisName1" parameterType="String" resultType="com.user102.pojo.Student">
select * from mybatis.student where sname like '${sanme}'
</select>
测试

点击查看代码
public void likeThisName1(){
SqlSession sqlSession = Utils.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
List <Student> students = mapper.likeThisName1("%李%");
System.out.println(students);
sqlSession.close();
}
第二种方式:

点击查看代码
public List <Student> likeThisName2(String name);

点击查看代码
<select id="likeThisName2" parameterType="String" resultType="com.user102.pojo.Student">
select * from mybatis.student where sname like "%"${sname}"%"
</select>
测试:

拼接出的SQL代码出错
解决方法:将${}改为#{}:

success:

点击查看代码
public void likeThisName2(){
SqlSession sqlSession = Utils.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
List <Student> students = mapper.likeThisName2("李");
System.out.println(students);
sqlSession.close();
}
#{}和${}这两个语法是为了动态传递参数而存在的,是Mybatis实现动态SQL的基础,总体上他们的作用是一致的(为了动态传参),但是在编译过程、是否自动加单引号、安全性、使用场景等方面有很多不同,下面详细比较两者间的区别:
-
1.编译过程:
#{} 是 占位符 :动态解析 -> 预编译 -> 执行
${} 是 拼接符 :动态解析 -> 编译 -> 执行 -
2.自动加单引号:
#{} 对应的变量会自动加上单引号
${} 对应的变量不会加上单引号 -
3.安全性:
#{} 能防止sql 注入
${} 不能防止sql 注入
建议以后使用#{}进行动态传参,更加安全和高效










浙公网安备 33010602011771号