myquery.java实现代码_mybatis单表操作实现完全java代码封装

之前在项目中用到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也实现了全封装的操作;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值