SpringBoot整合Jpa实现数据的增删改查

版权声明: https://blog.csdn.net/RAVEEE/article/details/85235704

SpringBoot是什么?

SpringBoot框架  Spring
Boot是由Pivotal团队提供的全新框架,属于spring旗下的一个项目,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,它使用“习惯优于配置”的理念,从而使开发人员不再需要定义样板化的配置。使用springboot很容易创建一个独立运行的spring项目,并且可以几乎不使用spring配置或者使用很少的配置。

Jpa是什么?

JPA的主要目标之一就是提供更加简单的编程模型:在JPA框架下创建实体和创建Java 类一样简单,没有任何的约束和限制,只需要使用
javax.persistence.Entity进行注释,JPA的框架和接口也都非常简单,没有太多特别的规则和设计模式的要求,开发者可以很容易地掌握。JPA基于非侵入式原则设计,因此可以很容易地和其它框架或者容器集成。

Spring Data JPA相对于JAVA EE中的JPA,配置更简单,以轻量级的方式实现了部分在 EJB 容器环境下才具有的功能,将 EntityManager 的创建与销毁、事务管理等代码抽取出来,并由其统一管理,并且极大的简化了数据库访问层的代码。
总的来说:jpa是一种规范,也可说它是hibernate的进一步封装,其简单的只要编写Repository接口即可,会自动创建实现类

SpringBoot整合jpa框架

接下来将会简洁明了的使用Springboot整合jpa框架,并实现相关的增删改查方法。
所需环境:mysql数据库,springboot sts3
新建一个springboot项目
1.pom文件
加入一下依赖到pom文件中

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

2.mysql数据库创建表
mysql数据库已经准备好,创建以下表,也可以使用我提供的sql文件进行创建

/*
Navicat MySQL Data Transfer

Source Server         : localhost_3306
Source Server Version : 50620
Source Host           : localhost:3306
Source Database       : secure

Target Server Type    : MYSQL
Target Server Version : 50620
File Encoding         : 65001

Date: 2018-12-24 16:20:33
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `t_user`
-- ----------------------------
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
  `id` bigint(22) NOT NULL AUTO_INCREMENT,
  `name` varchar(22) DEFAULT NULL,
  `age` varchar(22) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of t_user
-- ----------------------------

3.配置applicaiton.properties
配置如下,其中username password url修改为自己的账号 密码 数据库地址

server.port=80
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost/secure?characterEncoding=utf8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root

4.编写实体类
这里以user类为例子,包含name ,id ,age等属性。代码如下:

/**
 * @author Ray
 *
 */
package com.secure.pojo;

import javax.persistence.*;

@Entity
@Table(name = "t_user")
public class User {
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "id")
	private Long id;// 用户编号
	@Column(name = "name")
	private String name;// 用户名称
	@Column(name = "age")
	private String age;// 用户年龄

	public Long getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

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

	public String getAge() {
		return age;
	}

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

}



5.编写Jpa接口层

package com.secure.jpa;

import java.io.Serializable;

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

import com.secure.pojo.User;

public interface UserJPA extends JpaRepository<User, Long>, JpaSpecificationExecutor<User>, Serializable {
}

7.编写Controller控制层

package com.secure.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.secure.jpa.UserJPA;
import com.secure.pojo.User;

@RestController
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserJPA userJPA;
	@RequestMapping(value = "/save", method = RequestMethod.GET)
	public User save(User user) {
		return userJPA.save(user);
	}

}

8.使用springboot整合jpa执行数据的插入
访问http://localhost/user/save?name=xyf&age=22
测试成功,其他删除编辑的用法和增加大体相同。
在这里插入图片描述

可以看到接口已经访问成功,数据已经保存至数据库。
JpaRepository相关的接口

> List<T> findAll(); List<T> findAll(Sort sort); List<T>
> findAllById(Iterable<ID> ids); <S extends T> List<S>
> saveAll(Iterable<S> entities); void flush(); <S extends T> S
> saveAndFlush(S entity); void deleteInBatch(Iterable<T> entities); void
> deleteAllInBatch(); T getOne(ID id); long count(); boolean
> existsById(ID id); void deleteById(ID id);

9.相关的注解讲解

@Id

>The mapped column for the primary key of the entity is assumed
 * to be the primary key of the primary table. If no <code>Column</code> annotation
 * is specified, the primary key column name is assumed to be the name
 * of the primary key property or field.

主要作用是用于标注主键

@Table

 Specifies the primary table for the annotated entity. Additional
 * tables may be specified using {@link SecondaryTable} or {@link
 * SecondaryTables} annotation.
 * <p/>
 * If no <code>Table</code> annotation is specified for an entity
 * class, the default values apply.
 *

主要用作指定实体类对应的表
写法如下:
*@Table(name = “t_user”)

@Column:*

* Is used to specify the mapped column for a persistent property or field.
 * If no <code>Column</code> annotation is specified, the default values apply.

如果字段名和数据库的字段名不一致,则使用该注解标注
写法如下:
@Column(name = “id”)
千万注意这里一个大坑,name="" 必须小写,如果大写则会以下划线的方式查询数据库。详情见https://www.jianshu.com/p/ba87a9ee6001

@GeneratedValue

<p> The <code>GeneratedValue</code> annotation
 * may be applied to a primary key property or field of an entity or
 * mapped superclass in conjunction with the {@link Id} annotation.
 * The use of the <code>GeneratedValue</code> annotation is only
 * required to be supported for simple primary keys.  Use of the
 * <code>GeneratedValue</code> annotation is not supported for derived
 * primary keys.

用于标注主键,不能被使用在派生主键,主要作用是设置主键的生成策略,@Id
是用来标注主键,其中@GeneratedValue主要有以下四种用法
@GeneratedValue(strategy=GenerationType.IDENINY)

PS:@GeneratedValue注解的strategy属性提供四种值:

-AUTO主键由程序控制, 是默认选项 ,不设置就是这个

-IDENTITY 主键由数据库生成, 采用数据库自增长, Oracle不支持这种方式

-SEQUENCE 通过数据库的序列产生主键, MYSQL 不支持

如果数据库中设置了自增主键则应该使用IDENTITY注解,否则报错。

JpaRepository

提供了对数据库访问的增删改查的接口,其中对jpaRespository两个参数的解释如下:

public interface UserJPA extends JpaRepository<User, Long>, JpaSpecificationExecutor<User>, Serializable {
       @param <T> the domain type the repository manages
     * @param <ID> the type of the id of the entity the repository manages

T:实体类
ID: 在仓库中实体类的id

猜你喜欢

转载自blog.csdn.net/RAVEEE/article/details/85235704