mybatis学习笔记1_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > mybatis学习笔记1

mybatis学习笔记1

 2014/8/13 15:25:28  cnflat  程序员俱乐部  我要评论(0)
  • 摘要:一个UserMapper<mappernamespace="example.dao.UserMapper"><resultMaptype="User"id="usermap"><resultcolumn="name"property="name"typeHandler="example.dao.typehandler.SimpleTypeHandler"/></resultMap><
  • 标签:笔记 学习 学习笔记
一个UserMapper
class="xml">
<mapper namespace="example.dao.UserMapper">
	<resultMap type="User" id="usermap">
		<result column="name" property="name" typeHandler="example.dao.typehandler.SimpleTypeHandler"/>
	</resultMap>
	<select id="findById" parameterType="HashMap" resultType="User" resultMap="usermap">
		select * from test.T_User where id=#{id}
    </select>
    <!-- 
    <select id="findByName" parameterType="HashMap" resultType="User">
		select * from test.T_User where name=#{name}
    </select>
     -->
     <insert id="addUser" parameterType="User" useGeneratedKeys="true" keyProperty="id">
     	insert into T_User (name,sex,age) values(#{name},#{sex},#{age})
     </insert>
</mapper>


测试代码:
package example;

import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import example.dao.UserMapper;
import example.model.User;

public class SimpleBatis {
	public static void main(String[] args) throws Exception {
		String resource = "mybatis-config.xml";
		InputStream in = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlfactory = new SqlSessionFactoryBuilder().build(in);
		SqlSession session = sqlfactory.openSession(true);
		try {
			UserMapper mapper = session.getMapper(UserMapper.class);
			
			User user = null;
			user = new User();
			user.setName("terry");
			user.setSex((byte)1);
			user.setAge(30);
			mapper.addUser(user);
			
			Thread.sleep(20000);
			
			new User();
			user.setName("marry");
			user.setSex((byte)0);
			user.setAge(26);
			mapper.addUser(user);
			
			user = mapper.findByName("terry");
			System.out.println(user.getId()+"-"+user.getName()+", sex:"+user.getSex()+", age:"+user.getAge());
		} finally {
//			session.commit();
			session.close();
		}
	}
}

1. sqlfactory.openSession()缺省是不会自动提交的,即使finally调用了session.close。上面insert的记录也不会出现在数据库中。需要自己调用session.commit()来提交修改。要打开autocommit可以使用openSession(true)
2. mapper.findByName根据mapper的配置是只能返回单一记录,等同于调用了session.selectOne(...),若数据库中出现多条name=terry的记录,上面的代码会报异常
发表评论
用户名: 匿名