iis服务器助手广告
返回顶部
首页 > 资讯 > 后端开发 > Python >springbootjpaRepository为何一定要对Entity序列化
  • 517
分享到

springbootjpaRepository为何一定要对Entity序列化

2024-04-02 19:04:59 517人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

目录SpringBoot jpaRepository对Entity序列化1. 问题2. 写个基本的JpaRepository的使用最后一个简单的测试springboot 使用JpaR

springboot jpaRepository对Entity序列化

1. 问题

一开始,我没有对实体类Inventory序列化,导致在使用内嵌数据库H2的JPA时,它直接安装字母序列把表Inventory的字段生成。

举例,原来我按照


inventory(id, name, quantity, type, comment)

顺序写的数据库导入表,但是因为没有序列化,导致表结构变成


inventory(id, comment,name, quantity, type )

所以后面JPA处理失败。

2. 写个基本的JpaRepository的使用

顺便记录一下写spring cloud 基于和H2 database的jpa简单restful 程序。

实体类Inventory


package com.example.demo; 
import java.io.Serializable; 
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
 
@Entity
public class Inventory implements Serializable{ 
    private static final long serialVersionUID = 1L; 
    @Id
    @SequenceGenerator(name="inventory_generator", sequenceName="inventory_sequence", initialValue = 2)
    @GeneratedValue(generator = "inventory_generator")
    private Integer id;
    @Column(nullable = false)
    private String name;
    @Column(nullable = false)
    private Integer quantity;
    @Column(nullable = false)
    private Integer type;
    @Column(nullable = false)
    private String comment;
    public Inventory(Integer id, String name, Integer quantity, Integer type, String comment) {
        super();
        this.id = id;
        this.name = name;
        this.quantity = quantity;
        this.type = type;
        this.comment = comment;
    }
    public Inventory() {
        super();
    }
    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 getQuantity() {
        return quantity;
    }
    public void setQuantity(Integer quantity) {
        this.quantity = quantity;
    }
    public Integer getType() {
        return type;
    }
    public void setType(Integer type) {
        this.type = type;
    }
    public String getComment() {
        return comment;
    }
    public void setComment(String comment) {
        this.comment = comment;
    }
    @Override
    public String toString() {
        return "Inventory [id=" + id + ", name=" + name + ", quantity=" + quantity + ", type=" + type + ", comment="
                + comment + "]";
    }
}

下面使用JpaRepository简化开发流程,非常舒服地定义简单的service 接口即可,会自动实现,大赞。


package com.example.demo; 
import org.springframework.data.jpa.repository.JpaRepository; 
public interface InventoryRepository extends JpaRepository<Inventory, Integer> { 
    Inventory findById(Integer id); 
}

我把controller方法放到了springboot启动类里面,这又是一个大问题,因为我的项目只有放在这才能被dispatcher转发,简直了。

这里的@EnableDiscoveryClient 是因为我在做spring cloud的eureka 服务发现,需要这个注解让注册中心发现这个服务。


package com.example.demo; 
import java.time.LocalTime; 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.WEB.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
 
@SpringBootApplication
@EnableDiscoveryClient
@RestController
public class InventoryApplication { 
    public static void main(String[] args) {
        SpringApplication.run(InventoryApplication.class, args);
    }
    @Autowired
    private InventoryRepository inventoryRepository;
 
    @Value("${server.port}")
    private Integer port; 
    @RequestMapping("/info")
    public String info(){
        inventoryRepository.save(new Inventory(1, "火锅底料", 10000, 1, "你吃火锅,我吃底料"));
        inventoryRepository.save(new Inventory(2, "微服务架构", 100, 2, "微服务还是要考虑 一波"));
        return "{Inventory[port:"+port+", info:库存微服务"+"]}";
    }
 
    @GetMapping("/get/{id}")
    @ResponseBody
    @Transactional
    public String getById(@PathVariable("id")Integer id){
        return inventoryRepository.findById(id).toString();
    }
 
    @GetMapping("/")
    @ResponseBody
    @Transactional
    public String re(){
        return inventoryRepository.findAll().toString();
    }
 
    @GetMapping("/delete/{id}")
    @ResponseBody
    @Transactional
    public String delete(@PathVariable("id")Integer id){
        inventoryRepository.delete(id);
        return "delete successfully";
    }
 
    @GetMapping("/save/id={id}&name={name}&quantity={quantity}&type={type}&comment={comment}")

    public String save(@PathVariable("id")Integer id,@PathVariable("name")String name,
            @PathVariable("quantity")Integer quantity,@PathVariable("type")Integer type,
            @PathVariable("comment")String comment){
        inventoryRepository.save(new Inventory(id,name,quantity,type,comment));
        System.out.println(new Inventory(id,name,quantity,type,comment));
        //强调一下identity和auto
        return "save successfully";
    }
 
