我有我的实体类:
@Entity
@Table(name = "TABLE")
public class User {
@Id
@Column
private UUID id;
我正在使用EcliseLink。当我尝试执行以下代码时:
em.createQuery("select t from Table").getResultList();
我有例外:
我已经尝试添加属性转换器
<converter class="com.example.UuidConverter" auto-appy="true"/>
转换器中的“技巧”在PostgreSQL中工作得很好(我需要那里属性转换器
如何处理这种情况,以便我的实体也支持MSSQL?
有一个技巧,我希望这能帮助其他有同样问题的人
步骤#1创建一个类转换器
import org.eclipse.persistence.internal.helper.DatabaseField;
import org.eclipse.persistence.mappings.DatabaseMapping;
import org.eclipse.persistence.mappings.DirectCollectionMapping;
import org.eclipse.persistence.mappings.converters.Converter;
import org.eclipse.persistence.sessions.Session;
import java.util.UUID;
public class MyUUIDConverter implements Converter {
@Override
public Object convertObjectValueToDataValue(Object o, Session session) {
return o;
}
@Override
public UUID convertDataValueToObjectValue(Object o, Session session) {
return (UUID) o;
}
@Override
public boolean isMutable() {
return true;
}
@Override
public void initialize(DatabaseMapping databaseMapping, Session session) {
final DatabaseField field;
if (databaseMapping instanceof DirectCollectionMapping) {
// handle @ElementCollection...
field = ((DirectCollectionMapping) databaseMapping).getDirectField();
} else {
field = databaseMapping.getField();
}
field.setSqlType(java.sql.Types.OTHER);
field.setTypeName("java.util.UUID");
field.setColumnDefinition("your column name in database");
}
}
步骤#2使用注释转换器来实现您最近创建的类
@Entity
@Table(name = "TABLE")
@Converter(name = "myUuidConverter", converterClass = MyUUIDConverter.class)
public class User {
Step#3 USe注释在您的物业中转换
@Convert("myUuidConverter")
private UUID id;