有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

带hibernate的java ClassCastException

我正在尝试从实体中获取特定字段。我需要实体结构中的结果

以下是我的实体:

国家

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;
}

状态

public class StateModel {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "SmtID")
    private int id;
    @Column(name = "SmtName")
    private String name;
}

以下是正在执行的HQL查询:

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();

但是我得到了以下错误:

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.muziris.entity.CountryModel

谢谢你的帮助

预期结果:

Country :
        name : india
        state : 
              name : kerala
              name : goa
        name : Pak
        state :
              name : karachi

共 (2) 个答案

  1. # 1 楼答案

    由于您的类已映射,您可以尝试:

     Query query = session.createQuery("from CountryModel c where c.id=2");
     CountryModel countryModel = (CountryModel) query.uniqueResult();
    

    让我们利用映射和HQL

    从那里,您可以使用DTO仅获取所需的数据

    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是您需要的结果