ArrayList不能使用Texo生成的模型来设置在休眠状态

时间:2015-11-17 09:45:41

标签: java hibernate arraylist emf ecore

我已经从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。

我已经检查了这个link.,但我没有找到任何答案。

COUNTRY.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() + "]";
    }
}

2 个答案:

答案 0 :(得分:2)

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

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

  1. 生成注释模型。

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

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

  4. enter image description here

答案 1 :(得分:-1)

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