首页 > 数据库技术 > 详细

解决mybatis中 数据库column 和 类的属性名property 不一致的两种方式

时间:2019-11-10 19:40:01      阅读:216      评论:0      收藏:0      [点我收藏+]

解决方式way1:resultMap

     (1)studentMapper.xml

	<!-- 当数据库的字段名   和  类的属性名   不一致的时候的解决方式:2种   way1-->
	<select id="selectOneNotPipeiWay1" resultMap="aaa" parameterType="int">
	      select * from student where id = #{id}
	</select>
	<resultMap id="aaa" type="susu.demo.Student">
	     <result property="grade" column="gradenews"/><!-- property: 类的属性名     column:数据库的字段名 -->
	</resultMap>

  

      (2)studentManager.java动态代理接口(接口中的方法默认都是public  abstract ,可以不写)

        

    //数据库的字段名   和  类的属性名不一致的时候 的解决方式之一
    Student selectOneNotPipeiWay1(int id);

 

  (3)测试方法

 

	
	/**
	 * column  和  property不匹配的时候的解决方式之一: resultMap
	 */
	public static void notPipeiWay01() throws IOException
	{
		Reader reader = Resources.getResourceAsReader("conf.xml");
		
		SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
		
		SqlSession session  =  sessionFactory.openSession();//就是session名字即可
		
		
		StudentManager studentManager = session.getMapper(StudentManager.class);
		Student s = studentManager.selectOneNotPipeiWay1(2);
	 
		System.out.println(s.toString());
		session.close();
		
	}//notPipeiWay01()

  

 

解决方式way2:resultType+HashMap

     (1)studentMapper.xml

 

	<!-- way2 -->
	<select id="selectOneNotPipeiWay2" resultType="susu.demo.Student" parameterType="int">
	      select id, gradenews "grade" from student where id = #{id}
	</select>

  

      (2)studentManager.java动态代理接口(接口中的方法默认都是public  abstract ,可以不写)

        

	//数据库的字段名   和  类的属性名不一致的时候 的解决方式之二
	Student selectOneNotPipeiWay2(int id);

  

  (3)测试方法

    /**
     * column  和  property不匹配的时候的解决方式之二: resultType+HashMap
     */
    public static void notPipeiWay02() throws IOException
    {
        Reader reader = Resources.getResourceAsReader("conf.xml");
        
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
        
        SqlSession session  =  sessionFactory.openSession();//就是session名字即可
        
        
        StudentManager studentManager = session.getMapper(StudentManager.class);
        Student s = studentManager.selectOneNotPipeiWay2(1);
     
        System.out.println(s.toString());
        session.close();
        
    }//notPipeiWay02()

 

解决mybatis中 数据库column 和 类的属性名property 不一致的两种方式

原文:https://www.cnblogs.com/guofen3399/p/11831343.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!