I am trying to fetch specific fields from my entities. I need the result in my entity structure.
Following are my entities:
Country
public class CountryModel {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "CmtID")
private int id;
@Column(name = "CmtName")
private String name;
@JoinColumn(name="CmtStateID")
@OneToMany(targetEntity=StateModel.class,fetch=FetchType.EAGER)
private List<StateModel> state;
}
State
public class StateModel {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "SmtID")
private int id;
@Column(name = "SmtName")
private String name;
}
Following is the HQL query am executing:
Query query = session.createQuery("select c.name, s.name from CountryModel c join c.state s where c.id=2");
CountryModel stateModel = (CountryModel) query.uniqueResult();
But am getting the following error:
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.muziris.entity.CountryModel
Thanks for helping.
Expected result:
Country :
name : india
state :
name : kerala
name : goa
name : Pak
state :
name : karachi
Since your classes are mapped you can try:
Query query = session.createQuery("from CountryModel c where c.id=2");
CountryModel countryModel = (CountryModel) query.uniqueResult();
Let's make use of the mapping and HQL.
From there you can use a DTO to have only the data that you need
public CountryDTO transform(CountryModel cm){
String countryName = cm.getName();
List<String> stateNames = cm.getState().stream.map(StateModel::getName)
.collect(Collectors.toList());
return new CountryDTO(countryName, stateNames);
}
CountryDTO is the result that you need.
Hibernate returns List<Object[]>
when you use the projections. List<Object[]>
is a list of specified projection columns.
Some links
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.