    @GetMapping("/update/id={id}&name={name}&quantity={quantity}&type={type}&comment={comment}")
    @ResponseBody
    @Transactional
    public String update(@PathVariable("id")Integer id,@PathVariable("name")String name,
            @PathVariable("quantity")Integer quantity,@PathVariable("type")Integer type,
            @PathVariable("comment")String comment){
        Inventory inventory=inventoryRepository.findById(id);
        if(inventory.getComment().length()<LocalTime.now().toString().length()){
            inventory.setComment(inventory.getComment()+LocalTime.now());
        }else{
            inventory.setComment(inventory.getComment().substring(0,inventory.getComment().length()-
                    LocalTime.now().toString().length())+LocalTime.now());
        }
        inventoryRepository.save(inventory);
        inventoryRepository.flush();
        return "update successfully";
    }
}

application.properties的配置很关键,搜了不少教程


spring.jpa.show-sql=true
logging.pattern.level=trace
server.port=8765
spring.application.name=inventory
server.Tomcat.max-threads=1000
eureka.instance.leaseRenewalIntervalInSeconds= 10
eureka.client.reGIStryFetchIntervalSeconds= 5
eureka.client.serviceUrl.defaultZone=Http://localhost:8889/eureka
#eureka.client.service-url.defaultZone=http://${eureka.instance.hostname}:${eureka.instance.server.port}/eureka
 
#spring.thymeleaf.prefix=classpath:/templates/  
#spring.thymeleaf.suffix=.html  
#spring.thymeleaf.mode=HTML5  
#spring.thymeleaf.encoding=UTF-8  
# ;charset=<encoding> is added  
#spring.thymeleaf.content-type=text/html  
# set to false for hot refresh  
spring.h2.console.enabled=true
spring.thymeleaf.cache=false  
spring.jpa.hibernate.ddl-auto=update
#这里是把h2持久化到本地文件夹,这可以保持数据
spring.datasource.url=jdbc:h2:file:C\:/h2/h2cache;AUTO_SERVER=TRUE;DB_CLOSE_DELAY=-1
logging.file=c\:/h2/logging.log
logging.level.org.hibernate=debug
#spring.datasource.data=classpath:import.sql

数据库是自动导入的,只要命名方式是import.sql, 放在src/main/resources下面就可以


insert into inventory(id, name, quantity, type, comment) values (1, "火锅底料", 10000, 1, "你吃火锅,我吃底料")
insert into inventory(id, name, quantity, type, comment) values (2, "微服务架构", 100, 2, "微服务还是要考虑 一波")

最后一个简单的测试

junit测试一波


package com.example.demo; 
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; 
@RunWith(SpringRunner.class)
@SpringBootTest
public class InventoryApplicationTests {
 
    @Autowired
    private InventoryRepository inventoriRepository;
 
    @Test
    public void test2() {
        System.out.println(inventoriRepository.findAll());
    } 
}

这里写图片描述

上图是项目结构图

springboot 使用JpaRepository

在对数据库操作时使用 MissionInfoRepository,对应的实体类必须用下面两个注解修饰


@Entity
@Table(name = "mission_info")

主键用下面修饰


 @Id
 @GeneratedValue(strategy = IDENTITY)
 @Column(name = "id", nullable = false)

在这里插入图片描述

属性命名如果使用驼峰,例如missionId,表中字段对应mission_id,否则对数据库操作的时候会报错,所以在表字段定义的时候,方便代码里使用JPA的话,表字段定义多个词之间用“_”隔开,而不是驼峰定义表字段。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

--结束END--

本文标题: springbootjpaRepository为何一定要对Entity序列化

