MyBatis的学习
一.提供的注解
- 1参数绑定
public interface StudentMapper {
/**
* 按照地址和名字查找学生
* @param name
* @param address
* @return
*/
//Parm:Mybatis提供的注解 参数绑定作用:将指定的参数绑定到注解中,起一个名字
//参数绑定的使用
Student selectStudentByNameAddress(@Param("name") String name,@Param("addr") String address);
}
映射文件:
<?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.qf.mapper.StudentMapper">
<!-- 查询所有学生的方法-->
<select id="findAll" resultType="Student">
select * from student;
</select>
<!-- 根据姓名和地址-->
<select id="selectStudentByNameAddress" resultType="Student">
select * from student where name = #{name} and address = #{addr};
<!-- 原来实体类的属性是address,参数绑定的addr,可以直接使用-->
</select>
</mapper>
核心配置文件:
<?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 resource="jdbc.properties"/>
<!-- 实体类的别名包扫描-->
<typeAliases>
<package name="com.qf.pojo"/>
</typeAliases>
<!--环境配置-->
<!--环境配置-->
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"/>
<!--启用mybatis自带的连接池-->
<dataSource type="org.apache.ibatis.datasource.pooled.PooledDataSourceFactory">
<!--不启用mybatis连接池-->
<!-- <dataSource type="org.apache.ibatis.datasource.unpooled.UnpooledDataSourceFactory">-->
<property name="driverClass" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.qf.mapper"/>
</mappers>
</configuration>
测试类:
package com.qf.test;
import com.qf.mapper.StudentMapper;
import com.qf.pojo.Student;
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.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/**
* @author : Jack Chao
* @date : 12:43 2022/3/17
*/
public class StudentTest {
private SqlSession sqlSession ;
private InputStream inputStream ;
private StudentMapper Studentmapper ;
/**
* 初始化
* @throws Exception
*/
@Before
public void init() throws Exception{
inputStream = Resources.getResourceAsStream("mybatis-config.xml");
//创建SqlSessionFactoryBuilder
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = builder.build(inputStream);
//创建sqlSession
sqlSession = sqlSessionFactory.openSession();//手动提交
//获取mapper接口代理对象
Studentmapper = sqlSession.getMapper(StudentMapper.class);
}
/**
* 寻找所有学生
*/
@Test
public void findAllStu(){
List<Student> list = Studentmapper.findAll();
for (Student s:list){
System.out.println(s);
}
}
/**
* 根据姓名住址查学生
*/
@Test
public void findStuByNameAdd(){
Student student = Studentmapper.selectStudentByNameAddress("张三", "诺克萨斯");
if (student != null){
System.out.println(student);
}else{
System.out.println("你要找的学生不存在!!");
}
}
/**
* 关闭
* @throws IOException
*/
@After
public void close() throws IOException {
inputStream.close();
sqlSession.commit();
sqlSession.close();
}
}
执行结果:
1.2 参数作为复杂类型(Map)
StudentMapper:
package com.qf.mapper;
import com.qf.pojo.Student;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
public interface StudentMapper {
/**
* 通过姓名和用户名查找学生
* @param values
* @return
*/
Student findStudentByNameId(Map values);
}
映射文件:
<?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.qf.mapper.StudentMapper">
<!-- 通过姓名和id查询学生 -->
<select id="findStudentByNameId" resultType="Student">
select * from student where id = #{id} and name = #{name} ;
</select>
</mapper>
测试类:
package com.qf.test;
import com.qf.mapper.StudentMapper;
import com.qf.pojo.Student;
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.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author : Jack Chao
* @date : 12:43 2022/3/17
*/
public class StudentTest {
private SqlSession sqlSession ;
private InputStream inputStream ;
private StudentMapper Studentmapper ;
/**
* 初始化
* @throws Exception
*/
@Before
public void init() throws Exception{
inputStream = Resources.getResourceAsStream("mybatis-config.xml");
//创建SqlSessionFactoryBuilder
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = builder.build(inputStream);
//创建sqlSession
sqlSession = sqlSessionFactory.openSession();//手动提交
//获取mapper接口代理对象
Studentmapper = sqlSession.getMapper(StudentMapper.class);
}
/**
*通过姓名和查询学生
*/
@Test
public void findStudentByNameId(){
Map map = new HashMap();
map.put("id","4");
map.put("name","拉克丝");
Student student = Studentmapper.findStudentByNameId(map);
if (student != null){
System.out.println(student);
}else{
System.out.println("没有找到该学生!");
}
}
/**
* 关闭
* @throws IOException
*/
@After
public void close() throws IOException {
inputStream.close();
sqlSession.commit();
sqlSession.close();
}
}
结果:
二.MyBatis中的连接池
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"/>
<!--启用mybatis自带的连接池-->
<!-- <dataSource type="org.apache.ibatis.datasource.pooled.PooledDataSourceFactory">-->
<!--不启用mybatis连接池-->
<!-- <dataSource type="org.apache.ibatis.datasource.unpooled.UnpooledDataSourceFactory">-->
<!--使用自己的连接池:自定义一个工厂类 继承了 mybatis里面的PooledDataSourceFactory-->
<dataSource type="com.qf.datasource.MyDruidDataSourceFactory">
<property name="driverClass" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<!--最大激活数量-->
<property name="maxActive" value="${jdbc.maxActive}"/>
</dataSource>
</environment>
</environments>
启用连接池:
不启用连接池:
结果:
查询完毕之后,关闭连接
启用德鲁伊连接池
public class MyDruidDataSourceFactory extends PooledDataSourceFactory {
//构造方法
public MyDruidDataSourceFactory(){
//自己创建连接池
System.out.println("德鲁伊连接池舒适化了!");
this.dataSource = new DruidDataSource() ;
}
}
核心配置文件:
<?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 resource="jdbc.properties"/>
<typeAliases>
<!--实体类的别名包扫描,别名就是默认当前类名,不区分大小写-->
<package name="com.qf.pojo"/>
</typeAliases>
<!--环境配置-->
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"/>
<!--启用mybatis自带的连接池-->
<!-- <dataSource type="org.apache.ibatis.datasource.pooled.PooledDataSourceFactory">-->
<!--不启用mybatis连接池-->
<!-- <dataSource type="org.apache.ibatis.datasource.unpooled.UnpooledDataSourceFactory">-->
<!--使用自己的连接池:自定义一个工厂类 继承了 mybatis里面的PooledDataSourceFactory-->
<dataSource type="com.qf.datasource.MyDruidDataSourceFactory">
<property name="driverClass" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<!--最大激活数量-->
<property name="maxActive" value="${jdbc.maxActive}"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.qf.mapper"/>
</mappers>
</configuration>
三:通过字段别名来解决字段名与属性名的映射
3.1当字段名与属性名不一致:数据库中的字段名称不是不可以改变的,可以使用别名来修改:
<?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.qf.mapper.StudentMapper">
<!-- 查询所有学生的方法-->
<select id="findAll" resultType="Student">
select id id, name name, age age, sex sex, address from student;
</select>
</mapper>
测试类:
package com.qf.test;
import com.qf.mapper.StudentMapper;
import com.qf.pojo.Student;
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.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author : Jack Chao
* @date : 12:43 2022/3/17
*/
public class StudentTest {
private SqlSession sqlSession ;
private InputStream inputStream ;
private StudentMapper Studentmapper ;
/**
* 初始化
* @throws Exception
*/
@Before
public void init() throws Exception{
inputStream = Resources.getResourceAsStream("mybatis-config.xml");
//创建SqlSessionFactoryBuilder
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = builder.build(inputStream);
//创建sqlSession
sqlSession = sqlSessionFactory.openSession();//手动提交
//获取mapper接口代理对象
Studentmapper = sqlSession.getMapper(StudentMapper.class);
}
/**
* 寻找所有学生
*/
@Test
public void findAllStu(){
List<Student> list = Studentmapper.findAll();
for (Student s:list){
System.out.println(s);
}
}
/**
* 关闭
* @throws IOException
*/
@After
public void close() throws IOException {
inputStream.close();
sqlSession.commit();
sqlSession.close();
}
}
结果:
3.2 使用resultMap
映射文件:
<?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.qf.mapper.StudentMapper">
<!-- 查询所有学生的方法-->
<select id="findAll" resultMap="StudentMap">
select id id, name name, age age, sex sex, address from student;
</select>
<resultMap id="StudentMap" type="Student">
<id property="id" column="id"></id>
<result property="name" column="name"></result>
<result property="age" column="age"></result>
<result property="sex" column="sex"></result>
<result property="address" column="address"></result>
</resultMap>
</mapper>
测试类以及结果:
四:动态sql
如果你之前用过 JSTL 或任何基于类 XML 语言的文本处理器,你对动态 SQL 元素可能会感觉似曾相识。在 MyBatis 之前的版本中,需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。
- if
- choose (when, otherwise)
- trim (where, set)
- foreach
if:根据标签中test属性所对应的表达式决定标签中的内容是否需要拼接到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">
<mapper namespace="com.qf.mapper.StudentMapper">
<select id="findStudentByNameAddress" resultType="Student">
select * from student where
<if test="name != null">
name = #{name}
</if>
<if test="address != null">
and address = #{address}
</if>
</select>
</mapper>
where:
<?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.qf.mapper.StudentMapper">
<select id="findStudentByNameAddress" resultType="Student">
select * from student
<where>
<if test="name != null">
name = #{name}
</if>
<if test="address != null">
and address = #{address}
</if>
</where>
</select>
</mapper>
结果:
五:多对一的映射以及一对多的映射