1. 模糊查询
~~~
<select id="getUsersByName" parameterType="String" resultType="Userinfo">
select * from userinfo where name like "%"#{name}"%"
</select>
~~~
2. 参数为多个
2.1 以索引的方式
~~~
<select id="getUserByCondition" resultType="Userinfo">
select * from userinfo where username = #{0} and sex = #{1}
</select>
~~~
2.2 入参为map类型
~~~
<select id="getUsersByCondition2" parameterType="map" resultType="Userinfo">
select * from userinfo where name = #{name} and sex = #{sex}
</select>
~~~
2.3 入参为对象类型
~~~
<select id="getUsersByCondition" parameterType="Userinfo" resultType="Userinfo">
select * from userinfo where name = #{name} and sex = #{sex}
</select>
~~~
5. 插入操作
插入操作 - MySQL
~~~
<insert id="addUser" parameterType="Userinfo">
insert into userinfo values(null, #{name}, #{sex}, #{birthday},#{sal})
<selectKey keyProperty="id" order="AFTER" resultType="int">
select LAST_INSERT_ID()
</selectKey>
</insert>
~~~
插入操作 - Oracle
~~~
<insert id="addEnterprise" parameterType="com.neuedu.model.po.Enterprise">
insert into enterprise values(xx.nextval, #{name},#{videopath},#{introduction},#{jczs})
<selectKey keyProperty="qid" order="AFTER" resultType="int">
select xx.curval from dual
</selectKey>
</insert>
~~~
或者
~~~
<insert id="addEnterprise" parameterType="com.neuedu.model.po.Enterprise">
insert into enterprise values(xx.currval, #{name},#{videopath},#{introduction},#{jczs})
<selectKey keyProperty="qid" order="BEFORE" resultType="int">
select xx.nextval from dual
</selectKey>
</insert>
~~~
6. 更新操作
~~~
<update id="updateUser" parameterType="Userinfo">
update userinfo set name = #{name}, sex=#{sex}, birthday=#{birthday}, sal=#{sal} where id=#{id}
</update>
~~~
7. 删除操作
~~~
<delete id="deleteUser" parameterType="int">
delete from userinfo where id = #{id}
</delete>
~~~
注意:
1. MyBatis的事务不是自动提交的,对于增删改,需要提交事务,session.commit
2. MyBatis的事务控制
~~~
public static void addEnterprise()
{
//1. 得到一个SqlSession()
SqlSession session = DBUtils.getSession();
//2. 由sqlSession得到Mapper接口的实现类
EnterpriseMapper enterpriseMapper = session.getMapper(EnterpriseMapper.class);
SwiperMapper swiperMapper = session.getMapper(SwiperMapper.class);
//3. 创建一个lesson
try
{
//add enterprise
Enterprise item = new Enterprise();
item.setIntroduction("xxxx");
item.setJczs("xxx");
item.setName("xxx");
item.setVideopath("qqq");
enterpriseMapper.addEnterprise(item);
System.out.println(item.getQid());
Integer.parseInt("aa");
//add images
swiperMapper.addSwiper(item.getQid(),"AA.jpg","A");
swiperMapper.addSwiper(item.getQid(),"BB.jpg","A");
swiperMapper.addSwiper(item.getQid(),"CC.jpg","A");
//提交
session.commit();
}
catch(Exception e)
{
e.printStackTrace();
session.rollback();
}
finally
{
session.close();
}
}
~~~