gpt4 book ai didi

java - @Converter(autoApply = true) 不工作

转载 作者:塔克拉玛干 更新时间:2023-11-01 23:04:37 25 4
gpt4 key购买 nike

@Converter 即使添加了 autoApply = true 也不会应用。当 @Convert 添加到字段本身时有效。

这是Converter的代码

package com.example.hibernate.model;

@Converter(autoApply = true)
public class HeightConverter implements AttributeConverter<Height, Integer> {
public Integer convertToDatabaseColumn(Height height) {//convert}
public Height convertToEntityAttribute(Integer dbData) {//convert}
}

使用 Height 的类

package com.example.hibernate.model;

@Entity
@Table(name = "student")
public class Student implements Serializable {
@Id
@GeneratedValue(generator = "MY_S")
private int id;

// works if @Convert is applied
// @Convert( converter = HeightConverter.class, disableConversion = false )

@Column(name = "height_in_cm")
private Height height;

//getter setter

}

我正在使用 JPA 2.1(Hibernate 5.2.6.FINAL)

编辑:

persistence.xml

<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">

<persistence-unit name="persistence" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

<mapping-file>META-INF/orm.xml</mapping-file>
<class>com.example.hibernate.model.Student</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>

<properties>
<property name="packagesToScan" value="com.example.hibernate.model" />
<property name="hibernate.archive.autodetection" value="class" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/test_db1?useSSL=false" />
<property name="hibernate.connection.username" value="root" />
<property name="hibernate.connection.password" value="password" />
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.flushMode" value="FLUSH_AUTO" />
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
</properties>

</persistence-unit>
</persistence>

最佳答案

您需要确保带@Converter 注解的类是扫描包的一部分。这为我们解决了问题。

 public LocalContainerEntityManagerFactoryBean entityManager(DataSource dataSource) {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setPackagesToScan("your.converter.package","your.entities.package");
...

在我们的案例中,由于某些原因必须以编程方式进行 em 配置,但也可以通过其他方式实现。

关于java - @Converter(autoApply = true) 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42374051/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com