spring+hibernate+struts整合錯誤羅列
阿新 • • 發佈:2020-12-19
技術標籤:程式碼錯誤
1.中文亂碼:
JSP介面傳輸中文獲值亂碼,解決方案:工具類
public class Util{
//提供一個方法,將亂碼轉化成utf-8
public String getNewString(String input){
String result = “”;
try{
result = new String(input.getBytes(“iso-8859-1”),“utf-8”);
}catch(Exception e){
e.printStackTrace();
}
return result;
}
但是利用工具類檢索可以,新增卻是資料庫一堆亂碼。解決方案
在serlvers(伺服器資料夾)中的server.xml中的63行新增URIEncoding=”UTF-8“這樣工具類也不用了,資料庫也能成中文了,一勞永逸
2.一對多,我用的學生多,老師一,測試檢索的時候報錯指向的老師對映不存在,
Hibernate:An association from the table Table refers to an unmapped class錯誤資訊大概是這樣,
解決方案:把引用的class寫成全名,然後測試的時候不要用原來的開啟事務new的方法,這樣會丟失資料,還有就是對映檔案懶載入暫時先關掉,不然獲取不到值。
遍歷方法,
public List<User> getAllUser() {
return this.getHibernateTemplate().execute( new HibernateCallback< List<User>>() {
@Override
public List<User> doInHibernate(Session session) throws HibernateException, SQLException {
String hql="from User";
Query que=session.createQuery(hql);
return que.list();
}
});
測試方法
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class UserServiceImplTest {
@Resource(name ="us")
private UserServices us;
@Test
public void test() {
List<User> allUser = us.getAllUser();
for (User user : allUser) {
System.out.println(user.getName()+","+ user.getTeacher().getTname());
}
}
}
```測試結果
![在這裡插入圖片描述](https://img-blog.csdnimg.cn/20201217181430991.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzMwODkzNjM1,size_16,color_FFFFFF,t_70)
**注意:如果你的外來鍵欄位為空可能會報空指標**
3.一對多建立另外一張表失敗,不能自動見表,錯誤原因是application,xml不識別標籤決絕方案是把標籤全部寫成全稱,加上hibernate
![在這裡插入圖片描述](https://img-blog.csdnimg.cn/20201217175109822.png)
4.給教師表加資料,學生表外來鍵沒有對應值,大概就像這樣,外來鍵無值,
![在這裡插入圖片描述](https://img-blog.csdnimg.cn/20201217175235277.png)
解決方案:
加入級聯,這樣就可以又資料了
![在這裡插入圖片描述](https://img-blog.csdnimg.cn/20201217175311815.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzMwODkzNjM1,size_16,color_FFFFFF,t_70)
5.給學生表加資料,反過來想讓教師表裡也有,但是報錯
org.springframework.dao.InvalidDataAccessApiUsageException: object references an unsaved transient instance - save the transient instance before flushing: cn.oracle.pojo.Teacher; nested exception is org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: cn.oracle.pojo.Teacher
錯誤原因:因為對應表中沒有這個資料,所以你是無法把遊離態的資料加進去的,
解決方法:
教師類的對映取消維護
![在這裡插入圖片描述](https://img-blog.csdnimg.cn/20201217181054482.png)
學生類的增加級聯
![在這裡插入圖片描述](https://img-blog.csdnimg.cn/20201217181117515.png)
這樣就可以反向插入資料了