0

I'm using dropwizard 0.9.3 to create a simple REST API over MySQL (with Hibernate and Jackson - using Java 8).

I'm hitting a problem when trying to save a UTC DateTime value into a MySQL timestamp column from the application layer - while the application seems to handle it well, the value appearing in the db is a BLOB, so I'm guessing somewhere along the way the serializing the values correctly.

My Entity looks like this:

@Entity
@Table(name = "users")
public class User {

    @Id @NotNull @JsonProperty
    private String id;

    @JsonProperty @NotNull
    @Column(name="name", nullable=false)
    private String name;

    @JsonProperty @NotNull
    @Column(name="email", nullable=false)
    private String email;

    @JsonIgnore @JsonProperty @NotNull
    @Column(name="createdAt", nullable = false)
    private ZonedDateTime createdAt;

    // default constructor
    public User() {}

    public User(String name, String email) {
        this.name = name;
        this.email = email;

        // get the current UTC timestamp
        this.createdAt = ZonedDateTime.now(ZoneOffset.UTC);
    }

}

The corresponding DAO is:

public class UserDAO extends AbstractDAO<User> {

    public UserDAO(SessionFactory factory) {
        super(factory);
    }

    public User create(User user) {
        return persist(user);
    }
}

And the Resource is:

@Path("/users")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class UsersResource {

    private final UserDAO dao;

    public UsersResource(UserDAO dao) {
        this.dao = dao;
    }

    @PUT
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    @UnitOfWork
    public User create(
        @FormParam("name") String firstName,
        @FormParam("email") String email
    ) {
        User user = new User(name, email);
        return dao.create(user);
    }
}

Testing it with a simple curl works, but a BLOB is saved to the DB where the timestamp should be (e.g display a value like 2016-06-28 10:05:22).

I tried to follow the DW conventions, using a fairly conventional bootstrap (and the dropwizard-java8 bundle). I'm not sure what I've missed here, but I'm also new to DW and Java in general.

Suggestions are appreciated - thanks.

sa125
  • 28,121
  • 38
  • 111
  • 153

1 Answers1

0

DW is using hibernate 5+

For Hibernate to support java time types, you need to inlcude this dependency: (replace with the specific version)

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-java8</artifactId>
    <version>5.0.0.Final</version>
</dependency>

Note: this won't save to timestamp type though. Testing with MySQL, it saves to datetime type.

(took this from: Java 8 LocalDateTime and Hibernate 4)

Regards,

artur

Community
  • 1
  • 1
pandaadb
  • 6,306
  • 2
  • 22
  • 41