MyBatisMyBatis的增删改查
Posted 司徒二条
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MyBatisMyBatis的增删改查相关的知识,希望对你有一定的参考价值。
(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(); }
以上是关于MyBatisMyBatis的增删改查的主要内容,如果未能解决你的问题,请参考以下文章