2

我已经从 EMF 生成了 texo 模型。

以下是代码

 try{

             Session session = factory.openSession();
              Transaction tx = null;
              Integer employeeID = null;
              try{
                 tx = session.beginTransaction();
                 Country country = new Country();
                 country.setCode("PK");;
                 country.setCountry("PAKISTAN");
                 System.out.println((Integer) session.save(country));
                 //^ HERE THE ERROR COMES

                 tx.commit();
              }catch (HibernateException e) {
                 if (tx!=null) tx.rollback();
                 e.printStackTrace(); 
              }finally {
                 session.close(); 
              }

          }catch (Throwable ex) { 
             System.err.println("Failed to create sessionFactory object." + ex);
             throw new ExceptionInInitializerError(ex); 
          }

当我尝试添加带或不带位置的国家对象时,出现错误

无法创建 sessionFactory object.java.lang.ClassCastException:java.util.ArrayList 无法转换为 java.util.Set

该模型由 Texo 生成,具有 List 以及生成的简单 getter 和 setter。

我已经检查了这个链接。但我没有找到任何答案。

国家.java

import java.util.ArrayList;
import java.util.List;
public class Country {
    private int iD = 0;
    private String country = null;
    private String code = null;
    private List<Location> locations = new ArrayList<Location>();
    public int getID() {
        return iD;
    }
    public void setID(int newID) {
        iD = newID;
    }    
    public String getCountry() {
        return country;
    }    
    public void setCountry(String newCountry) {
        country = newCountry;
    }       
    public String getCode() {
        return code;
    }    
    public void setCode(String newCode) {
        code = newCode;
    }       
    public List<Location> getLocations() {
        return locations;
    }   
    public void setLocations(List<Location> newLocations) {
        locations = newLocations;
    }
    @Override
    public String toString() {
        return "Country " + " [iD: " + getID() + "]" + " [country: "
                + getCountry() + "]" + " [code: " + getCode() + "]";
    }
}
4

2 回答 2

2

正如Texo中所讨论的 ,我必须在 java 实体中生成 SET 而不是 LIST 才能使用 Hibernate。

所以我必须配置 TEXO 为所有实体执行此操作。

  1. 生成注释模型。

  2. 找到实体(位置)并添加新注释。转到其属性并设置USE LIST = FALSE

  3. 生成 texo 模型,所有需要的实体将从 List 更改为 Set

在此处输入图像描述

于 2015-11-17T14:31:49.720 回答
-1

请尝试更改Set<Location> sLoc = new HashSet<Location>(locations);List<Location> sLoc = new ArrayList<Location>(locations);. 你有你locations的数组和sLoc哈希集,所以它给出了强制转换异常..希望这能解决你的问题

于 2015-11-17T09:56:22.587 回答