简体   繁体   English

如果在JOIN中使用自定义查询,则Hibernate AttributeConverter会失败

[英]Hibernate AttributeConverter fails if using custom query with JOIN

I found very interesting bug in hibernate jpa 2.1. 我在hibernate jpa 2.1中发现了非常有趣的bug。 When I'm writing custom query implementation in a repository and using both custom AttributeConverter and JOIN in the query then AttributeConverter don't work. 当我在存储库中编写自定义查询实现并在查询中使用自定义AttributeConverter和JOIN时,AttributeConverter不起作用。 I'm sure, that JOIN causes this problem, but I don't know how to solve it. 我确定,JOIN导致了这个问题,但我不知道如何解决它。 Without JOIN AttributeConverter in the query works fine. 没有JOIN AttributeConverter在查询中工作正常。 I found one ugly solution (you can see it in my code), but I'm looking for the right one. 我发现了一个丑陋的解决方案(你可以在我的代码中看到它),但我正在寻找合适的解决方案。

So, in case with JOIN for a query 因此,如果使用JOIN进行查询

SELECT t FROM TaskEntity t JOIN t.involvedUsers u WHERE status in :statuses AND u.id IN :involvedUserIds ORDER BY t.id DESC 

Query params: 查询参数:

statuses = [CREATED, APPROVED, IN_PROGRESS];
involvedUserIds = [1, 2];

I got following error: 我收到以下错误:

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.

Code below: 代码如下:

@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();
    }
}

Task entity: 任务实体:

@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;
}

User entity 用户实体

@Getter @Setter
@Entity
@Table(name = "users")
public class UserEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @NotNull
    @Column(unique = true)
    private String email;
}

Task statuses: 任务状态:

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;
    }
}

Task statuses converter: 任务状态转换器:

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);
    }
}

And repository: 和存储库:

@NoRepositoryBean
public interface CustomTaskRepository {
    List<TaskEntity> find(List<TaskStatuses> statuses, List<Integer> involvedUserIds)
}

In this project I'm using spring-boot 1.5.8.RELEASE and spring-data-jpa 1.5.8.RELEASE . 在这个项目中,我使用的是spring-boot 1.5.8.RELEASEspring-data-jpa 1.5.8.RELEASE Code from project simplified and contains only information required for this example (You can see some redundant information in logs). 项目简化的代码,仅包含此示例所需的信息(您可以在日志中看到一些冗余信息)。 Thank you for a help. 谢谢你的帮助。

试试这个:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM