Mybatis入门(二)——CRUD
Mybatis入门(二)
添加数据
1.在studentMapping.xml写入SQL
<insert id="studentAdd" parameterType="com.bean.Student"> insert into student values(#{sno},#{sName},#{sSex},#{sAge},#{sDept}); </insert>
2.Main函数调用插入数据
String statement="com.bean.studentMapping";
String sIn=statement+".studentAdd";
Student stu=new Student("234","dexx","nvd","de","eddd"); int s=sqlSession.insert(sIn, stu);
sqlSession.commit();
更新数据
1.在studentMapping.xml写入SQL
<parameterMap type="Map" id="updMap">
<parameter property="sName" javaType="String"/>
<parameter property="sno" javaType="String"/>
</parameterMap>
<update id="studentUp" parameterMap="updMap">
update student set sname=#{sName} where sno=#{sno};
</update>
2.Main函数调用更新数据
String stuSelect=statement+".getStudent"; Student studentInfor=sqlSession.selectOne(stuSelect, "111");
System.out.println(studentInfor.getsName()); String stuUpd=statement+".studentUp"; Map<String,Object> updMap=new HashMap<String,Object>(); updMap.put("sno", studentInfor.getSno()); updMap.put("sName", "Xu"); sqlSession.update(stuUpd, updMap); sqlSession.commit(); sqlSession.close();
删除数据
1.在studentMapping.xml写入SQL
<delete id="stuDel" parameterType="String"> delete from student where sno=#{sno}; </delete>
2.Main函数调用删除数据
String stuDel=statement+".stuDel"; sqlSession.delete(stuDel, "234"); sqlSession.commit(); sqlSession.close();
查询获取多条数据
1.在studentMapping.xml写入SQL
<select id="getStudentAll" resultType="com.bean.Student"> select * from student; </select>
2.Main函数调用查询数据
String stuSelectAll=statement+".getStudentAll"; List<Student> StuList=sqlSession.selectList(stuSelectAll); System.out.println(StuList); sqlSession.close();