[英]Hibernate AttributeConverter fails if using custom query with JOIN
我在hibernate jpa 2.1中發現了非常有趣的bug。 當我在存儲庫中編寫自定義查詢實現並在查詢中使用自定義AttributeConverter和JOIN時,AttributeConverter不起作用。 我確定,JOIN導致了這個問題,但我不知道如何解決它。 沒有JOIN AttributeConverter在查詢中工作正常。 我發現了一個丑陋的解決方案(你可以在我的代碼中看到它),但我正在尋找合適的解決方案。
因此,如果使用JOIN進行查詢
SELECT t FROM TaskEntity t JOIN t.involvedUsers u WHERE status in :statuses AND u.id IN :involvedUserIds ORDER BY t.id DESC
查詢參數:
statuses = [CREATED, APPROVED, IN_PROGRESS];
involvedUserIds = [1, 2];
我收到以下錯誤:
2018-02-26 15:39:36.458 DEBUG 2482 --- [nio-8008-exec-1] org.hibernate.SQL : select taskentity0_.id as id1_11_, taskentity0_.amount as amount2_11_, taskentity0_.comment as comment3_11_, taskentity0_.commission as commissi4_11_, taskentity0_.created as created5_11_, taskentity0_.currency as currency6_11_, taskentity0_.current_account_id as current14_11_, taskentity0_.current_object_id as current15_11_, taskentity0_.current_user_id as current16_11_, taskentity0_.description as descript7_11_, taskentity0_.data as data8_11_, taskentity0_.initiator_account_id as initiat17_11_, taskentity0_.initiator_object_id as initiat18_11_, taskentity0_.initiator_user_id as initiat19_11_, taskentity0_.payment_method as payment_9_11_, taskentity0_.status as status10_11_, taskentity0_.title as title11_11_, taskentity0_.updated as updated12_11_, taskentity0_.version as version13_11_ from public.tasks taskentity0_ inner join public.tasks_users involvedus1_ on taskentity0_.id=involvedus1_.task_id inner join public.users userentity2_ on involvedus1_.user_id=userentity2_.id where (status in (? , ? , ?)) and (userentity2_.id in (? , ?)) order by taskentity0_.id DESC limit ?
2018-02-26 15:39:36.459 TRACE 2482 --- [nio-8008-exec-1] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [VARBINARY] - [CREATED]
2018-02-26 15:39:36.460 TRACE 2482 --- [nio-8008-exec-1] o.h.type.descriptor.sql.BasicBinder : binding parameter [2] as [VARBINARY] - [APPROVED]
2018-02-26 15:39:36.460 TRACE 2482 --- [nio-8008-exec-1] o.h.type.descriptor.sql.BasicBinder : binding parameter [3] as [VARBINARY] - [IN_PROGRESS]
2018-02-26 15:39:36.460 TRACE 2482 --- [nio-8008-exec-1] o.h.type.descriptor.sql.BasicBinder : binding parameter [4] as [INTEGER] - [1]
2018-02-26 15:39:36.461 TRACE 2482 --- [nio-8008-exec-1] o.h.type.descriptor.sql.BasicBinder : binding parameter [5] as [INTEGER] - [2]
org.postgresql.util.PSQLException: ERROR: operator does not exist: integer = bytea
No operator matches the given name and argument type(s). You might need to add explicit type casts.
代碼如下:
@Repository
public class TaskRepositoryImpl implements CustomTaskRepository {
private final EntityManager em;
@Autowired
public TaskRepositoryImpl(JpaContext context) {
this.em = context.getEntityManagerByManagedType(TaskEntity.class);
}
public List<TaskEntity> find(List<TaskStatuses> statuses, List<Integer> involvedUserIds) {
Map<String, Object> params = new HashMap<>();
StringBuilder queryStr = new StringBuilder("SELECT t FROM TaskEntity t WHERE");
if (statuses != null && !statuses.isEmpty()) {
queryStr.append(" status in :statuses AND");
params.put("statuses", involvedUserIds == null ? statuses :
statuses.stream().map(TaskStatuses::getId).collect(Collectors.toList())); //problem is here
}
if (involvedUserIds != null && !involvedUserIds.isEmpty()) {
queryStr.insert(queryStr.indexOf("WHERE"), "JOIN t.involvedUsers u "); //this join causes the problem
queryStr.append(" u.id IN :involvedUserIds AND");
params.put("involvedUserIds", involvedUserIds);
}
if (queryStr.lastIndexOf(" WHERE") == queryStr.length() - 6)
queryStr.setLength(queryStr.length() - 6);
else
queryStr.setLength(queryStr.length() - 4);
Query query = em.createQuery(queryStr.toString());
params.forEach(query::setParameter);
query.setFirstResult(0);
query.setMaxResults(20);
return query.getResultList();
}
}
任務實體:
@Getter @Setter
@Entity
@Table(name = "tasks")
public class TaskEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String title;
private String description;
@NotNull
@Convert(converter = TaskStatusesConverter.class)
private TaskStatuses status;
@ManyToMany
@JoinTable(
name = "tasks_users",
joinColumns = @JoinColumn(name = "task_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
foreignKey = @ForeignKey(name = "none", value = ConstraintMode.NO_CONSTRAINT),
inverseForeignKey = @ForeignKey(name = "none", value = ConstraintMode.NO_CONSTRAINT))
private Set<UserEntity> involvedUsers;
}
用戶實體
@Getter @Setter
@Entity
@Table(name = "users")
public class UserEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@NotNull
@Column(unique = true)
private String email;
}
任務狀態:
public enum TaskStatuses {
CREATED(1),
APPROVED(2),
IN_PROGRESS(3),
COMPLETED(4),
REJECTED(100),
;
private Integer id;
TaskStatuses(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public static TaskStatuses valueOf(Integer id) {
for (TaskStatuses value : values())
if (value.getId().equals(id))
return value;
return null;
}
}
任務狀態轉換器:
public class TaskStatusesConverter implements AttributeConverter<TaskStatuses, Integer> {
@Override
public Integer convertToDatabaseColumn(TaskStatuses status) {
return status.getId();
}
@Override
public TaskStatuses convertToEntityAttribute(Integer status) {
return TaskStatuses.valueOf(status);
}
}
和存儲庫:
@NoRepositoryBean
public interface CustomTaskRepository {
List<TaskEntity> find(List<TaskStatuses> statuses, List<Integer> involvedUserIds)
}
在這個項目中,我使用的是spring-boot 1.5.8.RELEASE
和spring-data-jpa 1.5.8.RELEASE
。 項目簡化的代碼,僅包含此示例所需的信息(您可以在日志中看到一些冗余信息)。 謝謝你的幫助。
試試這個:
select t from TaskEntity t where t.status in (:statuses) and t.involvedUsers.id in (:involvedUserIds) order by t.id DESC
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.