本文链接: https://www.lsjlt.com/news/159246.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • springbootjpaRepository为何一定要对Entity序列化
    目录springboot jpaRepository对Entity序列化1. 问题2. 写个基本的JpaRepository的使用最后一个简单的测试springboot 使用JpaR...
    99+
    2024-04-02
  • springboot jpaRepository为什么一定要对Entity序列化
    这篇文章主要介绍“springboot jpaRepository为什么一定要对Entity序列化”,在日常操作中,相信很多人在springboot jpaRepository为什么一定要对Entity序列化问题上存在疑...
    99+
    2023-06-21
  • redis为什么要序列化对象
    redis要序列化对象是使对象可以跨平台存储和进行网络传输。因为存储和网络传输都需要把一个对象状态保存成一种跨平台识别的字节格式,然后其他的平台才可以通过字节信息解析还原对象信息,所以进行“跨平台存储”和”网络传输”的数据都需要进行序列化。...
    99+
    2024-04-02
  • 一文详解Java对象的序列化和反序列化
    目录一、什么是 Java 序列化和反序列化?二、序列化和反序列化的实现方式三、序列化和反序列化的注意事项四、序列化和反序列化的优点和缺点五、总结Java 对象的序列化和反序列化是一种...
    99+
    2023-05-16
    Java对象序列化 Java对象反序列化 Java对象序列化和反序列化
  • C#如何对Json进行序列化和反序列化
    这篇“C#如何对Json进行序列化和反序列化”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“C#如何对Json进行序列化和反序...
    99+
    2023-06-30
  • 在Python 中将类对象序列化为JSON
    目录1. 引言2. 举个栗子3. 解决方案3.1 使用 json.dumps() 和 __dict__3.2 实现 __str__ 和 __repr__3.3 实现 JSON enc...
    99+
    2024-04-02
  • .如何理解.NET对象的XML序列化和反序列化
    .如何理解.NET对象的XML序列化和反序列化,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。.NET对象的XML序列化和反序列化是如何实现的呢?通过下面实例中的...
    99+
    2023-06-17
  • 探讨一下JS为什么提交表单前需要序列化
    Javascript是一种被广泛应用于web前端的编程语言。在web开发中,表单(form)提交是一个非常常见的操作,而在Javascript中,提交表单前通常需要序列化(serialize)表单数据。本文旨在探讨一下Javascript为...
    99+
    2023-05-14
  • redis要序列化对象的原因是什么
    Redis要序列化对象的原因有以下几点:1. 数据持久化:Redis是一个内存数据库,如果不进行序列化,那么数据只会存在于内存中,一...
    99+
    2023-09-01
    redis
  • C#开发中如何处理对象序列化和反序列化
    C#开发中如何处理对象序列化和反序列化,需要具体代码示例在C#开发中,对象序列化和反序列化是非常重要的概念。序列化是将对象转换为可以在网络上传输或在磁盘上存储的格式,而反序列化则是将序列化后的数据重新转换为原始对象。本文将介绍在C#中如何处...
    99+
    2023-10-22
    序列化 反序列化 对象处理
  • 如何自定义Jackson序列化 @JsonSerialize
    目录自定义Jackson序列化 @JsonSerializejackson自定义全局序列化、反序列化创建序列化类创建反序列化类将两个类注册进入jackson核心对象objectMap...
    99+
    2024-04-02
  • 在Python中怎么将类对象序列化为JSON
    本文小编为大家详细介绍“在Python中怎么将类对象序列化为JSON”,内容详细,步骤清晰,细节处理妥当,希望这篇“在Python中怎么将类对象序列化为JSON”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。1. ...
    99+
    2023-06-29
  • Java自定义序列化行为的示例分析
    这篇文章给大家分享的是有关Java自定义序列化行为的示例分析的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。正常情况下,一个类实现java序列化很简单,只需要implements Serializable接口即可,...
    99+
    2023-06-17
  • 如何将复杂对象序列化为Redis可存储的形式
    将复杂对象序列化为Redis可存储的形式可以通过以下几种方法: 使用JSON序列化:将复杂对象转换为JSON字符串,然后将其存储...
    99+
    2024-04-29
    Redis
  • SpringBoot集成Redis,并自定义对象序列化操作
    SpringBoot项目使用redis非常简单,pom里面引入redis的场景启动器,在启动类上加@EnableCaching注解,项目启动会自动匹配上redis,这样项目中就可以愉...
    99+
    2024-04-02
  • InnoDB表为什么一定要用自增列做主键
    这篇文章主要介绍InnoDB表为什么一定要用自增列做主键,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完! 0、导读 我们先了解下InnoDB引擎表的一些关键特征: InnoD...
    99+
    2024-04-02
  • Go Spring开发技术中,如何实现对象的序列化和反序列化?
    在Go Spring开发中,对象的序列化和反序列化是非常常见的操作。序列化是将对象转换为字节流的过程,而反序列化则是将字节流转换回对象。在本文中,我们将探讨Go Spring开发技术中如何实现对象的序列化和反序列化。 一、JSON序列化和...
    99+
    2023-07-26
    spring 开发技术 对象
  • 如何对pytorch中不定长序列补齐
    小编给大家分享一下如何对pytorch中不定长序列补齐,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!第二种方法通常是在load一个batch数据时, 在collate_fn中进行补齐的.以下给出两种思路:第一种思路是比较容...
    99+
    2023-06-15
  • redis缓存对象如何实现序列化
    Redis缓存对象的序列化可以使用以下方法实现:1. 使用Redis自带的序列化机制:Redis提供了几种默认的序列化方式,包括ra...
    99+
    2023-09-06
    redis
  • 如何使用Python中的pickle和JSON进行对象序列化和反序列化
    如何使用Python中的pickle和JSON进行对象序列化和反序列化Python是一种简单而强大的编程语言,其内置了许多有用的库和模块,使开发人员能够快速进行各种任务。其中,pickle和JSON是两个常用的模块,用于对象序列化和反序列化...
    99+
    2023-10-22
    序列化 JSON pickle
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作