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 '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
項目搭建
代碼
配置文件
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
服務器更新,再次發送請求
數據庫結果
成功~
以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。
推薦閱讀:
- 解決netty中spring對象註入失敗的問題
- SpringBoot中的main方法註入service
- SpringBoot項目如何將Bean註入到普通類中
- 基於Spring上下文工具類 ApplicationContextUtil
- Springboot如何獲取上下文ApplicationContext