mybatis详细笔记二(自用)

一.MyBatis基础知识https://www.cnblogs.com/luohuas/p/14860588.html

二.MyBatis的注解开发

注解 作用对象 对应的XML元素 描述
@Results 方法 < resultMap > 多个结果映射列表属性:value,是Result注解的数组
@Result 方法 < id > < result > 在列和属性或者字段之间的单独结果映射。属性:id,column,property,javaType,type Handler,one,many。 id是一个布尔值,表示了应该被用来比较的属性。one属性应于表示一对一的关联,和< association >相似,many属性是对集合而言的,和< collection >相似。
@One 方法 < association > 复杂类型的单独属性值映射。属性:select,已映射语句(也就是映射器的方法)的完全限定名,它可以加载合适类型的实例
@Many 方法 < collection > 复杂类型的集合属性映射。属性:select,是映射器方法的完全限定名,它可加载合适类型的一组实例
@Options 方法 映射语句的属性 这个注解提供访问交换和配置选项的宽广范围,它们通常在映射语句上作为属性出现。而不是将每条语句注解变复杂,Options 注解提供连贯清晰的方式来访问它们。属性: useCache=true,flushCache=false,resultSetType=FORWARD_ONLY,statementType=PREPARED,fetchSize= -1,timeout=-1 ,useGeneratedKeys=false ,keyProperty=”id“。理解Java 注解是很重要的,因为没有办法来指定“null ”作为值。因此,一旦你使用了 Options注解,语句就受所有默认值的支配。要注意什么样的默认值来避免不期望的行为
@select @Insert @Update @Delete 方法 < select> < insert > < delete > < select > 这些注解中的每一个代表了执行的真实 SQL。它们每一个都使用字符串数组(或单独的字符串)。如果传递的是字符串数组,它们由每个分隔它们的单独空间串联起来。属性:value,这是字符串数组用来组成单独的SQL语句
@InsertProvider @UpdateProvider @DeleteProvider @SelectProvider 方法 < insert> < update> < delete> < select>允许创建动态SQL。 这些可选的SQL注解允许你指定一个类名和一个方法在执行时来返回运行的SQL。基于执行的映射语句, MyBatis会实例化这个类,然后执行由 provider指定的方法. 这个方法可以选择性的接受参数对象作为它的唯一参数,但是必须只指定该参数或者没有参数。属性:type,method。type 属性是类的完全限定名。method 是该类中的那个方法名。

单表的增删改查

student表

id loginname username age

主要的配置文件见博客(一)

此处省略.......

一.@select @Insert @Update @Delete注解方式

1.创建学生的实体类:Student.java
public class Student {
	private Integer id;
	private String loginname;
	private String username;
	private Integer age;
	get和set
	}
2.创建StudentMapper.java

实现对数据的增删改查
在执行删除测试时,查询的测试在删除测试前面,但是删除测试的执行情况比查询测试优先级高(正常来说,测试顺序是依次执行)
image

package com.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.po.Student;

public interface StudentMapper {

	//根据id查询一个学生信息
	@Select("select * from student where id=#{id}")
	//实体类和数据库列名结果映射
	@Results({
		@Result(id=true,property="id",column="id"),
		@Result(property="loginname",column="loginname"),
		@Result(property="username",column="username"),
		@Result(property="age",column="age")
	})
	Student selectOneStuById(Integer id);

	//查询全部学生信息
	@Select("select * from student")
	List<Student>selectAllStu();

	//增加一个学生信息
	@Insert("insert into student(loginname,username,age) value(#{loginname},#{username},#{age})")
	@Options(useGeneratedKeys = true , keyProperty="id")
	int insertStudent(Student student);

	//根据id删除一个学生
	@Delete("delete from student where id=#{id}")
	int deleteStudentByid(int id);

	//改变一个学生信息
	@Update("update student set loginname=#{loginname},username=#{username},age=#{age} where id=#{id}")
	int updateStudentByid(Student student);
}
3.创建测试test.java
package com.test;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import com.mapper.StudentMapper;
import com.po.Student;
import com.utils.Utils;

public class StudentTest {
	@Test
	public void selectOneStuById() {
		SqlSession sqlSession = Utils.getSession();
		/*SqlSession中可以通过getMapper()拿到代理对象,
		SqlSession.getMapper 运用了 JDK动态代理,产生了目标Mapper接口的代理对象。*/
		StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
		//调用接口studentMapper预先写好的方法selectOneStuById(Integer id)
		Student student = studentMapper.selectOneStuById(1);
		System.out.println(student.toString());
		sqlSession.close();
	}

