使用SqlSession封装的一些方法可以完成crud操作,但是SqlSession封装的方法,传递的参数statement, 传递占位符的参数只能传递一个。而且他的方法名称都是固定。而真实在开发环境下我们不使用SqlSession封装的方法,而是习惯自己定义方法,自己调用自己的方法。
1.如何实现
(1.1)创建dao接口并定义自己需要的方法
(1.2)创建映射文件
注意: namespace必须和dao接口一样,而且标签的id必须和你接口的方法名一样 。
(1.3) 测试
public void testfindone() throws Exception {
Reader reader = Resources.getResourceAsReader("mybatis.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = factory.openSession();
//UserDao是接口不能实例化,所以用相应接口的代理对象
UserDao userDao = session.getMapper(UserDao.class);
User findone = userDao.findone(26);
System.out.println(findone);
session.commit();
session.close();
}
2.接口中定义的方法传递多个参数
我们需要在参数处使用@Param()为参数起名
3.添加时如何返回递增的主键值。
<insert id="adduser" useGeneratedKeys="true" keyProperty="u_id">
insert into user values(null,#{u_username},#{u_password},#{u_name})
</insert>
useGeneratedKeys:设置使用生成的主键改为true(默认false)
keyProperty: 赋值给哪个属性(根据自己实体类的字段名赋值)
4.解决列名和实体类属性名不一致。
第一种: 使用resultMap完成列和属性之间的映射关系。
<resultMap id="myuser" type="User">
<id column="id" property="u_id"/>
<!--
id:指定主键列的封装规则(主键也可以使用result来定义)
column:指定哪一列
property:指定对应的javaBean属性
-->
<!--
result:定义普通列封装规则
-->
<result column="username" property="u_username"/>
<result column="password" property="u_password"/>
<result column="name" property="u_name"/>
</resultMap>
<!--resultType和ResultMap二者只能用一个-->
<select id="findone" resultMap="myuser">
select * from user where id=#{id}
</select>
第二种:为列名起别名
<select id="findOne" resultType="User">
select stu_id id,stu_name name,stu_age age from tb_stu where stu_id=#{id}
</select>
5.动态sql
dao中定义的方法
public List<User> findByCondition(@Param("id") Integer id,@Param("username") String
username,@Param("password") Integer password,@Param("name") String name
)
映射文件中对应的查询方法
<select id="findByCondition" resultMap="myuser">
select * from user
/*where 1=1*/
<where>
<if test="id!=null and id>0">
and id=#{id}
</if>
<if test="username!=null and username!=''">
and username=#{username}
</if>
<if test="password!=null">
and password=#{password}
</if>
<if test="name!=null">
and name=#{name}
</if>
</where>
</select>
可以把代码中的where双标签去掉该成 where 1=1
如果不使用where 1=1 那么你的动态sql可能会出错。 那么我们就可以使用where标签,作用:可以自动为你添加where关键字,并且可以帮你去除第一个and |or
代码运行结果: