增加null&&使用HashMap存储查询结果集

增加null

oracle:如果插入的字段是Null,提示错误:Other而不是null

mysql:如果插入的字段是Null,正常执行(没有约束)

原因:各个数据库在mybatis中对各种数据类型的默认值不一致

  mybatis中,jdbcTypeForNull(如果是null),则默认值是Other。

  Other来说,Mysql能够处理(NULL),但是Oracle不行

解决:

  Oracle:null->Other,需要手工告诉Oracle:other为null

  a.修改具体的sql标签

当某个数据类型oracle无法处理时,告诉它默认值null

注意此时设置的#{stuName,jdbcType=NULL}不会影响正常的赋值

src\org\myy\mapper\studentMapper.xml

    "addStudent" parameterType="Student" databaseId="oracle">
        "stuNo" resultType="Integer" order="AFTER">
            select myseq.currval from dual
        
        insert into student1(stuno,stuname,stuage,graname)
        values(myseq.nextval,#{stuName,jdbcType=NULL},#{stuAge},#{graName})
    

  b.配置mybatis全局配置文件conf.xml(推荐)

src\conf.xml

 
        "jdbcTypeForNull" value="NULL"/>
 

 

 

返回值为HashMap的情况

 src\org\myy\mapper\studentMapper.xml

    

 其中stuNo是数据库的字段名

"no"是stuNo的别名,用于在map中get值时使用(作为map的key)map.get("no")

如果不加别名,map的key就是字段名

 src\org\myy\mapper\StudentMapper.java

HashMap queryStudentOutByHashMap(int stuNo);

 

src\org\myy\test\Test.java

        //Connection - SqlSession操作Mybatis
        //conf.xml->reader
        Reader reader = Resources.getResourceAsReader("conf.xml");
        //reader->sqlSession

        //可以通过build的第二参数 指定数据库环境
        SqlSessionFactory sessionFactory=new SqlSessionFactoryBuilder().build(reader,"devOracle");
        SqlSession session = sessionFactory.openSession();

        StudentMapper studentMapper=session.getMapper(StudentMapper.class);

        HashMap studentMap = studentMapper.queryStudentOutByHashMap(1);
        System.out.println(studentMap.get("no")+","+studentMap.get("name")+","+studentMap.get("age"));
        System.out.println(studentMap);
        session.close();

key:id  value:Student

src\org\myy\mapper\studentMapper.xml

    <select id="queryStudentsByHashMap"
            resultType="HashMap">
        select stuNo,stuName,stuAge from student1
    select>

 

 src\org\myy\mapper\StudentMapper.java

    //程序根据select的返回值,知道map的value就是Student,根据@MapKey("STUNO")知道map的key是stuNo
  @MapKey("STUNO")//Oracle的元数据(表名、字段名)都是大写
  HashMap
queryStudentsByHashMap();

 

src\org\myy\test\Test.java

        //Connection - SqlSession操作Mybatis
        //conf.xml->reader
        Reader reader = Resources.getResourceAsReader("conf.xml");
        //reader->sqlSession

        //可以通过build的第二参数 指定数据库环境
        SqlSessionFactory sessionFactory=new SqlSessionFactoryBuilder().build(reader,"devOracle");
        SqlSession session = sessionFactory.openSession();

        StudentMapper studentMapper=session.getMapper(StudentMapper.class);

        HashMap studentsMap = studentMapper.queryStudentsByHashMap();
        //System.out.println(studentMap.get("no")+","+studentMap.get("name")+","+studentMap.get("age"));
        System.out.println(studentsMap);

        session.close();

 

你可能感兴趣的:(增加null&&使用HashMap存储查询结果集)