MyBitis(iBitis)系列随笔之三:简单实现CRUD
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MyBitis(iBitis)系列随笔之三:简单实现CRUD相关的知识,希望对你有一定的参考价值。
Mybitis(iBitis)实现对对象增删改查操作要借助<select/>查询,<insert/>增加,<update/>更新,<delete/>删除 标签来操作。
值得注意的有两点:
1、在对对象进行增删改时,SqlSession session = sqlSessionFactory.openSession();获取的session。必选执行session.commit();否则操作无效。
2、Mybitis与hibernate一样,插入数据后会把id值赋值给缓存中对象
还是接着上一讲的代码继续改动
UserMapper.xml
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE mapper
- PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
- "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
- <mapper namespace="user">
- <resultMap id="userResultMap" type="user">
- <id property="id" column="id"/>
- <result property="userName" column="name"/>
- <result property="password" column="pass"/>
- </resultMap>
- <!--resultType 表示com.jefry.User这样一个实体对象 -->
- <select id="selectUser" parameterType="int" resultMap="userResultMap" >
- select * from t_user where id = #{id}
- </select>
- <!--增加操作-->
- <insert id="addUser" parameterType="user"
- useGeneratedKeys="true" keyProperty="id">
- insert into t_user(name,pass) values(#{userName},#{password})
- </insert>
- <!--更新操作-->
- <update id="modifyUser" parameterType="user">
- update t_user set name=#{userName}, pass=#{password} where id=#{id}
- </update>
- <delete id="deleteUser" parameterType="int">
- delete from t_user where id=#{id}
- </delete>
- </mapper>
测试代码
- public class Test {
- static String resource = "mybatis-config.xml";
- public static void main(String[] args) throws IOException {
- // TODO Auto-generated method stub
- InputStream inputStream = Resources.getResourceAsStream(resource);
- SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
- SqlSession session = sqlSessionFactory.openSession();
- try {
- //User.selectUser中User对应UserMapper.xml文件中标签<mapper namespace="User"> namespace的值
- //selectUser 对应UserMapper.xml文件中标签<select id="selectUser" parameterType="int" resultType="com.jefry.User">中id值
- User user = session.selectOne("user.selectUser", 1);
- System.out.println("user.getName()=" + user.getPassword());
- User addUser = new User();
- addUser.setUserName("NEWWWWW");
- addUser.setPassword("111111");
- session.insert("user.addUser", addUser);
- //插入操作
- User modifyUser = new User();
- modifyUser.setUserName("NEWWWWW");
- modifyUser.setPassword("111111");
- modifyUser.setId(1);
- //修改用户
- session.update("user.modifyUser", addUser);
- //删除操作
- session.delete("user.deleteUser",2);
- //这里必须commit,否则增删改无效
- session.commit();
- //与hibernate一样,插入数据后会把id值赋值给缓存中的id
- System.out.println("addUser.getId()" + addUser.getId() );
- } finally {
- session.close();
- }
- }
- }
以上是关于MyBitis(iBitis)系列随笔之三:简单实现CRUD的主要内容,如果未能解决你的问题,请参考以下文章
MyBitis(iBitis)系列随笔之六:mybitis与spring集成