Kiemoon
Kiemoon

Reputation: 57

Updating object's LocalDate attribute with query. Parameter value did not match expected type [java.time.LocalDate (n/a)]

Vaadin + Spring + MySQL

I try to update my object's LocalDate attribute via query with java.time.LocalDate attribute converted to java.sql.Date

Entity:

import java.time.LocalDate;

@Entity
@Table(name = "ENTERPRISES")
public class Enterprise {

    int enterpriseId;
    String name;
    LocalDate expiryDate;

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

    @Id
    @GeneratedValue
    @NotNull
    @Column(unique = true)
    public int getEnterpriseId() {
        return enterpriseId;
    }
    @Column
    public String getName() { return name; }

    @Column
    public LocalDate getExpiryDate() {
        return expiryDate;
    }

    public void setEnterpriseId(int enterpriseId) {
        this.enterpriseId = enterpriseId;
    }

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

    public void setExpiryDate(LocalDate expiryDate) {
        this.expiryDate = expiryDate;
    }
}

Service layer:


import java.sql.Date;
import java.time.LocalDate;

@Service
public class EnterpriseService {

    private static EnterpriseService enterpriseService;
    private EnterpriseDao enterpriseDao;

    public EnterpriseService(EnterpriseDao enterpriseDao) {
        this.enterpriseDao = enterpriseDao;
    }

    public void updateExpiryDate(int enterpriseId, LocalDate newExpiryDate) {
        Date expiryDate = Date.valueOf(newExpiryDate);
        enterpriseDao.updateExpiryDate(enterpriseId, expiryDate);
    }

}

repository layer:


import java.sql.Date;
import java.time.LocalDate;

public interface EnterpriseDao extends CrudRepository<Enterprise, Integer> {

    @Modifying
    @Query("update Enterprise e set e.expiryDate = :expiryDate where e.enterpriseId = :enterpriseId")
    void updateExpiryDate(@Param(value = "enterpriseId") int enterpriseId, @Param(value = "expiryDate") Date expiryDate);

}

When I try to call method in my application:

enterpriseService.updateExpiryDate(enterpriseX.getEnterpriseId(), LocalDate.of(2022, 12, 12));

I get exception:

Caused by: org.springframework.dao.InvalidDataAccessApiUsageException: Parameter value [2022-12-12] did not match expected type [java.time.LocalDate (n/a)]; nested exception is java.lang.IllegalArgumentException: Parameter value [2022-12-12] did not match expected type [java.time.LocalDate (n/a)]

I tried changing date types in DAO method to LocalDate but with no success

Upvotes: 0

Views: 378

Answers (1)

Pierre Demeestere
Pierre Demeestere

Reputation: 406

Since the attribute expiryDate on your Enterprise entity is a java.time.LocalDate, the parameter :expiryDate in the query must be a java.time.LocalDate. Therefore, you should change the parameter expiryDate of updateExpiryDate().

Upvotes: 2

Related Questions