Hibernate:将日期属性添加到mysql数据库,它会像前一天一样插入到数据库中

时间:2018-04-26 17:05:50

标签: mysql sql hibernate jpa spring-data-jpa

所以我插入的日期(在另一个对象内)是2018/04/26,从String解析。在我用调试保存之前我可以看到它是正确的,但是当我从数据库请求它时显示为2018/04 / 25.想知道这里发生了什么?数据库是亚马逊网络服务MySql RDS

这是我的日程表类,里面是DateActiveScheduleItems列表,里面包含一个日期属性。我正在初始化这样的日期

**Date date1=  new SimpleDateFormat("yyyy/MM/dd").parse(suppliedString)**

附表

@Entity
public class Schedule {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@ManyToOne
@JoinColumn(name = "user_id")
private User user;

@ManyToOne
@JoinColumn(name = "usergroup_id")
private UserGroup userGroup;

private String description;


private boolean master;//is this a schedule for all supervalus(true) or one supervalu(false)

@OneToMany(mappedBy = "schedule",cascade = CascadeType.ALL)
private List<DateActiveScheduleItem> dateActiveScheduleItems = new ArrayList<>();

@OneToMany(mappedBy = "schedule",cascade = CascadeType.PERSIST)
private List<MusicScheduleItem> musicScheduleItems = new ArrayList<>();

@OneToMany(mappedBy = "schedule",cascade = CascadeType.PERSIST)
private List<AdvertisementScheduleItem> advertisementScheduleItems = new ArrayList<>();

@Basic
@Temporal(TemporalType.DATE)
private java.util.Date dateAdded;}

DateActiveScheduleItem

@Entity
public class DateActiveScheduleItem {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Basic
@Temporal(TemporalType.DATE)
private Date date;



@JsonIgnore
@ManyToOne
@JoinColumn(name = "schedule_id")
private Schedule schedule;}

我使用hibernate CrudRepository中的.save()方法保存对象。

奇怪的是,&#34;日期已添加&#34;在我的日程安排中的财产,我将成为&#34;现在&#34;正确插入,我初始化略有不同。也许我可以尝试用这种方式初始化dateactiveitem的日期,但不确定如何?

        Calendar now = Calendar.getInstance();
    schedule.setDateAdded(now.getTime());

1 个答案:

答案 0 :(得分:2)

可能是服务器时区? 检查下面的线程 - 他有同样的问题。

Joda Time - Hibernate inserts yesterday's date into database