目录
1.链表查询
1.1多对一
(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">
<!--namespace:命名空间:它的值现在可以随便写。
以后必须和dao接口对应。
-->
<mapper namespace="com.dao.StuDao">
<resultMap id="me" type="com.entity.Student" autoMapping="true">
<id property="sid" column="sid" />
<!--
association:表示多对一
property:表示对象属性名
javaType:表示该对象所属的类型
autoMapping :必须写
-->
<association property="classS" javaType="com.entity.ClassS" autoMapping="true">
<id property="classid" column="classid" />
</association>
</resultMap>
<select id="selectByid" resultMap="me" >
select * from student s join class c on s.class_id=c.classid where s.sid=#{sid}
</select>
</mapper>
StuDao方法
测试代码:
import com.dao.StuDao;
import com.entity.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.Before;
import org.junit.Test;
import java.io.Reader;
import java.util.List;
/**
* @program: mybatis02
* @description:
* @author: 秦王
* @create: 2021-12-04 14:29
**/
public class TestDBY {
private SqlSession session;
@Before
public void before() throws Exception{
//1.首先要读取mybatis的配置文件, 连接数据库
Reader reader = Resources.getResourceAsReader("mybatis.xml");
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(reader);
//2.获取Session对象 --》Connection对象
session=build.openSession();
}
@Test
public void selectAll(){
StuDao mapper = session.getMapper(StuDao.class);
List list = mapper.selectByid(3);
System.out.println(list);
}
}
第二种方法:嵌套查询,是一种查询两次的方法。在公司内可能用的到
2.动态sql语句
2.1 if和where一起用
测试:
2.2 [choose when otherwise] 和where
测试:
2.3 使用set标签,修改部分字段
测试:
2.4.批量删除
测试: