SpringBoot入门(六)(Spring Boot中使用Spring-data-jpa访问数据库)

本文介绍如何使用Spring Data JPA简化数据库操作,包括快速搭建环境、实体类定义、编写数据访问接口及单元测试等内容。

官方文档地址:https://spring.io/guides/gs/accessing-data-jpa/

在上一篇Spring Boot中使用JdbcTemplate访问数据库 中介绍了一种基本的数据访问方式,结合构建RESTful API使用Thymeleaf模板引擎渲染Web视图的内容就已经可以完成App服务端和Web站点的开发任务了。

然而,在实际开发过程中,对数据库的操作无非就“增删改查”。就最为普遍的单表操作而言,除了表和字段不同外,语句都是类似的,开发人员需要写大量类似而枯燥的语句来完成业务逻辑。

为了解决这些大量枯燥的数据操作语句,我们第一个想到的是使用ORM框架,比如:Hibernate。通过整合Hibernate之后,我们以操作Java实体的方式最终将数据改变映射到数据库表中。

为了解决抽象各个Java实体基本的“增删改查”操作,我们通常会以泛型的方式封装一个模板Dao来进行抽象简化,但是这样依然不是很方便,我们需要针对每个实体编写一个继承自泛型模板Dao的接口,再编写该接口的实现。虽然一些基础的数据访问已经可以得到很好的复用,但是在代码结构上针对每个实体都会有一堆Dao的接口和实现。

而使用Spring-data-jpa的话我们只需要通过编写一个继承自JpaRepository的接口就能完成数据访问,下面以一个具体实例来体验Spring-data-jpa给我们带来的强大功能。

使用示例

由于Spring-data-jpa依赖于Hibernate。如果您对Hibernate有一定了解,下面内容可以毫不费力的看懂并上手使用Spring-data-jpa。如果您还是Hibernate新手,您可以先按如下方式入门,再建议回头学习一下Hibernate以帮助这部分的理解和进一步使用。

首先引入依赖:

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.45</version>
		</dependency>
		
		
		
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>

application.xml中配置:数据库连接信息(如使用嵌入式数据库则不需要)、自动创建表结构的设置,例如使用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

spring.jpa.properties.hibernate.hbm2ddl.auto=update

spring.jpa.properties.hibernate.hbm2ddl.auto是hibernate的配置属性,其主要作用是:自动创建、更新、验证数据库表结构。该参数的几种配置如下:

  • create:每次加载hibernate时都会删除上一次的生成的表,然后根据你的model类再重新来生成新表,哪怕两次没有任何改变也要这样执行,这就是导致数据库表数据丢失的一个重要原因。
  • create-drop:每次加载hibernate时根据model类生成表,但是sessionFactory一关闭,表就自动删除。
  • update:最常用的属性,第一次加载hibernate时根据model类会自动建立起表的结构(前提是先建立好数据库),以后加载hibernate时根据model类自动更新表结构,即使表结构改变了但表中的行仍然存在不会删除以前的行。要注意的是当部署到服务器后,表结构是不会被马上建立起来的,是要等应用第一次运行起来后才会。
  • validate:每次加载hibernate时,验证创建数据库表结构,只会和数据库中的表进行比较,不会创建新表,但是会插入新值。

然后创建实体:

创建一个User实体,包含id(主键)、name(姓名)、age(年龄)属性,通过ORM框架其会被映射到数据库表中,由于配置了hibernate.hbm2ddl.auto,在应用启动的时候框架会自动去数据库中创建对应的表。

package com.zy.SpringBootData.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;


@Entity
public class Student {
	@Id
	@GeneratedValue
	private Integer id;

	@Column(nullable = false)
	private String name;

	@Column(nullable = false)
	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;
	}

}

创建数据访问接口:

下面针对User实体创建对应的Repository接口实现对该实体的数据访问,如下代码:

package com.zy.SpringBootData.entity;



import org.springframework.data.jpa.repository.JpaRepository;


public interface StudentRepository extends JpaRepository<Student , Integer>{
	public Student findByName(String name);
	
	
	public Student  findByNameAndAge(String name, Integer age);
	
}

在Spring-data-jpa中,只需要编写类似上面这样的接口就可实现数据访问。不再像我们以往编写了接口时候还需要自己编写接口实现类,直接减少了我们的文件清单。

下面对上面的UserRepository做一些解释,该接口继承自JpaRepository,通过查看JpaRepository接口的API文档,可以看到该接口本身已经实现了创建(save)、更新(save)、删除(delete)、查询(findAll、findOne)等基本操作的函数,因此对于这些基础操作的数据访问就不需要开发者再自己定义。

在上例中,我们可以看到下面两个函数:

  • User findByName(String name)
  • User findByNameAndAge(String name, Integer age)

它们分别实现了按name查询User实体和按name和age查询User实体,可以看到我们这里没有任何类SQL语句就完成了两个条件查询方法。这就是Spring-data-jpa的一大特性:通过解析方法名创建查询

单元测试

在完成了上面的数据访问接口之后,按照惯例就是编写对应的单元测试来验证编写的内容是否正确。这里就不多做介绍,主要通过数据操作和查询来反复验证操作的正确性。

package com.zy.SpringBootData;

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.context.junit4.SpringJUnit4ClassRunner;


import com.zy.SpringBootData.entity.Student;
import com.zy.SpringBootData.entity.StudentRepository;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class SpringBootDataApplicationTests {
	
	@Autowired
	private StudentRepository studentRepository;
	
	@Test
	public void contextLoads() throws Exception{
		
		/*studentRepository.save(new Student(1, "a", 1));
		studentRepository.save(new Student(2, "b", 2));
		studentRepository.save(new Student(3, "c", 3));
		studentRepository.save(new Student(4, "d", 4));
		studentRepository.save(new Student(5, "e", 5));
		studentRepository.save(new Student(6, "f", 6));
		studentRepository.save(new Student(7, "g", 7));
		studentRepository.save(new Student(8, "h", 8));
		studentRepository.save(new Student(9, "i", 9));
		studentRepository.save(new Student(10, "j", 10));*/
		
		
		// 测试findAll, 查询所有记录
		Assert.assertEquals(10, studentRepository.findAll().size());

		// 测试findByName, 查询姓名为FFF的User
		Assert.assertEquals(1, studentRepository.findByName("a").getAge().longValue());

		// 测试findByNameAndAge, 查询姓名为FFF并且年龄为60的User
		Assert.assertEquals("f", studentRepository.findByNameAndAge("f", 6).getName());

		// 测试删除姓名为AAA的User
		studentRepository.delete(studentRepository.findByName("a"));

		// 测试findAll, 查询所有记录, 验证上面的删除是否成功
		Assert.assertEquals(9, studentRepository.findAll().size());

	}

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值