	@Test
	public void selectAllStu() {
		SqlSession sqlSession = Utils.getSession();
		StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
		List<Student> students = studentMapper.selectAllStu();
		System.out.println(students.toString());
		sqlSession.close();
	}

	@Test
	public void insertStudent() {
		SqlSession sqlSession = Utils.getSession();
		StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
		Student student = new Student();
		student.setLoginname("2018108037");
		student.setUsername("aiai");
		student.setAge(30);
		mapper.insertStudent(student);
		sqlSession.commit();
		System.out.println("添加成功!");
		sqlSession.close();
	}

	@Test
	public void deleteStudentByid() {
		SqlSession session = Utils.getSession();
		StudentMapper mapper = session.getMapper(StudentMapper.class);
		mapper.deleteStudentByid(11);
		session.commit();
		System.out.println("删除成功!!");
		session.close();
	}

	@Test
	public void updateStudentByid() {
		SqlSession session = Utils.getSession();
		StudentMapper mapper = session.getMapper(StudentMapper.class);
		Student student = new Student();
		student.setId(9);
		student.setLoginname("201810809");
		student.setUsername("naoke");
		student.setAge(30);
		mapper.updateStudentByid(student);
		session.commit();
		System.out.println("更新成功");
		session.close();
	}
}

二.@InsertProvider @UpdateProvider @DeleteProvider @SelectProvider动态sql注解方式

1.创建StudentMapper.java
package com.mapper;

import java.util.List;

import org.apache.ibatis.annotations.DeleteProvider;
import org.apache.ibatis.annotations.InsertProvider;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.annotations.UpdateProvider;

import com.po.Student;

public interface StudentMapper {

	//查询一个或多个学生信息
	@SelectProvider(type = StudentDynaSqlProvider.class , method = "selectOneStuBy")
	List<Student> selectOneStuById(Student student);

	//查询全部学生信息
	@SelectProvider(type = StudentDynaSqlProvider.class , method = "selectAllStu" )
	List<Student> selectAllStu();

	//增加一个学生信息
	@InsertProvider(type = StudentDynaSqlProvider.class , method = "insertStudent")
	int insertStudent(Student student);

	//根据id删除一个学生
	@DeleteProvider(type = StudentDynaSqlProvider.class , method = "deleteStudentByid")
	int deleteStudentByid(int id);

	//改变一个学生信息
	@UpdateProvider(type = StudentDynaSqlProvider.class , method = "updateStudentByid")
	int updateStudentByid(Student student);
}
2.创建存放动态SQL的StudentDynaSqlProvider类
package com.mapper;

import org.apache.ibatis.jdbc.SQL;

import com.po.Student;

public class StudentDynaSqlProvider {
	//动态的查询全部学生信息的SQL语句
	public String selectAllStu() {
		return new SQL() {
			{
				SELECT("*");
				FROM("student");
			}
		}.toString();	
	}

	//动态的查询一条或多条学生信息根据一个条件
	public String selectOneStuBy(Student student) {
		return new SQL() {
			{
				SELECT("*");
				FROM("student");
				if (student.getId()!=null) {
					WHERE("id=#{id}");
				}
				if (student.getLoginname()!=null) {
					WHERE("loginname=#{loginname}");
				}
				if (student.getUsername()!=null) {
					WHERE("username=#{username}");
				}
				if (student.getAge()!=null) {
					WHERE("age=#{age}");
				}
			}
		}.toString();
	}

	//动态插入
	public String insertStudent(Student student) {
		return new SQL() {
			{
				INSERT_INTO("student");
				if (student.getId()>0) {
					VALUES("id", "#{id}");
				}
				if (student.getLoginname()!=null) {
					VALUES("loginname", "#{loginname}");
				}
				if (student.getUsername()!=null) {
					VALUES("username", "#{username}");
				}
				if (student.getAge()!=null) {
					VALUES("age", "#{age}");
				}
			}
		}.toString();
	}

	//动态删除
	public String deleteStudentByid(int id) {
		return new SQL() {
			{
				DELETE_FROM("student");
				WHERE("id=#{id}");
			}
		}.toString();

	}

	//动态更新
	public String updateStudentByid(Student student) {
		return new SQL() {
			{
				UPDATE("student");
				if (student.getLoginname()!=null) {
					SET("loginname=#{loginname}");
				}
				if (student.getUsername()!=null) {
					SET("username=#{username}");
				}
				if (student.getAge()>0) {
					SET("age=#{age}");
				}
				WHERE("id=#{id}");
			}
		}.toString();

	}
}

image
在进行更新时,先进行条件查询测试,然后进行更新测试,最后进行全部查询测试。

posted @ 2021-07-14 15:58  luohuasheng  阅读(46)  评论(0编辑  收藏  举报