1.保证类里有构造函数
public Student(Integer SID, String sname, String ssex, Integer sage) { this.SID = SID; Sname = sname; Ssex = ssex; Sage = sage; }
2.接口里方法传对象
public int insertStudent(Student student);
3.Student Mapper.xml里
<insert id="insertStudent" parameterType="com.tulun.maventest.pojo.Student" > insert into student(SID, Sname, Sage, Ssex) values (#{SID}, #{Sname} ,#{Sage}, #{Ssex} ) </insert>
4.MyBatisDemo的insertStudent() 里
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); Student student=new Student(10,"小明","男",24); System.out.println(mapper.insertStudent(student)); sqlSession.commit();//事务
原理是将参数放到HashMap里,传一个Map对象,通过键值对的形式获取
1.xml文件
<update id="updateSnameById" parameterType="Map" > update Student set sname = #{sname} where sid = #{sid} </update>
2.接口
public int updateSnameById(Map map);
3.test.java里
Map<String,String> map=new HashMap<String,String>(); map.put("sid","4"); map.put("sname","刘能"); System.out.println(mapper.updateSnameById(map)); sqlSession.commit();//
在接口里面该方法的参数前面加注解
1.接口
public int updateSnameById(@Param(value="sid")Integer sid,@Param(value="sname") String sname);
2.xml文件
<update id="updateSnameById" parameterType="com.tulun.maventest.pojo.Student" > update Student set sname = #{sname} where sid = #{sid} </update>
3.test.java
System.out.println(mapper.updateSnameById(4, "刘心晶")); sqlSession.commit();//事务
Map<String, Object> params = new HashMap<>(); List<Long> ids = new ArrayList<>(); Long donwCnt = 20L; params.put("ids", ids); params.put("downCnt", donwCnt); boolean result = userMapper.batchUpdateByIds(params);
boolean batchUpdateByIds(Map<String, Object> params) throws Exception;
Xml内容
<update id="batchUpdateByIds" parameterType="java.util.Map" > update user <set> down_cnt = #{downCnt} where id in <foreach collection="ids" index="index" item="item" open="(" separator="," close=")" > #{item} </foreach> </set> </update>
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。