学习流水账:MyBatis -- helloworld,动态SQL

以前一直用的SpringJDBC,最近项目中要使用MyBatis,学习中。

之前看了一点孔浩老师的MyBatis相关视频,也没来得及练习,就开始在项目中写dao了。

但是马上就遇到一个问题:想要传入一个list作为in的条件,如果这个list为空的时候,就不要in的条件。之前用SpringJDBC,自己写代码拼sql,很容易搞定。但是MyBatis下怎么处理,并不知道。

查看了官方的文档,发现MyBatis原来有强大的动态SQL能力,我这个问题可以轻松搞定。

http://mybatis.github.io/mybatis-3/zh/dynamic-sql.html


解决问题:首先是搭建一个helloWorld工程。HelloWorld搭建好,再按照官方文档,做一点小测试就可以明白。

下面记录下步骤:

1 引入jar包。一个是mybatis的包,一个是数据库驱动。

	<dependencies>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.2.8</version>
		</dependency>
		<dependency>
			<groupId>org.oracle</groupId>
			<artifactId>ojdbc6</artifactId>
			<version>1.0</version>
		</dependency>
	</dependencies>
ojdbc没有在中央仓库找到,所以自己把它安装到了本地,写了一个bat脚本:

PATH = E:\tools\apache-maven-3.2.3\bin;%PATH%
mvn install:install-file -DgroupId=org.oracle -DartifactId=ojdbc6 -Dversion=1.0 -Dpackaging=jar -Dfile=ojdbc6.jar > log.log
pause

2 写一个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>
	<properties>
		<property name="driver" value="oracle.jdbc.OracleDriver" />
		<property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl" />
		<property name="username" value="scott" />
		<property name="password" value="testpwd" />
	</properties>
	<typeAliases>
		<typeAlias type="xue.practice.mybatis.model.Dept" alias="Dept"/>
	</typeAliases>
	<environments default="development">
		<environment id="development">
			<transactionManager type="JDBC" />
			<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>
	</environments>
	<mappers>
		<mapper resource="xue/practice/mybatis/model/DeptMapper.xml" />
	</mappers>
</configuration>


3 对照数据库里字段的名称,写一个测试用的javabean


4 写sql映射文件DeptMapper.xml。这个文件最重要,MyBatis的动态SQL就是在这里配置的

<?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">
<!-- namespace是必须指定的 -->
<mapper namespace="xue.practice.mybatis.model.DeptMapper">
<!-- MyBatis的特性之一就是动态SQL能力。 MyBatis采用基于OGNL的表达式 -->
	<select id="selectDeptIn" resultType="Dept">
		select * from dept where deptno in
		<!-- 把List作为参数对象传递给Mybatis,Mybatis会把参数包装在一个Map中,并且以list为键-->
		<foreach collection="list" item="item" index="index" open="("
			close=")" separator=",">
			#{item}
		</foreach>
	</select>
	<select id="selectDeptInOr" resultType="Dept">
		select * from dept
		<!-- 1 如果内容为空,则where不会出现。2 如果内容以or或者and开头,会去掉 -->
		<where>
			<if test="deptnos != null and deptnos.size != 0">
				deptno in
				<foreach collection="deptnos" item="item" index="index"
					open="(" close=")" separator=",">
					#{item}
				</foreach>
			</if>
			or loc = #{loc}
		</where>
	</select>
</mapper>

5 测试。我直接在Eclipse的工程中引入了JUnit4。(Maven中没有引入JUnit,也没有用Maven来运行)。

package xue.practice.mybatis;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

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 xue.practice.mybatis.model.Dept;

/**
 * Hello world!
 *
 */
public class AppTest
{
	
	@Test
	public void testIn()
		throws IOException
	{
		String resource = "xue/practice/mybatis/mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		// 创建sessionFactory
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
				.build(inputStream);
		// session不是线程安全的
		SqlSession session = sqlSessionFactory.openSession();
		try
		{
			List<Integer> deptnos = new ArrayList<Integer>();
			deptnos.add(2);
			deptnos.add(10);
			List<Dept> depts = session
					.selectList(
							"xue.practice.mybatis.model.DeptMapper.selectDeptIn",
							deptnos);
			for (Dept dept : depts)
			{
				System.out.println(dept.getDeptno() + dept.getDname());
			}
		}
		finally
		{
			session.close();
		}
	}
	
	@Test
	public void testWhere()
		throws IOException
	{
		String resource = "xue/practice/mybatis/mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
				.build(inputStream);
		SqlSession session = sqlSessionFactory.openSession();
		try
		{
			List<Integer> deptnos = new ArrayList<Integer>();
//			deptnos.add(2);
//			deptnos.add(20);
			HashMap<String, Object> params = new HashMap<String, Object>();
			params.put("deptnos", deptnos);
			params.put("loc", "BOSTON");
			List<Dept> depts = session.selectList(
					"xue.practice.mybatis.model.DeptMapper.selectDeptInOr",
					params);
			for (Dept dept : depts)
			{
				System.out.println(dept.getDeptno() + dept.getDname());
			}
		}
		finally
		{
			session.close();
		}
	}
}






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值