mybatis学习笔记1

一个UserMapper
<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的记录,上面的代码会报异常。

你可能感兴趣的:(java,mybatis)