SpringBoot入门(七)(Spring Boot整合MyBatis,并使用MyBatis注解完成增删查改)

前面两篇博客我们已经简单的了解了springboot访问数据的两种方法。今天我们介绍springboot整合MyBatis框架,然后对数据库进行访问

pom.xml中引入依赖

  • 引入连接mysql的必要依赖mysql-connector-java
  • 引入整合MyBatis的核心依赖mybatis-spring-boot-starter
  • 这里不引入spring-boot-starter-jdbc依赖,是由于mybatis-spring-boot-starter中已经包含了此依赖

<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.45</version>
		</dependency>
		
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.1.1</version>
		</dependency>
		
	</dependencies>

同之前介绍的使用jdbc和spring-data连接数据库一样,在application.properties中配置mysql的连接配置:

spring.datasource.url=jdbc:mysql://localhost:3306/springboot
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
到这里,我们就已经基本整合完毕了,下面我们看看如何使用mybatis吧

使用MyBatis

  • 在Mysql中创建Student表,包含id(INT)、name(VARCHAR)、age(INT)字段。同时,创建映射对象Student
package com.zy.SpringBootMybatis.entity;

public class Student {

	private Integer id;

	private String name;

	private Integer age;

	public Student() {

	}

	public Student(Integer id, String name, Integer age) {
		this.id = id;
		this.name = name;
		this.age = age;
	}

	public Integer getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

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

	public Integer getAge() {
		return age;
	}

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

}
  • 创建Student映射的操作StudentMapper,为了后续单元测试验证,实现增删查改的操作:
package com.zy.SpringBootMybatis.entity;

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

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.annotations.Results;

@Mapper
public interface StudentMapper {
	@Select("SELECT * FROM STUDENT WHERE NAME = #{name}")
	public Student findByName(@Param("name") String name);

	@Insert("INSERT INTO STUDENT(ID , NAME, AGE) VALUES(#{id}, #{name}, #{age})")
	public int insert(@Param("id") Integer id, @Param("name") String name, @Param("age") Integer age);

	@Insert("INSERT INTO STUDENT(ID , NAME, AGE) VALUES(#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER})")
	public int insertByMap(Map<String, Object> map);

	@Insert("INSERT INTO STUDENT(ID , NAME, AGE) VALUES(#{id} , #{name}, #{age})")
	int insertByUser(Student stu);

	@Update("UPDATE STUDENT SET age=#{age} WHERE name=#{name}")
	void update(Student stu);

	@Delete("DELETE FROM STUDENT WHERE id =#{id}")
	void delete(Integer id);

	@Results({@Result(property = "id", column = "id") , @Result(property = "name", column = "name"), @Result(property = "age", column = "age") })
	@Select("SELECT id, name, age FROM STUDENT")
	List<Student> findAll();
}

这里简单的介绍一下上面使用到的注解以及传参方式:

传参方式

下面通过几种不同传参方式来实现上面代码中实现的插入操作。

使用@Param
@Insert("INSERT INTO STUDENT(ID , NAME, AGE) VALUES(#{id}, #{name}, #{age})")
public int insert(@Param("id") Integer id, @Param("name") String name, @Param("age") Integer age);

这种方式很好理解,@Param中定义的name对应了SQL中的#{name}age对应了SQL中的#{age},id对应了SQL中的#{id}

使用Map

如下代码,通过Map对象来作为传递参数的容器:

@Insert("INSERT INTO STUDENT(ID , NAME, AGE) VALUES(#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER})")
public int insertByMap(Map<String, Object> map);

对于Insert语句中需要的参数,我们只需要在map中填入同名的内容即可,具体如下面代码所示:

Map<String, Object> map = new HashMap<String, Object>();
    map.put("id", 2);
    map.put("name", "CCC");
    map.put("age", 40);
使用对象

除了Map对象,我们也可直接使用普通的Java对象来作为查询条件的传参,比如我们可以直接使用Student对象:

@Insert("INSERT INTO STUDENT(ID , NAME, AGE) VALUES(#{id} , #{name}, #{age})")
int insertByUser(Student stu);
这样语句中的#{id} , #{name} #{age} 就分别对应了Student对象中的 id, name age 属性

返回结果的绑定

对于增、删、改操作相对变化较小。而对于“查”操作,我们往往需要进行多表关联,汇总计算等操作,那么对于查询的结果往往就不再是简单的实体对象了,往往需要返回一个与数据库实体不同的包装类,那么对于这类情况,就可以通过@Results@Result注解来进行绑定,具体如下:

@Results({@Result(property = "id", column = "id") , @Result(property = "name", column = "name"), @Result(property = "age", column = "age") })
	@Select("SELECT id, name, age FROM STUDENT")
	List<Student> findAll();
在上面代码中,@Result中的property属性对应Student对象中的成员名,column对应SELECT出的字段名。


然后是测试文件:

package com.zy.SpringBootMybatis;

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

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit4.SpringRunner;

import com.zy.SpringBootMybatis.entity.Student;
import com.zy.SpringBootMybatis.entity.StudentMapper;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class SpringBootMybatisApplicationTests {
	
	@Autowired
	private StudentMapper studentMapper;
	
	@Test
	@Rollback
	public void contextLoads() {
		//studentMapper.insert(1, "AAA", 20); 
		//Student stu = studentMapper.findByName("AAA");
		//Assert.assertEquals(20, stu.getAge().intValue());
		
		
		
		/*Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", 2);
		map.put("name", "CCC");
		map.put("age", 40);
		studentMapper.insertByMap(map);
		Assert.assertEquals(40, studentMapper.findByName("CCC").getAge().intValue());*/
		

		/*Student s= new Student(3, "BBB", 30);
		studentMapper.insertByUser(s);
		Assert.assertEquals(30, studentMapper.findByName("BBB").getAge().intValue());*/
		
		
		// update一条数据,并select出来验证
		/*stu.setAge(30);
		studentMapper.update(stu);
		stu = studentMapper.findByName("AAA");
		Assert.assertEquals(30, stu.getAge().intValue());*/
		
		// 删除这条数据,并select验证
		/*studentMapper.delete(stu.getId());
		stu = studentMapper.findByName("AAA");
		Assert.assertEquals(null, stu);*/
		
		
		List<Student> stuList = studentMapper.findAll();
		for(Student stu : stuList) {
			/*Assert.assertEquals(null, stu.getId());
			Assert.assertNotEquals(null, stu.getName());*/
			System.out.println(stu.getId());
			System.out.println(stu.getName());
			System.out.println(stu.getAge());
		}
	}

}

更多其他注解的使用可参见文档:http://www.mybatis.org/mybatis-3/zh/java-api.html

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值