Problem Statement: Country
have collection relationship with State
. Fetching a country getting all its states associated with it. It is desired in many cases. Now in a given case,I have both country id
and state id
, and when fetch country filtering with state id, is it possible to get single State
in Country
?
Country.class
@Entity
@Repository
@Table(name="COUNTRY")
class Country implements Serializable{
@Id
@GeneratedValue(startegy=GenerationType.AUTO)
private long id;
@OneToMany(mappedBy="country", cascade={javax.persistence.CascadeType.ALL}, fetch=FetchType.EAGER)
private java.util.Set<State> states;
//Getters and setters
}
State.class
@Entity
@Repository
@Table(name="STATE")
class State implements Serializable{
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="id", nullable=false, unique=true, updatable=true)
private long @Id
@ManyToOne
@JoinColumn(name="id")
private Country country;
//Getter and setter
}
I have tried with following query:
//This query works great when used in SQL editor. Getting one state
select * from country left join state ON country.id = state.id and state.id=3
//Tried following
setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
Used above SQL query and created criteria, but I am getting all states. Or this problem can be solved? Do we have better alternatives?