關於maven下ssm整合的項目推薦這篇博客:https://www.cnblogs.com/yiye/p/5969157.html
今日在ssm下的將新增數據寫回數據庫時遇到不少的問題,現作記錄
如果只是簡單地使用Mybatis的話,具體的流程如下:
創建配置文件——>根據配置文件來生成會話工廠——>通過工廠來生成會話——>通過會話操作數據庫!
具體可以參考這里:http://how2j.cn/k/mybatis/mybatis-crud/1088.html#nowhere
我理解就是如下圖的三個步驟
好了,說了上面的廢話其實是想說,在ssm中,操作數據庫也是要配置sessionFactory的,只是不再像上圖那樣,而是在mybatis的配置文件(或者spring的相關配置文件)中完成,如下圖:
如果沒整合過的,可以先看:https://www.cnblogs.com/yiye/p/5969157.html
回歸問題上來,在插入數據庫時出現500的狀態碼錯誤!!!
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.jdbc.BadSqlGrammarException: ### Error updating database. Cause: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ',,,)' at line 1 ### The error may involve com.example.edu.mapper.UserMapper.insert-Inline ### The error occurred while setting parameters ### SQL: insert into t_user (username,password,birthday,gender) values (,,,) ### Cause: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ',,,)' at line 1
根據提示,是說SQL語法錯誤?然后,我發現自己瞎了,參考的視頻是這樣的(注意紅色框內)
沒錯,我以為紅色框內的字段是用單引號引起來的,然后我的SQL語句中就都用單引號引起來了!!!
誰知道ta用的是 ` 這個點?????
所以最后的SQL語句應該是
<insert id="insert" parameterType="User" useGeneratedKeys="true" keyProperty="id">
insert into t_user (`username`,`password`,`birthday`,`gender`) values (#{username},#{password},#{birthday},#{gender}) </insert>
或者是(去掉那個點)
<insert id="insert" parameterType="User" useGeneratedKeys="true" keyProperty="id">
insert into t_user (username,password,birthday,gender) values (#{username},#{password},#{birthday},#{gender}) </insert>
然后還遇到了一個這樣的問題
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.jdbc.BadSqlGrammarException:
### Error updating database. Cause: java.sql.SQLSyntaxErrorException: Unknown column 'Karen' in 'field list'
### The error may involve com.example.edu.mapper.UserMapper.insert-Inline
### The error occurred while setting parameters
### SQL: insert into t_user (username,password,birthday,gender) values (Karen,kl,19990912,female)
### Cause: java.sql.SQLSyntaxErrorException: Unknown column 'Karen' in 'field list'
原因是我的sql語句中的#全用了 $,就是下面這樣的,是錯的,是錯的!
<insert id="insert" parameterType="User" useGeneratedKeys="true" keyProperty="id">
insert into t_user (username,password,birthday,gender) values (${username},${password},${birthday},${gender}) </insert>
引入了一個 關於 # 和 $ 的區別
好吧我不知道什么鬼,看這篇博客吧:https://www.cnblogs.com/kangyun/p/5881531.html
后續:
這也是我第一次玩ssm,剛開始有以為也要想單一使用mybatis那樣,要創建具體的會話工廠來操作數據庫,要commit和close,后來才知道在xml中直接配置就行了,果然niubi
上面那個#和$的錯誤其實是看了一篇錯的博客導致的,不過,也是因為那篇博客才讓我去關注到這個問題,雖然現在還不是很理解