【问题标题】:Spring Data JPA won't find duplicate byte[]Spring Data JPA 找不到重复的字节 []
【发布时间】:2016-10-27 14:58:50
【问题描述】:

我有一个沿 3 个类映射的实体层次结构,如下所示:

Event.java:

@Entity
@Table(name = "events")
public class Event implements Serializable
{
    @Id
    @GeneratedValue
    @Column(name = "id")
    private long id;

    @Enumerated(EnumType.STRING)
    @NotNull
    @Column(name = "department_name", nullable = false)
    private Department department;

    @NotNull
    @Lob
    @Column(name = "business_identifier", nullable = false)
    private byte[] businessIdentifier;

    @Embedded
    private AbstractEventInformation eventInformation;

    public Event(
        final Department department,
        final AbstractEventInformation eventInformation
    )
    {
        this.department = department;
        this.eventInformation = eventInformation;
    }

    @PrePersist
    public void saveBusinessIdentifier()
    {
        this.businessIdentifier = eventInformation.getBusinessIdentifier();
    }

    public byte[] getBusinessIdentifier()
    {
        return null != businessIdentifier ? this.businessIdentifier : eventInformation.getBusinessIdentifier();
    }
}

AbstractEventInformation.java:

@Embeddable
public abstract class AbstractEventInformation
{
    public abstract byte[] getBusinessIdentifier();
}

OrderEventInformation.java:

import com.google.common.primitives.Ints;

public class OrderEventInformation extends AbstractEventInformation
{
    private final int orderId;

    public OrderEventInformation(final int orderId)
    {
        this.orderId = orderId;
    }

    @Override
    public byte[] getBusinessIdentifier()
    {
        return Ints.toByteArray(orderId);
    }
}

这是绑定到Event的存储库:

EventRepository.java:

public interface EventRepository extends JpaRepository<Event, Long>
{
    int countByDepartmentAndBusinessIdentifier(Department department, byte[] businessIdentifier);
}

这种结构非常适合将条目保存到events 表中。但是,由于某种原因,当我尝试使用 countByDepartmentAndBusinessIdentifier 检查 MySQL 中的重复项时,此方法总是返回 0

我有使用 H2 运行的集成测试,在这些测试中,重复检查工作得很好,这似乎是 MySQL 特有的。

起初我认为这可能与我的类的结构方式有关,使用Embeddable、抽象方法等,但我认为如果这是问题所在,那么保存值将无法正常工作。

有人知道我在这里缺少什么吗?

顺便说一句,我正在使用 Spring Boot 版本 1.3.5.RELEASEspring-boot-starter-data-jpa

非常感谢您的帮助!

【问题讨论】:

    标签: java mysql spring spring-data-jpa


    【解决方案1】:

    原来问题与类层次结构无关。

    我的Event#businessIdentifier 被映射为byte(16) 到DB,因此,当我执行Ints.toByteArray(orderId) 时,它会返回一个byte[4]。但在 DB 中,所有businessIdentifiers 都存储为byte[16],因此我试图对不同大小的字节数组进行重复检查。

    修复将 OrderEventInformation#getBusinessIdentifier 更改为将 byte[] 右填充零,最多 16 个位置。然后一切顺利。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-10
      • 1970-01-01
      • 2014-12-29
      • 2021-11-16
      • 2018-08-27
      • 2013-11-04
      • 2016-10-10
      • 1970-01-01
      相关资源
      最近更新 更多