Home > Software engineering >  Spring Boot - created_at cannot be null. Spring JPA
Spring Boot - created_at cannot be null. Spring JPA

Time:10-28

Whenever I am trying to save an object to my DB, I keep getting the error Column 'created_at' cannot be null.

Here is my audit model:

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;

@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties(
        value = {"createdAt", "updatedAt"},
        allowGetters = true
)
public abstract class AuditModel implements Serializable {
    @Temporal(TemporalType.TIMESTAMP)
    @CreatedDate
    @Column(name = "created_at", nullable = false, updatable = false)
    @JsonIgnore
    private Date createdAt;

    @Temporal(TemporalType.TIMESTAMP)
    @LastModifiedDate
    @Column(name = "updated_at", nullable = false)
    private Date updatedAt;

    public Date getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(Date createdAt) {
        this.createdAt = createdAt;
    }

    public Date getUpdatedAt() {
        return updatedAt;
    }

    public void setUpdatedAt(Date updatedAt) {
        this.updatedAt = updatedAt;
    }
}

Here is an example of a model that extends it:

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.lang.Nullable;

import javax.persistence.*;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Set;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
public class Category extends AuditModel {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotEmpty(message = "Item Name is required.")
    private String categoryName;
    @NotNull
    private String categoryDescription;
    @Nullable
    @JsonIgnore
    @OneToMany(mappedBy = "category", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    private Set<Item> items;

    public Category(String categoryName, String categoryDescription) {
        this.categoryName = categoryName;
        this.categoryDescription = categoryDescription;
    }

And here is the temporary CommandLine bean that is performing some tests for me:

@Configuration
public class ItemConfig {

    @Autowired
    ItemRepository itemRepository;
    @Autowired
    CategoryRepository categoryRepository;

    @Value("${STORE.ENV}")
    private String env;

    @Bean
    CommandLineRunner itemRunner(ItemRepository itemRepository) {
        return args -> {

            System.out.println("true");
            Category cueCategory = new Category
                    ("Cues",
                     "This category contains all items relating to billiard cues. This includes yada, yadada, and yada."
                    );
            categoryRepository.save(cueCategory);

            Item item = new Item("Test Cue", 700, cueCategory);
            itemRepository.save(item);
        };
    }
}

At first, I was creating a blank object then setting all the values with setters. I thought that maybe it all needed to happen in one fel-swoop for the created_at to register with a proper date, so I added some constructors. That still didn't work. Please let me know if you see anything glaring!

CodePudding user response:

You can fix this issue by modifying your createdAt and updatedAt properties like below and also, modify your getter and setters.

@CreationTimestamp
@Column(name = "created_at", updatable = false)
private Timestamp createdAt;

@UpdateTimestamp
@Column(name = "updated_at")
private Timestamp updatedAt;

CodePudding user response:

You do explicitly set created_at column to be non-nullable with the @Column annotation, via nullable = false:

@Column(name = "created_at", nullable = false, updatable = false)
private Date createdAt;

If you want it to accept null values, just set it true or just simply drop it, because nullable is optional and the default value for it is true.

@Column(name = "created_at", updatable = false)
private Date createdAt;

CodePudding user response:

You should add @EnableJpaAuditing annotation.

import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
// ...

@Configuration
@EnableJpaAuditing
public class ItemConfig {
    // ...
}
  • Related