2013-04-13 33 views
1

我正在與休眠(hibernate.jar文件)與和對象「Cliente」工作,例如:org.hibernate.exception.DataException雖然被釣到

public class Cliente { 
    private nombre; 
    ... 
    //set and get 
} 

的「農佈雷」屬性被映射爲:

<property name="nombre" type="string"> 
    <column name="nombre" length="30" not-null="true" /> 
</property> 

正如你在上面看到的,有一個字符長度限制爲30。在這裏,事情變得複雜起來......我想用長的名字,以更新名稱,以迫使一個錯誤:當名稱超過了允許的極限

Session session = HibernateUtil.getSessionFactory().openSession(); 
Transaction tx = session.beginTransaction(); 

try{ 
    cliente.setNombre(textField.getText()); //here 
    session.update(cliente); 
    tx.commit(); 
    list.repaint(); 
} catch (org.hibernate.exception.DataException e) { 
    JOptionPane.showMessageDialog(null, "Data entered too long"); 
    session.getTransaction().rollback(); 
} finally { 
    session.close(); 
} 

,這excepcion org.hibernate.exception.DataException被拋出(如debbuger細節,這是行x.commit();

SEVERE: Data truncation: Data too long for column 'nombre' at row 1 
Hibernate: update gimnasiobd.cliente set nombre=? where idCliente=? 
abr 12, 2013 7:40:07 PM org.hibernate.event.def.AbstractFlushingEventListener performExecutions 
SEVERE: Could not synchronize database state with session 
org.hibernate.exception.DataException: Could not execute JDBC batch update 

這裏有什麼問題嘛......雖然excepcion被逮住(在JOPtion所示),異常在好像抓不起作用控制檯中顯示?

回答

1

給大長度h列名稱nombre。例如

<column name="nombre" length="200" not-null="true" /> 

或刪除長度屬性。這將需要對字符串自動定義的最高值按您的數據庫供應商爲

見下面的鏈接

Solution1

也見下面的鏈接

https://stackoverflow.com/questions/1281188/text-field-using-hibernate-annotation 
+0

是的,但是當屬性被刪除時,異常依然存在。假設我在mysql數據庫中使用了列'nombre varchar(255)'。如果我設置了一個比這更大的名字,這個異常也會被拋出。 – manix

+0

轉到DB客戶端,查看Nombre列的長度。它應該是255的長度 –

+0

是的,它設置爲255。讓我試試你的鏈接。 – manix

0

環繞的rollback()與其他的try-catch到看看它是否是例外的原因

catch (org.hibernate.exception.DataException e) { 
    JOptionPane.showMessageDialog(null, "Data entered too long"); 
    try { 
     session.getTransaction().rollback(); 
    } catch (HibernateException ex) {} 
} 

我無法從文檔中確定回滾會拋出DataException的原因,但javadoc聲明回滾可以拋出一個是DataException超類的HibernateException。

+0

努普,異常是再次拋出,並一次又一次 – manix

+0

這是離奇的。嘗試圍繞'session.close()'語句,只是爲了helluvit而用try-catch,儘管我不認爲這是拋出異常 - 我無法想象任何其他原因。 –

+0

哈哈我太......圍繞session.close()不要把戲 – manix