Yuvraj
Yuvraj

Reputation: 1

Using java.sql.Timestamp in springboot for giving multiple fields for entry in Swagger instead of single field

This is my Entity class:

@Entity
@Table(name = "trade_data")
public class TradeData {
    //POJO Class- Entity Trade data
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "s_no", unique = true)
    private int s_no;
    
    @Column(name = "tradeDate")
    private java.sql.Date tradeDate = new java.sql.Date(System.currentTimeMillis());
    
    @Column(name = "effectiveDate")
    private java.sql.Date effectiveDate;
    
    @Column(name = "maturityDate")
    private java.sql.Date maturityDate;
    
    //error
    @Column(name = "creationTimeStamp", insertable = false)
    private java.sql.Timestamp CreationTimeStamp = new
            java.sql.Timestamp(System.currentTimeMillis());
    
    //error
    @Column(name = "VersionTimeStamp", nullable = false)
    private java.sql.Timestamp VersionTimeStamp = new
            java.sql.Timestamp(System.currentTimeMillis());
    
    //error
    @Column(name = "ConfirmationTimeStamp", insertable = false)
    private java.sql.Timestamp ConfirmationTimeStamp;
}

All the java.sql.Timestamp variables are giving different fields for entry for hour,minute, second, year, month, day instead of a single field in swagger and also it doesn't give pre-filled data in the field even though I'm putting current timestamp using System.currentTimemillis() . Also it should be accepting json data as I'm using @RequestBody but it shows fields to enter the data in.

Here's an image for reference: [1]: https://i.sstatic.net/T9giP.png

Upvotes: 0

Views: 521

Answers (1)

Alexander Golovnya
Alexander Golovnya

Reputation: 321

The java.sql.Date class shouldn't be exposed by REST API and Swagger. It's intended only for internal use in the application.

You may consider using the LocalDateTime type for this case. Please see the following example of the entity class below:

@Entity
@Table(name = "trade_data")
public class TradeData {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "s_no", unique = true)
    private int s_no;
    
    @Column(name = "tradeDate")
    private LocalDate tradeDate = LocalDate.now(ZoneId.systemDefault());;
    
    @Column(name = "effectiveDate")
    private LocalDate effectiveDate;
    
    @Column(name = "maturityDate")
    private LocalDate maturityDate;
}

You may also want to consider introducing a separate DTO class, which will be exposed in your Swagger and REST API instead of the entity class. There might be different opinions on using DTO classes, and it extremely depends on your configuration and use cases. In general, it's not a bad idea.

Upvotes: 1

Related Questions