Ama*_*har 8 java hibernate jpa
@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}
}
Run Code Online (Sandbox Code Playgroud)
类,其中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
}
Run Code Online (Sandbox Code Playgroud)
我正在使用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>
Run Code Online (Sandbox Code Playgroud)
Rub*_*rio 10
您需要确保 @Converter 注解的类是扫描包的一部分。这为我们解决了这个问题。
public LocalContainerEntityManagerFactoryBean entityManager(DataSource dataSource) {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setPackagesToScan("your.converter.package","your.entities.package");
...
Run Code Online (Sandbox Code Playgroud)
在我们的例子中,由于某些原因,em 配置必须以编程方式进行,但也可以通过其他方式来实现。
我认为您必须在实体映射中提及转换器才能自动应用。
<?xml version="1.0"?>
<entity-mappings>
<converter class="com.example.hibernate.model.HeightConverter" auto-apply="true"/>
</entity-mappings>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8028 次 |
最近记录: |