java - Mysql int 到 Java Long 映射到 null

标签 java mysql hibernate jpa

我将 JPA 与 Hibernate 结合使用。我有一个@Entity,它有一个字段,我已将其数据类型设置为 Long。 mysql数据库中对应的字段是int(11)。当我尝试检索该字段时,它显示为 Null。我错过了什么吗?

@Entity
@EqualsAndHashCode(of = {"test_id", "other_test_id"})
@Table(name = "test_table")
@Data
class Dummy{
    @Id
    @Column(name = "test_id", nullable = false)
    private Long testId;

    @Id
    @Column(name = "other_test_id", nullable = false)
    private Long otherTestId;

}

class DummyDao{

    public Dummy findDummyByOtherTestId(Long otherTestId){

      StringBuffer query = new StringBuffer();
      query.append("SELECT * ");
      query.append("FROM test_table tt WHERE ");

      List<String> criteria = new ArrayList<>();
      criteria.add("tt.other_test_id = :otherTestId");
      query.append(criteria.get(0));

      List<Dummy> results = em.createNativeQuery(query.toString(), Dummy.class).setParameter("otherTestId", otherTestId).getResultList();

      return results.isEmpty() ? null : results.get(0);
    }
}

最佳答案

所以问题原来是有多个@Id,我认为这是告诉 JPA 这个实体有一个复合键的方法。

定义复合键 -

@Embeddable
public class MyCompositeKey implements Serializable{

    @Column(name = "test_id", nullable = false)
    @Getter
    @Setter
    private Long testId;

    @Column(name = "other_test_id")
    @Getter
    @Setter
    private Long otherTestId;
}


@Entity
@EqualsAndHashCode(of = "compositeKey")
@Table(name = "test_table")
@Data
class Dummy{

    @EmbeddedId
    @Column(name = "test_id", nullable = false)
    private Long compositeKey;
}

一旦我这样做了,hibernate 使用复合键正确地创建了模式,并且能够检索 int 字段并映射到 Long。

关于java - Mysql int 到 Java Long 映射到 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49524463/

相关文章:

java - 解析 FileList 对象中的文件

java - 如何从框架左侧制作垂直的按钮线?

mysql - Coldfusion cfloop 通过 cfquery 中的复选框

java - 无法将类型 'java.lang.String' 的值转换为所需类型

java - JPA/hibernate : schema generation with multiple persistence units

java - Hibernate XML 读取时出错

java - 通过拖动角来调整 gui 元素的大小

java - 修复 Gridlayout 转换为 ImageView 时出现的错误

mysql - SQL UNION 不适用于 2 个 HAVING 子句

php - CodeIgniter num_rows 和affected_rows 上下文