我有一个映射的Hibernate实体,它的一个属性是我使用AttributeConverter接口创建的枚举。
它适用于大多数情况,但如果我在“IN”子句中使用它它不起作用,这是代码:
@Converter(autoApply=true)
public class BankInvestmentStateConverter implements
AttributeConverter<BankInvestmentState, Character> {
public enum BankInvestmentState {
ON_GOING('O'),
WITHDRAW('W'),
ENDED('E'),
COLLECTED('C');
...
.....
}
@Override
public Character convertToDatabaseColumn(BankInvestmentState state) {
....
}
@Override
public BankInvestmentState convertToEntityAttribute(Character dbData) {
return ....
}
}
实体:
@Entity
@Table(name = "user_transaction_bank")
public class UserTransactionBank implements Serializable {
..
..
@Column(name = "state")
@Convert(converter = BankInvestmentStateConverter.class)
private BankInvestmentState state;
..
..
}
Hibernate查询:
UserTransactionBank transaction = (UserTransactionBank)session.createQuery(
"FROM UserTransactionBank WHERE userId=:user_id AND state IN (:statesList)")
.setLong("user_id", user_id)
.setParameterList("statesList", new Character[] { BankInvestmentState.ON_GOING.toChar(), BankInvestmentState.ENDED.toChar() })
.uniqueResult();
例外:
原因:
java.lang.ClassCastException: java.lang.Character cannot be cast to com.shareddata.helper.BankInvestmentStateConverter$BankInvestmentState
消息:
javax.persistence.PersistenceException: Error attempting to apply AttributeConverter
为什么会发生这种情况? 顺便说一句,如果不是使用.setParameterList(...),我只需硬编码IN(..)就可以了。
谢谢!