Spring boot Jpa添加对象字段使用数据库默认值

jpa做持久层框架,项目中数据库字段有默认值和非空约束,这样在保存对象是必须保存一个完整的对象,但在开发中我们往往只是先保存部分特殊的字段其余字段用数据库默认值,要是直接用idea生成实体类操作的话会报SQLIntegrityConstraintViolationException异常,我们需要jpa根据传入的对象存在的属性动态生成更新和添加语句需要给实体类添加@DynamicUpdate,@DynamicInsert根据对象属性生成动态update和insert语句。


建库建表
CREATE TABLE `student` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL COMMENT '姓名',
`age` int(3) NOT NULL DEFAULT '' COMMENT '年龄',
`adder` varchar(255) NOT NULL DEFAULT '北京' COMMENT '地址',
`class` int(15) NOT NULL DEFAULT '' COMMENT '班级',
`is_ali` tinyint(1) NOT NULL DEFAULT '' COMMENT '阿里认证',
`is_tx` tinyint(1) NOT NULL DEFAULT '' COMMENT '腾讯认证',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8

项目搭建

代码

配置文件

spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.database=mysql
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
StudnetController
package com.myjpa.demo.controller;

import com.myjpa.demo.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RestController; @RestController
public class StudnetController { @Autowired
StudentService student; @PutMapping("/add")
public String insertStudent(String name, Integer age) {
student.addStudent(name, age);
return "添加成功";
} }
StudentService
package com.myjpa.demo.service;

import com.myjpa.demo.entity.StudentEntity;
import com.myjpa.demo.respository.StudentRespository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; @Service
@Transactional(rollbackFor = Exception.class)
public class StudentService { @Autowired
StudentRespository studentRespository; public void addStudent(String name, Integer age) {
StudentEntity s = new StudentEntity();
s.setName(name);
s.setAge(age);
studentRespository.save(s);
}
}
StudentRespository
package com.myjpa.demo.respository;

import com.myjpa.demo.entity.StudentEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository; @Repository
public interface StudentRespository extends JpaRepository<StudentEntity, Long> {
}
StudentEntity 实体类可以使用idea反向生成
package com.myjpa.demo.entity;

import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate; import javax.persistence.*;
import java.util.Objects; @Entity
@Table(name = "student", schema = "test")
public class StudentEntity {
private long id;
private String name;
private int age;
private String adder;
private int clazz;
private byte isAli;
private byte isTx; @Id
@Column(name = "id")
public long getId() {
return id;
} public void setId(long id) {
this.id = id;
} @Basic
@Column(name = "name")
public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} @Basic
@Column(name = "age")
public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} @Basic
@Column(name = "adder")
public String getAdder() {
return adder;
} public void setAdder(String adder) {
this.adder = adder;
} @Basic
@Column(name = "class")
public int getClazz() {
return clazz;
} public void setClazz(int clazz) {
this.clazz = clazz;
} @Basic
@Column(name = "is_ali")
public byte getIsAli() {
return isAli;
} public void setIsAli(byte isAli) {
this.isAli = isAli;
} @Basic
@Column(name = "is_tx")
public byte getIsTx() {
return isTx;
} public void setIsTx(byte isTx) {
this.isTx = isTx;
} @Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
StudentEntity that = (StudentEntity) o;
return id == that.id &&
age == that.age &&
clazz == that.clazz &&
isAli == that.isAli &&
isTx == that.isTx &&
Objects.equals(name, that.name) &&
Objects.equals(adder, that.adder);
} @Override
public int hashCode() {
return Objects.hash(id, name, age, adder, clazz, isAli, isTx);
}
}
DemoApplication
package com.myjpa.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication
public class DemoApplication { public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
} }

错误测试

问题主要在于实体类,因为jpa生成sql依靠实体类

发送请求

服务器错误

解决问题

修改StudentEntity添加两个注解

@DynamicUpdate
@DynamicInsert

服务器更新,再次发送请求

数据库结果

成功

