programing

JPA를 사용하여 LocalDate를 유지하는 방법

instargram 2023. 3. 18. 08:15
반응형

JPA를 사용하여 LocalDate를 유지하는 방법

Date without time을 데이터베이스에 저장하려고 합니다.그래서, 나는 그것을 사용하는 것을 택했다.LocalDate유형.

기사에서 설명한 바와 같이 JPA 컨버터를 사용하여 변환합니다.LocalDate로.Date.

그러나 엔티티를 유지하고 싶을 때(POST 및 PUT 요청으로) 문제가 있습니다.

에러

2019-02-23 11:26:30.254  WARN 2720 --- [-auto-1-exec-10] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Expected array or string.; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Expected array or string.
 at [Source: (PushbackInputStream); line: 1, column: 104] (through reference chain: ...entity.MyObject["startdate"])]

org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class org.springframework.http.ResponseEntity]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `org.springframework.http.ResponseEntity` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
 at [Source: (PushbackInputStream); line: 1, column: 2]

코드

컨버터

package ...entity;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.time.LocalDate;
import java.sql.Date;

@Converter(autoApply = true)
public class LocalDateAttributeConverter implements AttributeConverter<LocalDate, Date> {

    @Override
    public Date convertToDatabaseColumn(LocalDate locDate) {
        return (locDate == null ? null : Date.valueOf(locDate));
    }

    @Override
    public LocalDate convertToEntityAttribute(Date sqlDate) {
        return (sqlDate == null ? null : sqlDate.toLocalDate());
    }
}

독립체

package ...entity;

import org.hibernate.annotations.ColumnDefault;

import javax.persistence.*;
import java.time.LocalDate;
import java.util.HashSet;
import java.util.Set;

@Entity
public class MyObject {

    @Id
    private String id;
    private LocalDate startdate;
    private LocalDate enddate;

    public MyObject() {}

    public MyObject(LocalDate enddate) {
        this.startdate = LocalDate.now();
        this.enddate = enddate;
    }

    ...
}

'메인"

private DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
MyObject myobject = new MyObject(LocalDate.parse("2019-03-01", formatter));

도와주셔서 감사합니다.

편집 1 : My Object 인쇄

 HttpHeaders headers = new HttpHeaders();
 headers.setContentType(MediaType.APPLICATION_JSON);
 HttpEntity<String> entity = new HttpEntity<>(this.toJsonString(myObject), headers);
 System.out.println(entity.toString());

 // <{"id":"ba6649e4-6e65-4f54-8f1a-f8fc7143b05a","startdate":{"year":2019,"month":"FEBRUARY","dayOfMonth":23,"dayOfWeek":"SATURDAY","era":"CE","dayOfYear":54,"leapYear":false,"monthValue":2,"chronology":{"id":"ISO","calendarType":"iso8601"}},"enddate":{"year":2019,"month":"MARCH","dayOfMonth":1,"dayOfWeek":"FRIDAY","era":"CE","dayOfYear":60,"leapYear":false,"monthValue":3,"chronology":{"id":"ISO","calendarType":"iso8601"}}},[Content-Type:"application/json"]>

JPA 2.2에서는 컨버터를 사용할 필요가 없어지고 다음 java.time 유형의 매핑 지원이 추가되었습니다.

java.time.LocalDate
java.time.LocalTime
java.time.LocalDateTime
java.time.OffsetTime
java.time.OffsetDateTime
@Column(columnDefinition = "DATE")
private LocalDate date;
@Column(columnDefinition = "TIMESTAMP")
private LocalDateTime dateTime;
@Column(columnDefinition = "TIME")
private LocalTime localTime;

JPA 2.2 지원LocalDate변환기는 필요 없습니다.

또한 5.3 버전에서는 휴지 상태도 지원됩니다.

상세한 것에 대하여는, 이 기사를 봐 주세요.

hibernate 5는 Java 8을 지원하므로 pom.xml에 추가할 수 있습니다.

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

그러면 다음 항목에 대한 매핑이 제공됩니다.LocalDate그리고.LocalDateTime개봉 후

JPA 2.2에서는 Java 8 Date/Time API 매핑 지원이 추가되었습니다.LocalDate,LocalTime,LocalDateTime,OffsetDateTime또는OffsetTime.

예를 들어 다음과 같은 엔티티가 있다고 가정합니다.

@Entity(name = "UserAccount")
@Table(name = "user_account")
public class UserAccount {

    @Id
    private Long id;

    @Column(name = "first_name", length = 50)
    private String firstName;

    @Column(name = "last_name", length = 50)
    private String lastName;

    @Column(name = "subscribed_on")
    private LocalDate subscribedOn;

    //Getters and setters omitted for brevity
}

주의:subscribedOnattribute는LocalDateJava 오브젝트

지속할 때UserAccount:

UserAccount user = new UserAccount()
    .setId(1L)
    .setFirstName("Vlad")
    .setLastName("Mihalcea")
    .setSubscribedOn(
        LocalDate.of(
            2013, 9, 29
        )
    );

entityManager.persist(user);

휴지 상태에서는 적절한 SQL INSERT 문이 생성됩니다.

INSERT INTO user_account (
    first_name, 
    last_name, 
    subscribed_on, 
    id
) 
VALUES (
    'Vlad', 
    'Mihalcea', 
    '2013-09-29', 
    1
)

를 취득할 때UserAccount엔티티, 우리는 볼 수 있습니다.LocalDate데이터베이스로부터 올바르게 취득되고 있다.

UserAccount userAccount = entityManager.find(
    UserAccount.class, 1L
);

assertEquals(
    LocalDate.of(
        2013, 9, 29
    ),
    userAccount.getSubscribedOn()
);

직접 Converter를 작성할 수 있습니다. Spring Data JPA - 문자열에서 날짜/또는 시간을 변환할 때 변환에 실패했습니다.

언급URL : https://stackoverflow.com/questions/54840769/how-to-persist-localdate-with-jpa

반응형