1、 动态SQL
就是通过传入的参数不一样,可以组成不同结构的SQL语句,这种根据参数的条件修改SQL结构的SQL语句称为动态SQL语句。
动态SQL作用:
(1)根据条件组装不同结构的SQL语句,可以提高SQL代码的重用性.
(2)满足某些特定需求,如条件判断查询
2、动态SQL标签包括
<sql>标签:用于声明公有的SQL语句块,在操作标签中使用<include>调用
<if>标签:类似java的if(){},用于判断
<foreach>标签:类似java的foreach循环,一般用户批量处理的SQL语句
<trim>标签:切割标签,主要用于切割关键字的头和尾的字符
<set>标签:可以在update的时候set 关键字后面的,sql语句最后的逗号可以自动忽略
<where>:where后面的条件都不成立,忽略where关键字.
<choose> <when> <otherwise> : 类似java的swithc case选择语句
基于配置文件的mubatis动态SQL入门事例(以操作MySql数据库为例)
第一步:创建项目,导入jar包
第二步:配置xml规则文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "mybatis-3-config.dtd" > <configuration> <environments default="hzh"> <environment id="hzh"> <transactionManager type="JDBC"></transactionManager> <dataSource type="POOLED"> <!-- 配置四要素 --> <property name="driver" value="org.gjt.mm.mysql.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/hzh" /> <property name="username" value="root" /> <property name="password" value="123" /> </dataSource> </environment> </environments>
<!-- 配置指定加载的映射文件 --> <mappers> <mapper resource="cn/hzh/mapper/xml/StudentMapper.xml" /> </mappers> </configuration> |
第三步:创建一个MybatisUtils,获得Session
package cn.hzh.utils;
import java.io.IOException; import java.io.Reader; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MybatisUtils { //创建私有一个会话工厂。 public static final SqlSessionFactory SSF=createSSF();
//声明一个线程变量 private static final ThreadLocal<SqlSession> THREAD_LOCAL=new ThreadLocal<>();
//1.获得会话工厂 private static SqlSessionFactory createSSF(){
try { //读取配置文件 Reader reader = Resources.getResourceAsReader("mybatis-config.xml"); //创建会话工厂构建类对象 SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder(); //构建会话工厂 return builder.build(reader); } catch (IOException e) { e.printStackTrace(); } return null; }
//2.获得会话 public static SqlSession getSession(){ if (THREAD_LOCAL.get()==null) { SqlSession session = SSF.openSession(); //将对象放在线程变量里面 THREAD_LOCAL.set(session); } //如果已经有该会话。直接返回线程变量的会话对象。 return THREAD_LOCAL.get(); }
//使用了线程变量,在关闭会话的时候,需要清除线程变量的对象;。 public static void close(){ if (THREAD_LOCAL.get()!=null) { SqlSession session = THREAD_LOCAL.get(); session.close(); THREAD_LOCAL.remove(); } } //测试数据库是否连接成功 public static void main(String[] args) { System.out.println(MybatisUtils.getSession()); System.out.println(MybatisUtils.getSession()); } } |
第四步:创建一个操作接口和实体类
package cn.hzh.mapper;
import java.util.List; import cn.hzh.pojo.Student;
public interface StudentMapper {
//批量插入多条语句 int batchInsert(List<Student> list);
} |
package cn.hzh.pojo;
import java.io.Serializable; import java.util.Date;
public class Student implements Serializable{
private static final long serialVersionUID = 1L;
private Long studentId;//学生ID private String studentName;//学生用户名 private String studentPassword;//学生密码 private Date createDate;//创建日期
public Student(String studentName, String studentPassword, Date createDate) { super(); this.studentName = studentName; this.studentPassword = studentPassword; this.createDate = createDate; }
public Long getStudentId() { return studentId; } public void setStudentId(Long studentId) { this.studentId = studentId; } public String getStudentName() { return studentName; } public void setStudentName(String studentName) { this.studentName = studentName; } public String getStudentPassword() { return studentPassword; } public void setStudentPassword(String studentPassword) { this.studentPassword = studentPassword; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; }
} |
第五步:创建映射文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "mybatis-3-mapper.dtd" > <mapper namespace="cn.hzh.mapper.StudentMapper"> <!-- 使用foreach标签,循环拼接sql语句 --> <!-- collection:指定集合的类型,item:变量,指定循环返回的值或对象 --> <!-- separator:每次循环后面都追加一个",",但最后一次不追加 --> <insert id="batchInsert"> INSERT INTO t_student(studentName, studentPassword, createDate) VALUES <foreach collection="collection" item="item" separator=","> (#{item.studentName}, #{item.studentPassword}, #{item.createDate}) </foreach> </insert> </mapper>
|
第六步:在src下创建一个log4j.properties文件,配置日志输出格式
log4j.rootLogger=DEBUG,A1 log4j.appender.A1=org.apache.log4j.ConsoleAppender log4j.appender.A1.layout=org.apache.log4j.PatternLayout log4j.appender.A1.layout.ConversionPattern=%-4r%-5p[%t]%37c%3x-%m%n log4j.logger.org.apache.ibatis=ERROR |
第七步:编写测试类
package cn.hzh.test;
import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import cn.hzh.mapper.StudentMapper; import cn.hzh.pojo.Student; import cn.hzh.utils.MybatisUtils;
public class StudentMapperTest {
@Test public void insert(){ try { SqlSession session = MybatisUtils.getSession(); StudentMapper studentMapper = session.getMapper(StudentMapper.class);
List<Student> list = new ArrayList<>(); Student student1 =new Student("lisaa", "123123", new Date()); Student student2 =new Student("lsss", "123123", new Date()); list.add(student1); list.add(student2); int batchInsert = studentMapper.batchInsert(list); session.commit();
System.out.println(batchInsert); MybatisUtils.close(); } catch (Exception e) { e.printStackTrace(); } } } |