skip to Main Content

I have a dependency Table Sellars which is having the City ID only. But while showing the sellars I need to show the Sellar country, state. I have written the join query it is returning rest of the sellar details except country,city and state as null. I haven’t kept any relation like @manytoOne as it will also show the zipcode list under the city as there is a relation.

@Entity(name = "tbl_sellars")
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class Sellars extends CommonEntity {
    
    @Column(name = "sellarName")
    String sellarName;
    @JsonIgnore
    @Column(name = "fk_city_id")   // this contains the city Id
    String fk_city_id;
    
    @Transient             //Kept these variable Transient as I Don't need these in Entity
    String country;
    @Transient
    @JsonProperty
    String state;
    @Transient
    @JsonProperty
    String cityName;
}


@Entity(name= "tbl_city")
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class City extends CommonEntity {
    
    String cityName;
    
    @ManyToOne
    @JoinColumn(name = "fk_state_id")
    private State state;
    
    @OneToMany(cascade = CascadeType.ALL)
    @JoinColumn(name = "fk_city_id", referencedColumnName = "id")
    private List<ZipCode> zipcodes;
}

@Repository
public interface SellarsRepository extends JpaRepository<Sellars, Long>{
      @Query(value = "SELECT u.*, c.country, s.state,ci.cityName" +
      " FROM tbl_sellars u" + " JOIN tbl_city ci ON u.fk_city_id = ci.id" +
      " JOIN tbl_state s ON ci.fk_state_id = s.id" +
      " JOIN tbl_country c ON s.fk_country_id = c.id", nativeQuery = true)
      List<Sellars> getAllSellarsWithRegion();
}

Json Returned like

[
  {
    "id": 2,
    "sellarName": "Avik ray",
    "country": null,
    "state": null,
    "cityName": null
  }
]

2

Answers


  1. As your attributes are annotated with @Transient they will not be handled by Hibernate and are therefore null

    Login or Signup to reply.
  2. @Transient annotation is used to mark a field to be transient for the mapping framework, which means the field marked with @Transient is ignored by mapping framework and the field not mapped to any database column (in RDBMS) or Document property (in NOSQL). Thus the property will not be persisted to data store.

    Source: https://javabydeveloper.com/using-transient-in-spring-boot-examples/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search