MyBatis的基本增删改查及条件操作及main方法调用

来源:互联网 发布:知乎手机怎么发文章 编辑:程序博客网 时间:2024/04/27 22:36

namespace="com.dao.StudentDao"

1.基本增删改查:

(1)增加:

<insert id="insertStudent" parameterType="student" keyProperty="id" useGeneratedKeys="true">

insert into student(age,name) values(#{age},#{name})

</insert>


(2)删除:

<delete id="delStudent" parameterType="int">
delete from student where id=#{id}
</delete>


(3)修改:

<update id="updateStudent3" parameterType="student">
update student set name=#{name},age=#{age} where id=#{id}
</update>


(4)查询:

<select id="selStudent" resultType="student">
select id,age,name from student
</select>

2.条件操作:

(1)动态SQL引用:

<sql id="condition">
<where>
<if test="id!=null and id!=0">
and id=#{id}
</if>
<if test="name!=null and name!=''">
and name like #{name}
</if>
<if test="age!=null and age!=0">
age=#{age}
</if>
</where>
</sql>


<select id="selStudent3" resultType="student" parameterType="student">
select id,name,age from student <include refid="condition"/>
</select>


(2).trim动态条件查询 (注意:前缀后缀)

<select id="selStudent4" resultType="student" parameterType="student">
select id,name,age from student
<trim prefix="where" prefixOverrides="and |or">
<if test="id!=null and id!=0">
id=#{id}
</if>
<if test="age!=null and age!=0">
age=#{age}
</if>
<if test="name!=null and name!=''">
name=#{name}
</if>
</trim>
</select>


(3)foreach子句 (IN)

<select id="selStudent5" resultType="student">
select id,name,age from student where id in
<foreach collection="list" item="item" index="index" open="(" separator="," close=")">
#{item}
</foreach>
</select>


(4)set动态条件修改

<update id="updateStudent" parameterType="student">
update student
<set>
<if test="name!=null and name!=''">name=#{name},</if>
<if test="age!=null and age!=0">age=#{age},</if>
</set>
where id=#{id}
</update>


(5)trim动态条件修改

<update id="updateStudent2" parameterType="student">
update student
<trim prefix="set" suffixOverrides=",">
<if test="name!=null and name!=''">name=#{name},</if>
<if test="age!=null and age!=0">age=#{age},</if>
</trim>
where id=#{id}
</update>



两种调用方式:

String resource="mybatis-config.xml";

InputStream is = Resources.getResourceAsStream(resource);

factory = new SqlSessionFactoryBuilder().build(is);

SqlSession session = factory.openSession();

//第一种

//List<Student> list = session.selectList("com.dao.StudentDao.selStudent");

//第二种(注意:与StudentDao接口方法对应起来)

StudentDao sd = session.getMapper(StudentDao.class);



0 0
原创粉丝点击