Spring boot Jpa添加对象字段使用数据库默认值的更多相关文章

  1. spring cloud spring boot JPA 克隆对象修改属性后 无法正常的执行save方法进行保存或者更新

    2019-12-1220:34:58 spring cloud spring boot JPA 克隆对象修改属性后 无法正常的执行save方法进行保存或者更新 未解决

  2. spring boot ----> jpa连接和操作mysql数据库

    环境: centos6.8,jdk1.8.0_172,maven3.5.4,vim,spring boot 1.5.13,mysql-5.7.23 1.引入jpa起步依赖和mysql驱动jar包 &l ...

  3. Java Spring Boot VS .NetCore (四)数据库操作 Spring Data JPA vs EFCore

    Java Spring Boot VS .NetCore (一)来一个简单的 Hello World Java Spring Boot VS .NetCore (二)实现一个过滤器Filter Jav ...

  4. Spring Boot + JPA(hibernate 5) 开发时,数据库表名大小写问题

      (转载)Spring Boot + JPA(hibernate 5) 开发时,数据库表名大小写问题   这几天在用spring boot开发项目, 在开发的过程中遇到一个问题hibernate在执 ...

  5. Spring Boot(五):Spring Boot Jpa 的使用

    在上篇文章Spring Boot(二):Web 综合开发中简单介绍了一下 Spring Boot Jpa 的基础性使用,这篇文章将更加全面的介绍 Spring Boot Jpa 常见用法以及注意事项. ...

  6. Spring Boot Jpa 的使用

    Spring Boot Jpa 介绍 首先了解 Jpa 是什么? Jpa (Java Persistence API) 是 Sun 官方提出的 Java 持久化规范.它为 Java 开发人员提供了一种 ...

  7. (转)Spring Boot(五):Spring Boot Jpa 的使用

    http://www.ityouknow.com/springboot/2016/08/20/spring-boot-jpa.html 在上篇文章Spring Boot(二):Web 综合开发中简单介 ...

  8. Spring Boot(十五):spring boot+jpa+thymeleaf增删改查示例

    Spring Boot(十五):spring boot+jpa+thymeleaf增删改查示例 一.快速上手 1,配置文件 (1)pom包配置 pom包里面添加jpa和thymeleaf的相关包引用 ...

  9. Spring boot JPA 用自定义主键策略 生成自定义主键ID

    最近学习Spring boot JPA 学习过程解决的一些问题写成随笔,大家一起成长.这次遇到自定义主键的问题 package javax.persistence; public enum Gener ...

随机推荐

  1. Bootloader与Kernel间参数传递机制 taglist【转】

    本文转载自:http://blog.csdn.net/tommy_wxie/article/details/9187821 Tag list被用来在bootloader和Linux kernel 之间 ...

  2. html5--6-2 CSS语法

    html5--6-2 CSS语法 实例 学习要点 掌握引入外部样式表方法 插入样式的三种方法 内联样式表(行内) 内部样式表(style中) 外部样式表 创建一个外部样式表 在head中使用link元 ...

  3. 一步一步学Silverlight 2系列(28):图片处理

    概述 Silverlight 2 Beta 1版本发布了,无论从Runtime还是Tools都给我们带来了很多的惊喜,如支持框架语言Visual Basic, Visual C#, IronRuby, ...

  4. hdu1226

    hdu1226 :点击打开题目链接 本题目由于题目意思,容易得知是一道广搜的题目. 首先. 我们需要知道 ,大数取模,比如 如何判断1234567 对15 取模的数为多少?答案是7,但是如果他是大数怎 ...

  5. Objective-C Runtime(二)消息传递机制

    在对象上调用方法是包括Objective-C的众多语言都具备的功能.但在Objective-C中,这个术语叫『传递消息』(pass a message).『消息』有「名称」(name)或「选择子」(s ...

  6. C++标准编程:虚函数与内联

    我们曾经在讨论C++的时候,经常会问到:“虚函数能被声明为内联吗?”现在,我们几乎听不到这个问题了.现在听到的是:“你不应该使print成为内联的.声明一个虚函数为内联是错误的!” 这种说法的两个主要 ...

  7. Android适合组件化开发的路由框架:Launch

    1.概述 最近越来越不想写代码了,特别是一些重复性的代码,比如由于每次启动一个 Activity,我们都会很习惯的在 Activity 中写下: public static void launch(A ...

  8. 【转】IntelliJ IDEA2017.3激活

    原文地址:https://blog.csdn.net/qq_27686779/article/details/78870816 http://idea.java.sx/ 简单快捷!! ———————— ...

  9. python-day-9- 进程-异步IO\

    本节内容 进程 Gevent协程 Select\Poll\Epoll异步IO与事件驱动 多进程multiprocessing multiprocessing is a package that sup ...

  10. 【197】PowerShell 通过 FTP 下载文件

    参考:使用 WGET 从FTP上下载文件 在 PowerShell 使用 wget2 工具,代码如下: wget2 ftp://user:password@192.168.14.31/1.jpg 其中 ...