我将 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/