码迷,mamicode.com
首页 > 其他好文 > 详细

MyBatis(三)MyBatis的增删改查

时间:2019-04-15 23:14:40      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:自动   inpu   自增   com   提交数据   res   val   test   add   

(1)接口中编写方法
1     public Emp getEmp(Integer id);
2     
3     public void addEmp(Emp emp);
4     
5     public void deleteEmp(Integer id);
6     
7     public void updateEmp(Emp emp);

 (2)编写Mapper文件

 1 <select id="getEmp" resultType="com.eu.bean.Emp">
 2     select id,last_name lastName,gender,email from Emp where id = #{id}
 3   </select>
 4  
 5   <!-- 最后两个属性为获取自增主键的值 如果不需要获取则可以省去 -->
 6   <insert id="addEmp" parameterType="com.eu.bean.Emp" useGeneratedKeys="true" keyProperty="id">
 7       INSERT INTO emp(last_name,gender,email) 
 8       VALUES(#{lastName},#{geder},#{email})
 9   </insert>
10   
11   <update id="updateEmp" parameterType="com.eu.bean.Emp">
12        update emp
13        set last_name = #{lastName},
14                gender = #{geder},
15                email = #{email}
16        where id = #{id}
17   </update>
18   
19   <delete id="deleteEmp">
20       delete from emp where id=#{id}
21   </delete>

(3)编写测试

public SqlSessionFactory getSqlSessionFactory() throws IOException {
        String resource = "conf/mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        return new SqlSessionFactoryBuilder().build(inputStream);
    }
    
    @Test
    public void testMapper() throws IOException {
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
        //1.获取到sqlsession 不会自动提交数据
        SqlSession openSession = sqlSessionFactory.openSession();
        EmpDao mapper = openSession.getMapper(EmpDao.class);
        
        //测试添加

        Emp emp = new Emp(null, "李四", "男","www.com"); 
        mapper.addEmp(emp);
        System.out.println(emp.getId());
        //测试修改
        /*
         * Emp emp2 = new Emp(3, "李四", "wu", "666333"); mapper.updateEmp(emp2);
         */
        
        //测试删除
        //mapper.deleteEmp(3);
        //手动提交数据
        openSession.commit();
        openSession.close();
    }

 

MyBatis(三)MyBatis的增删改查

标签:自动   inpu   自增   com   提交数据   res   val   test   add   

原文地址:https://www.cnblogs.com/wanerhu/p/10713752.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!