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);
    }
}
6
  • Is there a reason why you're using a Long instead of Integer? Commented Mar 28, 2018 at 1:09
  • To avoid running out of space/making a change in the code in case I change the id type to bigger data type Commented Mar 28, 2018 at 1:17
  • Why are you using the @Id annotation on two fields? That annotation should be used on the primary key field. Commented Mar 28, 2018 at 1: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 stackoverflow.com/questions/13032948/… Commented Mar 28, 2018 at 1:31
  • 1
    Yeah do that, you need to create a composite key class. See the Oracle docs as well. Commented Mar 28, 2018 at 1:34

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.