springboot整合jpa实现增删改查

一、Jpa简介

1、什么是JPA?

        JPA是一套Java官方制定的ORM 方案,是Java的一个规范 。Spring Data JPA是对基于 JPA 的数据访问层的增强支持。

        应用JPA的主流框架:Hibernate (JBoos)、EclipseTop(Eclipse社区)、OpenJPA (Apache基金会)。 

2、为什么使用JPA?

JPA优点:

   (1)简单易用,帮助开发者提供了生产率

   (2)便于维护,减低了维护成本

   (3)学习成本相对比较低。

jPA存在的缺点:

   (1)将语言与数据库混在一起,导致数据改动以后,配置文件必须更新

   (2)对与多数据与大数据量处理很容易产生性能问题。

   (3)过度封装,导致错误查找相对与JDBC等传统开发技术而言更加困难

3、JPA的特征

  • 为构建基于 Spring 和 JPA 的存储库提供高级支持

  • 支持Querydsl谓词,因此类型安全的 JPA 查询

  • 域类的透明审计

  • 分页支持,动态查询执行,集成自定义数据访问代码的能力

  • 在引导时验证带注释的查询@Query

  • 支持基于 XML 的实体映射

  • 通过引入 基于 JavaConfig 的存储库配置。@EnableJpaRepositories

4、JPA常用注解

注解 解释
@Entity 标识实体类是JPA实体,告诉JPA在程序运行时生成实体类对应表
@Table 设置实体类在数据库所对应的表名
@Basic 表示简单属性到数据库表字段的映射(几乎不用)
@Column 表示属性所对应字段名进行个性化设置
@GeneratedValue 设置主键生成策略,此方式依赖于具体的数据库
@Id 标识类里所在变量为主键
@Transient

表示属性并非数据库表字段的映射,ORM框架将忽略该属性

如果一个属性并非数据库表的字段映射,就务必将其标示为@Transient,否则,

ORM框架默认其注解为@Basic

@Temporal

当我们使用到java.util包中的时间日期类型,则需要此注释来说明转化成java.util包

中的类型。注入数据库的类型有三种:

   TemporalType.DATE(2008-08-08)

   TemporalType.TIME(20:00:00)

   TemporalType.TIMESTAMP(2008-08-08 20:00:00.000000001)

@OneToOne

一个一对一的关联

fetch:表示抓取策略,默认为FetchType.LAZY
cascade:表示级联操作策略

@OneToMany

一个一对多的关联,该属性应该为集体类型,在数据库中并没有实际字段.

fetch:表示抓取策略,默认为FetchType.EAGER
cascade:表示默认的级联操作策略,可以指定为ALL,PERSIST,MERGE,

REFRESH和REMOVE中的若干组合,默认为无级联操作

@ManyToOne

一个多对一的映射,该注解标注的属性通常是数据库表的外键

optional:是否允许该字段为null,该属性应该根据数据库表的外键约束来确定,

默认为true
fetch:表示抓取策略,默认为FetchType.EAGER
cascade:表示默认的级联操作策略,可以指定为ALL,PERSIST,MERGE,

REFRESH和REMOVE中的若干组合,默认为无级联操作
targetEntity:表示该属性关联的实体类型.该属性通常不必指定,ORM框架根据

属性类型自动判断targetEntity.

@ManyToMany

一个多对多的关联.多对多关联上是两个一对多关联,但是在ManyToMany描述

中,中间表是由ORM框架自动处理

targetEntity:表示多对多关联的另一个实体类的全名,例如:package.Book.class
mappedBy:表示多对多关联的另一个实体类的对应集合属性名称

二、入门案例

1、搭建环境

springboot整合jpa实现增删改查_第1张图片springboot整合jpa实现增删改查_第2张图片springboot整合jpa实现增删改查_第3张图片

2、导入依赖

(1)、整合jpa需导入依赖

 
        
        
            org.springframework.boot
            spring-boot-starter-data-jpa
            2.1.7.RELEASE
        
        
            com.h2database
            h2
            runtime
        

(2)、完整pom.xml文件



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.1.7.RELEASE
         
    
    com.example
    springboot-jpa
    0.0.1-SNAPSHOT
    springboot-jpa
    springboot-jpa
    
        1.8
    
    
        
        
            org.springframework.boot
            spring-boot-starter
        
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
            
                
                    org.junit.vintage
                    junit-vintage-engine
                
            
        
        
            junit
            junit
            test
        

        
            org.springframework.boot
            spring-boot-devtools
            true
            
        

        
        
        
            org.springframework.boot
            spring-boot-starter-data-jpa
            2.1.7.RELEASE
        
        
            com.h2database
            h2
            runtime
        
        
        
            org.projectlombok
            lombok
        
        
        
            mysql
            mysql-connector-java
            5.1.10
        
        
        
            com.alibaba
            druid
            1.1.10
            compile
        

    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
            
                org.apache.maven.plugins
                maven-surefire-plugin
                
                    true
                
            
        
    


3、创建数据库

(1)、创建数据库

        在你的数据库软件中,新建数据库mybatis04(注:由于springboot集成了JPA,因而创建数据库是不需要创建表,表会根据对象实体类的映射关系,通过运行程序,自动在数据库中生成

(2)、idea连接数据库

springboot整合jpa实现增删改查_第4张图片

4、配置application.yml文件

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mybatis04?useUnicode=true&characterEncoding=utf-8
    username: root
    password: x5  #配置数据源
  jpa:
    #这个参数是在建表的时候,将默认的存储引擎切换为 InnoDB 用的
    database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
    #控制台显示SQL
#    show-sql: true
    hibernate:
      #更新或者创建数据表结构
      ddl-auto: update
server:
  port: 8082


5、创建User实体类

package com.example.springbootjpa.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;

import javax.persistence.*;


@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "user")
@Component
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)//自增主键
    Integer id;
    @Column(length = 50)
    String name;
    @Column(length = 50)
    String age;

}

注:springboot整合jpa项目中,创建完实体类后,因为ORM(对象映射关系)的缘故,可以通过运行项目,自动在数据库中创建对应表及字段

6、创建dao层接口

package com.example.springbootjpa.mapper;

import com.example.springbootjpa.pojo.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

@Repository
public interface UserRepository extends JpaRepository {

}

7、编写测试类

package com.example.springbootjpa;

import com.example.springbootjpa.mapper.UserRepository;
import com.example.springbootjpa.pojo.User;
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.SpringRunner;

import java.util.Optional;


@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootJpaApplicationTest {
    @Autowired
    UserRepository userRepository;

/*    @Test
    public void test01(){
        User user=new User();
        user.setName("lihua");
        user.setAge("12");
        userRepository.save(user);
    }

    @Test
    public void query(){
        List list=userRepository.findAll();
        System.out.println(list);
    }
    @Test
    public void del(){
        userRepository.deleteById(11);
    }*/

    @Test
    public void selectById(){
        Optional list=userRepository.findById(2);
        System.out.println(list);
    }

}

运行结果:

三、项目源码

    源码地址:springboot-jpa · 沐曦辰/springboard - 码云 - 开源中国 (gitee.com)

你可能感兴趣的:(环境配置,springboot框架,java,spring,boot)