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

本文介绍了在Spring Boot JPA中如何处理带有默认值和非空约束的数据库字段。当尝试保存不完整对象时,如果不使用@DynamicUpdate和@DynamicInsert,会导致SQLIntegrityConstraintViolationException异常。通过在实体类上添加这两个注解,JPA可以根据对象属性动态生成更新和插入语句,允许使用数据库默认值。
摘要由CSDN通过智能技术生成

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

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

建库建表

CREATE TABLE`student` (

`id`bigint(20) NOT NULLAUTO_INCREMENT,

`name`varchar(255) NOT NULL COMMENT '姓名',

`age`int(3) NOT NULL DEFAULT '0' COMMENT '年龄',

`adder`varchar(255) NOT NULL DEFAULT '北京' COMMENT '地址',

`class`int(15) NOT NULL DEFAULT '0' COMMENT '班级',

`is_ali`tinyint(1) NOT NULL DEFAULT '0' COMMENT '阿里认证',

`is_tx`tinyint(1) NOT NULL DEFAULT '0' COMMENT '腾讯认证',PRIMARY KEY(`id`)

) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8

项目搭建

93ac3d8a5a710587ca27c461580b1e6d.png

代码

配置文件

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

packagecom.myjpa.demo.controller;importcom.myjpa.demo.service.StudentService;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.web.bind.annotation.PutMapping;importorg.springframework.web.bind.annotation.RestController;

@RestControllerpublic classStudnetController {

@Autowired

StudentService student;

@PutMapping("/add")publicString insertStudent(String name, Integer age) {

student.addStudent(name, age);return "添加成功";

}

}

StudentService

packagecom.myjpa.demo.service;importcom.myjpa.demo.entity.StudentEntity;importcom.myjpa.demo.respository.StudentRespository;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Service;importorg.springframework.transaction.annotation.Transactional;

@Service

@Transactional(rollbackFor= Exception.class)public classStudentService {

@Autowired

StudentRespository studentRespository;public voidaddStudent(String name, Integer age) {

StudentEntity s= newStudentEntity();

s.setName(name);

s.setAge(age);

studentRespository.save(s);

}

}

StudentRespository

packagecom.myjpa.demo.respository;importcom.myjpa.demo.entity.StudentEntity;importorg.springframework.data.jpa.repository.JpaRepository;importorg.springframework.stereotype.Repository;

@Repositorypublic interface StudentRespository extends JpaRepository{

}

StudentEntity 实体类可以使用idea反向生成

packagecom.myjpa.demo.entity;importorg.hibernate.annotations.DynamicInsert;importorg.hibernate.annotations.DynamicUpdate;import javax.persistence.*;importjava.util.Objects;

@Entity

@Table(name= "student", schema = "test")public classStudentEntity {private longid;privateString name;private intage;privateString adder;private intclazz;private byteisAli;private byteisTx;

@Id

@Column(name= "id")public longgetId() {returnid;

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

}

@Basic

@Column(name= "name")publicString getName() {returnname;

}public voidsetName(String name) {this.name =name;

}

@Basic

@Column(name= "age")public intgetAge() {returnage;

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

}

@Basic

@Column(name= "adder")publicString getAdder() {returnadder;

}public voidsetAdder(String adder) {this.adder =adder;

}

@Basic

@Column(name= "class")public intgetClazz() {returnclazz;

}public void setClazz(intclazz) {this.clazz =clazz;

}

@Basic

@Column(name= "is_ali")public bytegetIsAli() {returnisAli;

}public void setIsAli(byteisAli) {this.isAli =isAli;

}

@Basic

@Column(name= "is_tx")public bytegetIsTx() {returnisTx;

}public void setIsTx(byteisTx) {this.isTx =isTx;

}

@Overridepublic booleanequals(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);

}

@Overridepublic inthashCode() {returnObjects.hash(id, name, age, adder, clazz, isAli, isTx);

}

}

DemoApplication

packagecom.myjpa.demo;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplicationpublic classDemoApplication {public static voidmain(String[] args) {

SpringApplication.run(DemoApplication.class, args);

}

}

错误测试

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

发送请求

7a951ce2880df94f28dbd73ecc0c84d0.png

服务器错误

c36c4e6dc0f8bd5868b09de40cc3ef29.png

解决问题

修改StudentEntity添加两个注解

@DynamicUpdate

@DynamicInsert

8f703ff497d666ba1e1e4f9ec0580686.png

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

6e8c98757393cdada1105a2b9c0fea93.png

30a38e2403d2cfcf2fb1734bae805305.png

数据库结果

1436c3b9d33ae0519fbb3c2293183aad.png

成功

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值