mybatis动态sql

102 阅读1分钟

mapper.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.xml的父标签 namespace+id==类名+方法名 -->
	<!-- 
		如果想让接口和xml关联,必须满足如下配置:
			1.namespace的值是接口的全路径
			2.xml中标签的id必须关联dao接口中的方法名
	-->
<mapper namespace="com.zx.mybatis.mapper.StudentMapper">
	<!-- 自定义结果集映射 -->
	<resultMap id="myStudent" type="Student">
		<!-- 主键的映射关系,column:字段名,property:属性名 -->
		<id column="id" property="id"/>
		<!-- 非主键关系映射用result -->
		<result column="user_name" property="name"/>
		<result column="age" property="age"/>
		<result column="score" property="score"/>
	</resultMap>
	<!-- select标签中:parameterType可有可无,但resultType和resultMap必须有一个 -->
 	<select id="selectStuByAgeAndScore" resultMap="myStudent">
 		<!-- 需要进行判断,如果一个条件都没有,则不添加where关键字,有一个及以上条件,则添加where -->
 		<!-- 第一个条件是不需要加and的,后面每个条件前都要加and -->
		select id, user_name, age, score from student 
		<!-- 
			1.where标签中只要有内容要显示,则会为我们自动添加where关键字
			2.where标签会去掉第一个条件前的and关键字
		 -->
		<where>
			<if test="age!=null">
				and age = #{age} 
			</if>
			<!-- OGNL表达式 -->
			<if test="score!=null">
				and score = #{score}
			</if>
		</where>
	</select>
</mapper>

dao接口代码:

package com.zx.mybatis.mapper;

import java.util.List;
import java.util.Map;

import com.zx.mybatis.entity.Student;

public interface StudentMapper {
	/**
	 * 通过年龄和分数筛选学生
	 * @param age
	 * @param score
	 * @return
	 */
	public List<Student> selectStuByAgeAndScore(Map<String,Object> map);
}

java测试代码:

package com.zx.mybatis.test;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

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.Test;

import com.zx.mybatis.entity.Student;
import com.zx.mybatis.mapper.StudentMapper;
import com.zx.mybatis.util.MybatisUtil;

public class Test1 {
	@Test
	public void Test09() {
		SqlSession sqlSession = MybatisUtil.getSqlSession();
		//使用mapper动态代理技术生成对应接口的实现类
		StudentMapper sd = sqlSession.getMapper(StudentMapper.class);
		int age = 23;
		double score = 90.01;
		Map<String, Object> map = new HashMap<>();
		map.put("age", age);
		map.put("score", score);
		//多参数如何传递
		List<Student> stus = sd.selectStuByAgeAndScore(map);
		for(Student s : stus) {
			System.out.println(s);
		}
		sqlSession.close();
	}
}

java实体类代码:

package com.zx.mybatis.entity;
/**
 * 学生类
 * @author zhangyi
 *
 */
public class Student {
	private int id;
	private String name;
	private int age;
	private double score;
	
	public Student() {
		super();
	}

	public Student(int id, String name, int age, double score) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
		this.score = score;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public double getScore() {
		return score;
	}

	public void setScore(double score) {
		this.score = score;
	}

	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + ", age=" + age + ", score=" + score + "]";
	};
}

java工具类代码:

package com.zx.mybatis.util;

import java.io.IOException;
import java.io.InputStream;

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 MybatisUtil {
	
	private static String resource = "mybatis.xml";
	private static SqlSessionFactory sqlSessionFactory = null;
	/**
	 * 获取sqlSession
	 * @return
	 */
	public static SqlSession getSqlSession() {
		if(sqlSessionFactory==null) {
			try {
				InputStream inputStream = Resources.getResourceAsStream(resource);
				sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		/*
		 * 调用sqlSession工厂创建一个SqlSession
		 * 它有重载的方法,用来控制事务是否自动提交
		 * 默认是不自动进行事务提交的
		 */
		return sqlSessionFactory.openSession();
	}
}

jdbc.properties代码:

jdbc.driver=oracle.jdbc.OracleDriver
jdbc.url=jdbc:oracle:thin:@localhost:1521:orcl
jdbc.username=zhangyi
jdbc.password=123456

mybatis.xml代码:

<?xml version="1.0" encoding="UTF-8"?>
<!-- 引入约束(引入这个东西后,这个配置文件则有了一些提示标签,并且有一些语法校验) -->
<!-- 提示alt+/ -->
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<!-- configuration中的字标签是有顺序的,不能颠倒 -->
	<!-- 设置配置文件位置 -->
	<properties
		resource="com/zx/mybatis/properties/jdbc.properties"></properties>
	<settings>
		<!-- mybatis整合log4j  1.x 版本就这么写 -->
		<setting name="logImpl" value="LOG4J" />
	</settings>
	<!-- 用来配置mybatis别名 -->
	<typeAliases>
		<!-- package指定的包下所有的类都可以直接用类名表示,而不需要再写全路径 -->
		<package name="com.zx.mybatis.entity" />
		<!-- 二选一,不能同时存在 -->
		<!-- <typeAlias type="com.zx.mybatis.entity.Student" alias="stu" /> -->
	</typeAliases>
	<!-- 用来配置环境的(连接参数) -->
	<environments default="zy">
		<environment id="zy">
			<!-- 将事务交由jdbc管理 -->
			<transactionManager type="JDBC"></transactionManager>
			<dataSource type="POOLED">
				<!-- ${}语法是从.properties配置文件中获取对应值 -->
				<property name="driver" value="${jdbc.driver}" />
				<property name="url" value="${jdbc.url}" />
				<property name="username" value="${jdbc.username}" />
				<property name="password" value="${jdbc.password}" />
			</dataSource>
		</environment>
	</environments>
	<!-- 配置映射xml配置文件路径 -->
	<mappers>
		<!-- resource:用来配置相对路径xml文件 url:用来配置绝对路径xml文件 class:用来配置类路径 -->
		<!-- <mapper resource="com/zx/mybatis/mapper/StudentMapper.xml" /> -->
		<!-- package配置多个(类路径) -->
		<!-- 只能找到接口路径,但接口和xml的关系无法关联 -->
		<!-- 
			如果想使用package标签配置一个包下的所有xml文件要满足以下条件:
			1.dao接口和mapper.xml名称必须一致
			2.dao接口和mapper.xml必须放在同一路径下
		 -->
		<package name="com.zx.mybatis.mapper"/>
	</mappers>
</configuration>