gpt4 book ai didi

java - 如果将自定义查询与 JOIN 结合使用,则 Hibernate AttributeConverter 会失败

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:48:02 27 4
gpt4 key购买 nike

我在 hibernate jpa 2.1 中发现了一个非常有趣的错误。当我在存储库中编写自定义查询实现并在查询中同时使用自定义 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.RELEASEspring-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

关于java - 如果将自定义查询与 JOIN 结合使用,则 Hibernate AttributeConverter 会失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48990263/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com