Как использовать конвертер? - PullRequest
0 голосов
/ 27 марта 2020

в моем коде я хочу t

я использую формат LocalDataTime likethis:

@Entity
@Table(name="meals")
public class Meal {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Integer id;

    @Column(name = "date_time")
    @Convert(converter = MealConverter.class)
    private LocalDateTime datetime;

    @Column(name = "description")
    private String description;

    @Column(name = "calories")
    private int calories;

    public Meal() {
    }

    public Meal(int id) {
        this.id = id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public LocalDateTime getDatetime() {
        return datetime;
    }

    public void setDatetime(LocalDateTime datetime) {
        this.datetime = datetime;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public int getCalories() {
        return calories;
    }

    public void setCalories(int calories) {
        this.calories = calories;
    }

    public boolean isNew() {
        return this.id == null;
    }
}

в xml я использую это:

    <context:property-placeholder location="classpath:db/postgres.properties"/>

    <bean id="myDataSource"
          class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${database.driverClassName}"/>
        <property name="url" value="${database.url}"/>
        <property name="username" value="${database.username}"/>
        <property name="password" value="${database.password}"/>
    </bean>

    <bean id="entityManagerFactory"
          class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="packagesToScan" value="ru.demo.exercise.models"/>
        <property name="dataSource" ref="myDataSource"/>

        <property name="jpaProperties">
            <props>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQL9Dialect</prop>
            </props>
        </property>

        <property name="persistenceProvider">
            <bean class="org.hibernate.jpa.HibernatePersistenceProvider"/>
        </property>
    </bean>

    <bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>

    <jpa:repositories base-package="ru.demo.exercise.repository" entity-manager-factory-ref="entityManagerFactory"/>

    <tx:annotation-driven/>
</beans>

ошибка в журнале :

Ошибка поля в объекте 'foodsCreate' в поле 'datetime': отклоненное значение [2020-05-11T11: 08]; коды [typeMismatch.mealsCreate.datetime, typeMismatch.datetime, typeMismatch. java .time.LocalDateTime, typeMismatch]; аргументы [org.springframework.context.support.DefaultMessageSourceResolvable: codes [foodsCreate.datetime, datetime]; аргументы []; сообщение по умолчанию [datetime]]; сообщение по умолчанию [Не удалось преобразовать значение свойства типа 'java .lang.String' в требуемый тип 'java .time.LocalDateTime' для свойства 'datetime'; вложенное исключение: java .lang.IllegalStateException: невозможно преобразовать значение типа 'java .lang.String' в требуемый тип 'java .time.LocalDateTime' для свойства datetime: не найдено подходящих редакторов или стратегии преобразования ]]

мой конвертер:

@Converter(autoApply = true)
public class Converter implements AttributeConverter<Meal, String> {

private static final String SEPARATOR = ", ";

@Override
public String convertToDatabaseColumn(Meal meal) {
    if (meal == null) {
        return null;
    }

    StringBuilder sb = new StringBuilder();
    if (meal.getDatetime() != null) {
        sb.append(meal.getDatetime());
        sb.append(SEPARATOR);
    }

    if (meal.getDescription() != null
            && !meal.getDescription().isEmpty()) {
        sb.append(meal.getDescription());
    }

    return sb.toString();
}

@Override
public Meal convertToEntityAttribute(String dbPersonName) {
    if (dbPersonName == null || dbPersonName.isEmpty()) {
        return null;
    }

    String[] pieces = dbPersonName.split(SEPARATOR);

    if (pieces == null || pieces.length == 0) {
        return null;
    }

    Meal meal = new Meal();
    String firstPiece = !pieces[0].isEmpty() ? pieces[0] : null;
    if (dbPersonName.contains(SEPARATOR)) {
        meal.getDescription();

        if (pieces.length >= 2 && pieces[1] != null
                && !pieces[1].isEmpty()) {
            meal.setDescription(pieces[1]);
        }
    } else {
        meal.setDescription(firstPiece);
    }

    return meal;
}

}

и моя модель:

@Entity
@Table(name="meals")
public class Meal {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Integer id;

    @Column(name = "date_time")
    @Convert(converter = MealConverter.class)
    private LocalDateTime datetime;

    @Column(name = "description")
    private String description;

    @Column(name = "calories")
    private int calories;

    public Meal() {
    }

    public Meal(int id) {
        this.id = id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public LocalDateTime getDatetime() {
        return datetime;
    }

    public void setDatetime(LocalDateTime datetime) {
        this.datetime = datetime;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public int getCalories() {
        return calories;
    }

    public void setCalories(int calories) {
        this.calories = calories;
    }

}

моя jsp форма:

<html>
<head>
    <title></title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body>

<div class="container">
    <h2><a href="${pageContext.request.contextPath}/list">Home</a></h2>
    <h2 align="center"></h2>

    <div id="row">
        <%--@elvariable id="mealsCreate" type=""--%>
        <form:form action="${pageContext.request.contextPath}/create"
                   modelAttribute="mealsCreate" method="post">
            <div class="col-md-9">
                <input type="hidden"/>

                <div class="form-group">
                    <div class="col-md-12">
                        <label for="dateTime">DateTime</label>
                        <input id="dateTime" type="datetime-local" name="datetime"/>
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-md-12">
                        <label for="description" type="table" class="table">Description</label>
                        <input id="description" type="text" name="description"/>
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-md-12">
                        <label for="calories" type="table" class="table">Calories</label>
                        <input id="calories" type="number" name="calories"/>
                    </div>
                </div>

                <button type="submit" class="btn btn-default" name="saveMeals">Save</button>
                <button type="button" class="btn btn-default" name="cancelMeals" onclick="window.history.back()">
                    Cancel
                </button>

            </div>
        </form:form>
    </div>
</div>
</body>

Что не так в моем коде?

1 Ответ

0 голосов
/ 27 марта 2020

Вам необходимо реализовать конвертер в соответствии с типом свойства, а не типом вашей модели. В вашем случае LocalDateTime:

@Converter(autoApply = true)
public class LocalDateTimeConverter implements AttributeConverter<LocalDateTime, String> {

    @Override
    public String convertToDatabaseColumn(LocalDateTime localDateTime) {
        // code to convert from localDateTime to String
    }

    @Override
    public Meal convertToEntityAttribute(String stringDateTime) {
        // code to convert from  String to localDateTime
    }
}

Затем вам нужно применить этот конвертер к свойству:

public class Meal {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Integer id;

    @Column(name = "date_time")
    @Convert(converter = LocalDateTimeConverte.class)
    private LocalDateTime datetime;
    //(...)
}
...