2012-09-11 92 views
1

這裏適當的構造是我的課:休眠:無法找到上

public class TrainLate { 

private int id; 
private Date startDate; 
private Date endDate; 
private Set<TrainSchedule> ts=new HashSet<TrainSchedule>(); 
public TrainLate(){} 
public TrainLate(int id, Date startDate, Date endDate) { 
    super(); 
    this.id = id; 
    this.startDate = startDate; 
    this.endDate = endDate; 
} 

    // setters and getters... 
} 

類型日期爲java.sql.Date

在另一類我使用HQL:

String hql="SELECT new TrainLate(id,startDate,endDate) FROM TrainLate "+    "WHERE id="+String.valueOf(index); 

其中index爲一個int參數。

這裏是 「TrainLate.hbm.xml」:

<class name="classes.TrainLate"> 
    <id name="id"> 
     <generator class="native"/> 
    </id> 
    <property name="startDate"/> 
    <property name="endDate"/> 
    <set name="ts" lazy="false" cascade="all-delete-orphan" inverse="true"> 
      <key column="trainLateID" /> 
      <one-to-many class="classes.TrainSchedule" /> 
      </set> 
</class> 

這裏是個例外:

Unable to locate appropriate constructor on class [classes.TrainLate] [SELECT new TrainLate(id,startDate,endDate) FROM classes.TrainLate WHERE id=0] 

其中, 「類別」 是軟件包的名稱。

+1

我已經改變sql.Date到util.Date和類再出口到Oracle和在Oracle中,類型將是「解決了這個問題時間戳」。但是,如果我在java中使用sql.Date,那麼在導出之後,在oracle中輸入type將是「Date」,並且會出現上述異常。 – Frazer

回答

3

第一:Hibernate要求你的實體有一個默認的無參數構造函數。

第二:你的hql應該是:"from TrainLate t where t.id = :id"

String hql = "from TrainLate t where t.id = :id"; 
List<TrainLate> result = (List<TrainLate>) session.createQuery(hql).setParameter("id", 1).list(); 

甚至更​​好。當你知道實體的id,你不需要用HQL搜索:

TrainLate t = session.get(TrainLate.class, 1L); // I assume your id is a Long 

如果找不到實體這一個返回null

TrainLate t = session.load(TrainLate.class, 1L); // I assume your id is a Long 

如果未找到該實體這之一拋出ObjectNotFoundException

+0

我有沒有爭論的構造函數。那麼我試着session.get()方法,它的工作原理。但是HQL有什麼問題?我必須在接下來使用它。 – Frazer

+0

您通常使用佔位符,不要動態組合hql。 HQL適用於其他非ID的屬性。 – dcernahoschi

+0

你的意思是這樣的佔位符? Query query = session.createQuery(hql).setParameter(「id」,0);它也不起作用。 – Frazer

1

我知道它聽起來很愚蠢,但你試過調試這件事嗎?

我的第一個想法是(如果我是休眠:))創建TrainLate對象與無OP構造函數,然後調用一系列setter來設置id,startDate和endDate。

我沒有看到它在你的代碼片段...