当前位置: 首页 > 知识库问答 >
问题:

如何使用转换器?

穆彬郁
2023-03-14

在我的代码中,我想要

@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;
    }
}
    <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>

对象“膳食创建”中字段“日期时间”上的字段错误:拒绝值[2020-05-11T11:08];代码[TypeMismatch.MealScreate.DateTime,TypeMismatch.DateTime,TypeMismatch.java.time.LocalDateTime,TypeMismatch];参数[org.springframework.context.support.defaultmessageSourceResolvable:代码[mealscreate.datetime、datetime];参数[];default message[datetime]];默认消息[无法将“java.lang.String”类型的属性值转换为属性“DateTime”的必需类型“java.Time.LocalDateTime”;嵌套异常为java.lang.IllegalStateException:无法将“java.lang.String”类型的值转换为属性“DateTime”的必需类型“java.Time.LocalDateTime”:找不到匹配的编辑器或转换策略]]

我的转换器:

@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个答案

宋俊民
2023-03-14

您需要根据属性类型实现转换器,而不是根据您的模型的类型。在您的示例中,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;
    //(...)
}
 类似资料:
  • 尝试转换如下内容时,我为转换后的对象获取了一个空值: 对此: 这是我使用的规范: 这是我使用的代码: 我能够使用与上述相同的规范和代码成功转换以下输入: 那么,我需要做什么来转换员工对象数组呢?

  • 我想使用Spring和自定义实现来转换来自Spring XML配置的值。 配置如下所示: 转换器按预期注入方法,以便正确初始化。但是无法执行xml配置中参数的转换。错误消息为: org.springframework.beans.factory.unsatisfiedDependencyException:在通过SAX inputsource加载的资源中创建名为“A1”的bean时出错:未满足的依

  • 问题内容: 我曾经有一个可打电话的课 我曾经用来提交。如何更改使用? 以下代码无法编译 不存在变量U类型的实例,因此SampleTask符合Supplier 问题答案: 期望一个,而您给它一个。 错误消息告诉您,编译器已尝试找到用于“ 您的a”的类型,但找不到该类型。 Java将把lambda隐式“提升”到功能接口(例如或)。但是它不会将功能接口视为可互换的- 也就是说,您不能在期望的位置使用a

  • 我有一个任务:返回一个公司地图,其中键是它的名称,值是存储为String的员工列表,由和组成,用空格分隔。这是我的解决方案和它的工作罚款: 所以我的问题是,如何转换

  • 问题内容: 我在标签中嵌套了一个 内联元素 (a )。我将 转换属性 应用于(偏斜,因此看起来像平行四边形)。 我需要 将span标签转换 为“ unskew”它及其文本。但这似乎仅在IE中有效。 问题答案: 说明: A 是一个内联元素,并且 Transform属性不适用于内联元素 。 CSS转换模块1级上的可 解决方案: 将跨度的显示属性设置为或。这将使您将转换应用于span元素。 它也适用于其

  • 问题内容: 如何在Java中将十六进制颜色转换为RGB代码?在Google中,大多数示例是关于如何从RGB转换为十六进制的。 问题答案: 我想应该这样做: