2017-03-28 53 views
1

我已經定義了一個具有「java.util.UUID」作爲其「Id」字段的域類。將UUID作爲字段映射到mysql數據庫中錯誤的列類型

@Entity 
class Response{ 
@Id 
@GeneratedValue(generator = "myUUIDGenerator") 
@GenericGenerator(name = "myUUIDGenerator", strategy = "uuid2") 
@Column(columnDefinition = "uuid") 
private UUID id; 
... 
} 

我正在使用liquibase來生成數據庫。

<createTable tableName="response"> 
    <column name="id" type="uuid"> 
     <constraints primaryKey="true" nullable="false"/> 
    </column> 
</createTable> 

MySQL中生成的表將生成的id列描述爲「char(36)」。

運行測試用例時發生問題。它表示以下並沒有執行任何測試用例。

Wrong column type in DBNAME_response for column id. Found: char, expected: uuid 

回答

0

在你Response類要定義的id場爲UUID類型,但MySQL沒有原生UUID類型,所以它聲明列char(36)。你可能需要做的是改變它,使該字段爲String,然後提供執行轉換String <-> UUID的getter和setter方法。

0

爲更新到新庫, 隨着JPA2.1你不應該去SteveDonie的路線 -

聲明一個屬性轉換器:

@Converter() 
public class UUIDAttributeConverter implements AttributeConverter<UUID, String>, Serializable { 

    @Override 
    public String convertToDatabaseColumn(UUID locDate) { 
     return (locDate == null ? null : locDate.toString()); 
    } 

    @Override 
    public UUID convertToEntityAttribute(String sqlDate) { 
     return (sqlDate == null ? null : UUID.fromString(sqlDate)); 
    } 

} 

馬克持久性單元作爲應用的轉換器(如果在persistence.xml中

<class>UUIDAttributeConverter</class> 

不是自動應用)適用於場

@Id 
@Column(unique = true, nullable = false, length = 64) 
@Convert(converter = UUIDAttributeConverter.class) 
private UUID guid; 

這允許您指定轉換應該只發生在某些持久性單元(如MySql)中,而不是在其他堅持的單元中發生。它還正確地將項目映射到db並保持對象類型安全。

希望這會有所幫助!

相關問題