The insert method in SpringDataJPA is written like insertSelective in MyBatis?

[actual phenomenon]
long-term use of MyBatis, tools using Mybatis (Mybatis Generator/ generic Mapper), can have methods like insertSelective (E).

is actually mapped as follows: SQL (many fields have default values, but only part of the value is needed for insert)

CREATE TABLE  `TABLENAME` (
`id`  bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT "PRIMARY KEY" ,

name VARCHAR(1000) NOT NULL ,

`deleted`  tinyint UNSIGNED NOT NULL DEFAULT 0 COMMENT "" ,
`create_time`  datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT "" ,
`update_time`  datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT "" ,

PRIMARY KEY (`id`),
) ENGINE=InnoDB DEFAULT CHARACTER SET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT="TABLENAME";



(spring data )
INSERT INTO tablename (name) VALUES("NAME1");

but when spring data calls insert (E), it needs to assign all non-NULL attributes of E (such as create_time, here, but I don"t care, because the database has already processed it)

[expected phenomenon & what am I going to do]

  • wants spring data, to provide only part of the value when it comes to insert (E) data. (specifically, there is the insertSelective method in mybatis)
  • When
  • insert, the generated sql language only deals with non-null values in my entities, not null values

[Code]

SQL


Entity
public class Person {
    private Long id;
    private String name;
    
    private Boolean deleted;
    private Date createTime;
    private Date updateTime;
    
}


Repository
public interface IPersonRepository extends JpaRepository<Person>{
}


Service
public class PersonService {
    public void insert() {
        final Person p = new Person();
        p.setName("name1");
        this.personRepository.insert(p);   // 
    }
}

[context (important context)] & & [scenario]

  • mysql 5.7 server
  • spring boot 1.5
  • spring data jpa
  • @ Repository

[try to solve & my guess]

  • google search

@Column(insertable=false)
private Date createTime;

, , 
Sep.27,2021
Menu