在編寫代碼的時候,我對查詢這個方法進行了重載,這樣調用的時候會根據參數的不同,進而去執行不同的操作,但是......問題來了。想法都是美好的,實際情況卻不是我理想的狀態。運行代碼的時候他動了幾下,然后一片紅色。
我仔細看了看代碼:
1 @Select("INSERT INTO comment (com_pro,user_name,com_content,com_score) VALUES (#{comment.com_pro},#{comment.user_name},#{comment.com_content},#{comment.com_score}") 2 public int insertComment(Comment comment); 3 4 @Select("DELETE FROM comment WHERE com_id =#{comment.com_id}") 5 public int delCommentById(int id); 6 7 @Select("DELETE FROM comment where user_name=#{comment.user_name}") 8 public int delCommentAll(String name); 9 10 @Select("update comment set com_content=#{comment.com_content},com_score=#{comment.com_score} where com_id=#{comment.com_id}") 11 public int updateComment(Comment comment); 12 13 @Select("SELECT * FROM comment where com_pro=#{comment.com_pro}") 14 public List<Comment> findCommentAll(String proname); 15 16 @Select("SELECT * FROM comment where com_pro=#{proname} and com_score=#{com_score}") 17 public List<Comment> findCommentAll(String proname,String com_score);
當我運行代碼的時候,就會就收到如下錯誤:
嚴重: Error while adding the mapper 'interface com.sh.dao.CommentDao' to configuration.
java.lang.IllegalArgumentException: Mapped Statements collection already contains value for com.sh.dao.CommentDao.findCommentAll
告訴我這個方法“添加映射的接口的COM的錯誤。sh.dao commentdao”配置。”(百度翻譯)
方法名是否真的不可以一樣?
答案是肯定的,少俠。
mybatis @Select是不支持方法重載的(如果紅字不算執行結果的話)。
封印代碼:
1 @Select("INSERT INTO comment (com_pro,user_name,com_content,com_score) VALUES (#{comment.com_pro},#{comment.user_name},#{comment.com_content},#{comment.com_score}") 2 public int insertComment(Comment comment); 3 4 @Select("DELETE FROM comment WHERE com_id =#{comment.com_id}") 5 public int delCommentById(int id); 6 7 @Select("DELETE FROM comment where user_name=#{comment.user_name}") 8 public int delCommentAll(String name); 9 10 @Select("update comment set com_content=#{comment.com_content},com_score=#{comment.com_score} where com_id=#{comment.com_id}") 11 public int updateComment(Comment comment); 12 13 // @Select("SELECT * FROM comment where com_pro=#{comment.com_pro}") 14 // public List<Comment> findCommentAll(String proname); 15 // 16 // @Select("SELECT * FROM comment where com_pro=#{proname} and com_score=#{com_score}") 17 // public List<Comment> findCommentAll(String proname,String com_score);
運行我的Test:
1 @Test 2 public void test() { 3 ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); 4 ActivityService ad = ctx.getBean(ActivityService.class); 5 List<Activity> list = ad.findActivityAll(); 6 for (Activity e : list) { 7 System.out.println(e.toString()); 8 } 9 }
得到輸出結果:
1 Activity [act_id=1, act_theme=雙十一, act_img=12345, act_time=Sat Nov 11 00:00:00 CST 2017]
總結:
記者:為什么要寫注解?
我:沒有錢了,肯定要做啊,不做沒有錢用。
記者:你有手有腳的怎么不去寫重載?
我:重載方面......重載是不可能重載的 這輩子不可能重載的,做實現類又不會寫,就是接口這種東西,才能維持得了生活這樣子.
記者:那你覺得注解好還是看重載好?
我:不寫重載的感覺像回家一樣,我一年寫重載,大年三十 晚上我都不回去,就平時重載出點事,我就回去看看這樣子,注解的感覺,比重載感覺好多了,在重載的時候一個人很無聊,都沒有朋友,女朋友玩 ,寫了注解發現個個都是人才,說話又好聽,超 喜歡寫注解。