1. 操作 users 表的 CRUD
1). 定义 sql 映射 xml 文件:
<insert id="insertUser" parameterType="com.eduask.ibatis.bean.User"> insert into users(name, age) values(#{name}, #{age}); </insert> <delete id="deleteUser" parameterType="int"> delete from users where id=#{id} </delete> <update id="updateUser" parameterType="com.eduask.ibatis.bean.User"> update users set name=#{name},age=#{age} where id=#{id} </update> <select id="selectUser" parameterType="int" resultType="com.eduask.ibatis.bean.User"> select * from users where id=#{id} </select> <select id="selectAllUsers" resultType="com.eduask.ibatis.bean.User"> select * from users </select>
2).在 config.xml 中注册这个映射文件
<mapper resource="com/eduask/ibatis/bean/userMapper.xml"/>
3).在 dao 中调用:
public User getUserById(int id) {
SqlSession session = sessionFactory.openSession();
User user = session.selectOne(URI+".selectUser", id);
return user;
}