Mybatis的CRUD小Demo
为方便查看每次的增删改结果,封装了查询,用来显示数据库的记录;
public static void showInfo(){
SqlSession session = getSqlSesion();
String sql = "me.gacl.mapping.userMapper.getUsers";
List<Map<String,String>> users = session.selectList(sql);
for(Map<String,String> u : users){
System.out.println("id:" + u.get("id").toString() + "--NAME:" + u.get("NAME"));
}
session.close();
}
id字段数据库数据类型是int,返回Map接收查询结果,接收时使用了List<Map<String,String>>接收结果集;
<select id="getUsers" resultType="Map">
select * from users
</select>
然后一直报错:
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
at me.gacl.util.MyBatisUtil.showInfo(MyBatisUtil.java:46)
at me.gacl.test.TestDBUtil.upUser(TestDBUtil.java:71)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
最终改了接收结果集才解决问题:
public static void showInfo(){
SqlSession session = getSqlSesion();
String sql = "me.gacl.mapping.userMapper.getUsers";
List<Map<String,Object>> users = session.selectList(sql);
for(Map<String,Object> u : users){
System.out.println("id:" + u.get("id").toString() + "--NAME:" + u.get("NAME"));
}
session.close();
}
做一个随笔记录,纪念自己的坑。