Search code examples
javamysqlhibernatejpa

Mapping entity field in JPA/Hibernate with session.get()


Why do not I can create new Address with using:

AddressEntity ad = new AddressEntity(); 
ad.setCityId(session.get(CityEntity.class, 343))

but it works in this way:

Query<CityEntity> query = session.createQuery("from CityEntity where id = 343", CityEntity.class);
 query.setFirstResult(0);
 query.setMaxResults(1);
 List<CityEntity> listCity = query.getResultList();
 ad.setCityId(listCity.get(0));

Address entity:

@Entity
@Table(name = "address")
@Getter
@Setter
@ToString
public class AddressEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "address_id")
    private Short addressId;
    ...
    ...
    @ManyToOne
    @JoinColumn(name = "city_id")
    private CityEntity cityId;

}

City entity:

@Entity
@Table(name = "city")
@Getter
@Setter
@ToString
public class CityEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "city_id")
    private Short cityId;
    ...
    ...
    ...

}

I fell like I don't know something useful, but I can't understand what is it

I was trying get and set id by session.get() and by query


Solution

  • The problem here was that the primary key (@Id property) is defined as Short, but Java converts the 343 in session.get(CityEntity.class, 343) to an Integer by default; so JPA searches for a CityEntity with Integer id, which does not exist.

    Giving it a Short will do the trick; either:

    session.get(CityEntity.class, Short.valueOf(343))
    

    Or:

    session.get(CityEntity.class, (short) 343)
    

    In the latter case Java will still "box" the short literal to a Short object.