zoukankan      html  css  js  c++  java
  • SpringBoot学习笔记(7)整合JPA

    1.什么是JPA

    JPA(Java Persistence API)是Sun官方提出的Java持久化规范。它为Java开发人员提供了一种对象/关联映射工具来管理Java应用中的关系数据。他的出现主要是为了简化现有的持久化开发工作和整合ORM技术,结束现在Hibernate,TopLink,JDO等ORM框架各自为营的局面。
    注意:JPA是一套规范,不是一套产品,那么像Hibernate,TopLink,JDO他们是一套产品,如果说这些产品实现了这个JPA规范,那么我们就可以叫他们为JPA的实现产品。

    2.Spring Data JPA

    Spring Data JPA 是 Spring 基于 ORM 框架、JPA 规范的基础上封装的一套JPA应用框架,可使开发者用极简的代码即可实现对数据的访问和操作。它提供了包括增删改查等在内的常用功能,且易于扩展!学习并使用 Spring Data JPA 可以极大提高开发效率!spring data jpa让我们解脱了DAO层的操作,基本上所有CRUD都可以依赖于它来实现。

    3.快速开发一个案例

    3.1 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>
    <!--自定义连接池-->
    <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.10</version>
    </dependency>
    <dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.1</version>
    </dependency>

    3.2 在yml配置文件中 进行配置

    spring:
      datasource:
        username: root
        password: 123456
        url: jdbc:mysql://192.168.0.157:3306/db1
        driver-class-name: com.mysql.cj.jdbc.Driver
        type: com.alibaba.druid.pool.DruidDataSource
    
        #   数据源其他配置
        #初始化大小,最小,最大
        initialSize: 5
        minIdle: 5
        maxActive: 20
        # 配置获取连接等待超时的时间
        maxWait: 60000
        # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
        timeBetweenEvictionRunsMillis: 60000
        # 配置一个连接在池中最小生存的时间,单位是毫秒
        minEvictableIdleTimeMillis: 300000
        validationQuery: SELECT 1 FROM DUAL
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
        poolPreparedStatements: true
        #   配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
        filters: stat,wall,log4j
        maxPoolPreparedStatementPerConnectionSize: 20
        useGlobalDataSourceStat: true
        connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
      jpa:
        hibernate:
          ddl-auto: update #第一次建表create  后面用update,要不然每次重启都会新建表
        show-sql: true
    mybatis:
      config-location: classpath:mapping/mybatis-config.xml
      mapper-locations: classpath:mapping/modules/*.xml
    

    3.3 创建一个entity

    @Entity     //告诉jpa这是一个实体类
    @Table(name = "gy_user") //指定和哪个数据表对应
    @JsonIgnoreProperties(value = {"hibernateLazyInitializer", "handler"})
    public class UserPO {
    
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY) //自增主键
        private Integer id;
        @Column(name = "user_name", length = 50)
        private String userName;
        @Column
        private String password;

    com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class操作数据库的过程中会出现这样一个异常,
    导致这异常的原因是实体类中有的字段值为null,所以在json化的时候,fasterxml.jackson将对象转换为json报错
    在实体类上面加上注解 @JsonIgnoreProperties(value = { "hibernateLazyInitializer", "handler" }) 解决这个问题

    3.4 创建DAO
    import com.meng.demo.entity.UserPO;
    import org.springframework.data.jpa.repository.JpaRepository;

    /*
    * 我们在这里直接继承 JpaRepository
    * 这里面已经有很多现场的方法了
    * 这也是JPA的一大优点
    *
    * */
    public interface UserMapper extends JpaRepository<UserPO, Integer> {


    }  

    3.5 Controller类

    @GetMapping("/user")
        public UserPO userInset(UserPO userPO){
            userMapper.save(userPO);
            return userPO;
        }
    
        @GetMapping("/user/{id}")
        public UserPO getUser(@PathVariable("id") Integer id){
            return userMapper.getOne(id);
        }

    这里我们可以看到userMapper接口继承了很多方法

     4.启动项目

    在启动日志中我们可以看到

     数据表会自动创建,此时我们查看数据库

     5.测试访问

    在浏览器中访问我们写的测试方法

    新增一条数据:http://localhost:8080/user?userName=%E6%B5%8B%E8%AF%9501&password=123

    查询一条数据:http://localhost:8080/user/1

    com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class

  • 相关阅读:
    EF中的EntityState几个状态的说明
    sql server 更新表,每天的数据分固定批次设置批次号sql
    bootstrap Validators
    马老师 生产环境mysql主从复制、架构优化方案
    PHP在微博优化中的“大显身手”
    将form表单转化为json数据
    免费资源库收集
    奇怪的php问题
    PHP 大数自动转换为科学计数法
    access database in a helper function ?
  • 原文地址:https://www.cnblogs.com/mengY/p/11734458.html
Copyright © 2011-2022 走看看