1

I am using JPA with Hibernate. I have an @Entity with a field whose data type I have set to Long. The corresponding field in the mysql database is int(11). When I try to retrieve this field, it comes up as Null. Am I missing something?

@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);
    }
}
Vivin
  • 1,327
  • 2
  • 9
  • 28
  • Is there a reason why you're using a `Long` instead of `Integer`? – Jason White Mar 28 '18 at 01:09
  • To avoid running out of space/making a change in the code in case I change the id type to bigger data type – Vivin Mar 28 '18 at 01:17
  • Why are you using the `@Id` annotation on two fields? That annotation should be used on the primary key field. – Matt Mar 28 '18 at 01:29
  • @Matt I was actually reading about that. I am new to JPA and was trying to create an entity for a table that has a composite key of 2 columns. I guess I have to follow https://stackoverflow.com/questions/13032948/how-to-create-and-handle-composite-primary-key-in-jpa – Vivin Mar 28 '18 at 01:31
  • 1
    Yeah do that, you need to create a composite key class. See the [Oracle docs](https://docs.oracle.com/cd/E16439_01/doc.1013/e13981/cmp30cfg001.htm) as well. – Matt Mar 28 '18 at 01:34
  • See this [thread](https://stackoverflow.com/questions/47629670/how-to-get-list-of-long-values-in-hibernate-from-the-table-while-casting-from-bi), it will help you. – ArifMustafa Mar 28 '18 at 01:43

1 Answers1

1

So the problem turned out to be having multiple @Id which I thought is the way to tell JPA that this entity has a composite key.

To define a composite key -

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

Once I did, hibernate created the schema correctly with the composite key and was able to retrieve the int field and map to the Long.

Vivin
  • 1,327
  • 2
  • 9
  • 28