2017-02-21 1029 views
1

@Converter即使在添加autoApply = true時也不適用。當@Convert被添加到字段本身時工作。@Converter(autoApply = true)不起作用

下面是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.1Hibernate 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> 

回答

2

我覺得你必須提到在實體映射的轉換器自動適用於工作。

<?xml version="1.0"?> 
<entity-mappings> 
    <converter class="com.example.hibernate.model.HeightConverter" auto-apply="true"/> 
</entity-mappings> 
+0

我們如何避免XML?我們能自動掃描轉換器嗎? –

+0

應該沒有xml的工作...但我會試試看 – tom

+0

添加了snippets @ orm.xml,它的工作原理..但我試圖用註釋來完成這個工作。我錯過了什麼嗎? –

2

既然我已經添加註釋@Converter類這足以補充<class>com.example.hibernate.model.HeightConverter</class>persistence.xml

相關問題