Mysql int to Java Long映射到null

时间:2018-03-28 00:52:31

标签: 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);
    }
}

1 个答案:

答案 0 :(得分:1)

所以问题变成了多个@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。