user1409534
user1409534

Reputation: 2314

Date field not retrieved using JPA

I have table in mysql data base that called course that has the following columns :

And I have the following entity defined :

@Entity
@Table(name = "course")
public class Course {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@Column(name = "start_date")
@Temporal(TemporalType.DATE)
private Date startDate;

protected Course() {

}

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

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public Long getId() {
    return id;
}

public Date getStartDate() {
    return startDate;
 }

}

So the database should populate the date column. I use Spring data JPA so my dao looks like this:

public interface CourseRepository extends CrudRepository<Course, Long> {

}

I create a new Course entity (via the above constructor that accepts name):

courseRepository.save(new Course("Algebra"));

and save it to table it seems that the id columns is auto increment but the date column is null, even though it defined as default now.

Upvotes: 0

Views: 1678

Answers (3)

Sudhir Ojha
Sudhir Ojha

Reputation: 3305

This is happening because you never set startDate. Change your Course class constructor like following:

public Course(String name, Date startDate) {
    this.name = name;
    this.startDate = startDate;
}

And call save() like following:

courseRepository.save(new Course("Algebra", new Date()));

The save method get the current date of your system and save this into database.

Upvotes: 0

Deepak Jain
Deepak Jain

Reputation: 347

Please refer below example

@Column(name = "created_date")
@Temporal(TemporalType.TIMESTAMP)
@DateTimeFormat(pattern = "dd/MM/YYYY")
private Date createdDate;

Upvotes: 0

Kartik
Kartik

Reputation: 7917

Your start_date is a timestamp but you are using Date in your model.

Change

@Column(name = "start_date")
@Temporal(TemporalType.DATE)
private Date startDate;

to

@Column(name = "start_date", nullable = false, updatable = false)
@CreationTimestamp
private Timestamp startDate; //import java.sql.Timestamp;

Upvotes: 2

Related Questions