之前在项目中用到mybtis操作数据库时都是手动写sql,对于我这种sql水平不是很好地人来说痛苦死了;动态查询的sql我表示到现在还不会写呀!
还好,利用数据库表反向生成的工具可以帮我解决大部分的sql;(mybatis generator 你懂的)
首先利用反向生成可以帮我们自动生成实体类,dao接口,dao映射文件;
在dao映射文件如下所示:
and ${criterion.condition}
and ${criterion.condition} #{criterion.value}
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
and ${criterion.condition}
#{listItem}
and ${criterion.condition}
and ${criterion.condition} #{criterion.value}
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
and ${criterion.condition}
#{listItem}
id, name, password
select
distinct
from user
order by ${orderByClause}
select
from user
where id = #{id,jdbcType=VARCHAR}
delete from user
where id = #{id,jdbcType=VARCHAR}
delete from user
insert into user (id, name, password
)
values (#{id,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}
)
insert into user
id,
name,
password,
#{id,jdbcType=VARCHAR},
#{name,jdbcType=VARCHAR},
#{password,jdbcType=VARCHAR},
select count(*) from user
update user
id = #{record.id,jdbcType=VARCHAR},
name = #{record.name,jdbcType=VARCHAR},
password = #{record.password,jdbcType=VARCHAR},
update user
set id = #{record.id,jdbcType=VARCHAR},
name = #{record.name,jdbcType=VARCHAR},
password = #{record.password,jdbcType=VARCHAR}
update user
name = #{name,jdbcType=VARCHAR},
password = #{password,jdbcType=VARCHAR},
where id = #{id,jdbcType=VARCHAR}
update user
set name = #{name,jdbcType=VARCHAR},
password = #{password,jdbcType=VARCHAR}
where id = #{id,jdbcType=VARCHAR}
用这些生成的sql语句基本上可以解决我们单表查询中的所有情景;而不必我们再去手写sql(太操蛋了),是不是有点回到另外一个大框架中了呀;
例如:
我要新增客户:
那么在service层的代码就可以这么写:
@Override
public void saveUser(User record) {
userMapper.insert(record);
}
直接用反向生成的insert方法来进行插入;
你可能会觉得没什么太多意思:这种sql语句太容易写了;
那么查询呢?根据条件查询,条件比较多得情况下呢?更新,需要动态更新呢?
查询:
@Override
public List queryUserByName(String name) {
UserExample example=new UserExample();
example.createCriteria().andNameEqualTo(name); //我只需要在这里添加查询条件即可,添加的查询条件有很多可供选择的;Criteria这个对象是不是很熟悉呀!
List users = userMapper.selectByExample(example);
return users;
}
这样就将根据姓名查询的服务写好了,还可以有like,between等多种方法可以供选择;
更新:
有时候表单提交上来的数据不是很完整,更新需要写动态sql以防止数据库的数据被更新成null;
现在我们可以这样操作:
@Override
public void updateById(User user,String id) {
UserExample example=new UserExample();
example.createCriteria().andIdEqualTo(id);
userMapper.updateByExampleSelective(user, example);
}
动态sql已经反向生成好了,我们只需要将需要更新的条件封装到example类中即可;
当然,多表关联暂时还无法这么使用,关于多表关联可以关注我的另外一篇博文;
这样,是不是mybatis也实现了全封装的操作;