【框架篇】Mybatis的内置方法,撸代码更快捷~~
作者:互联网
掌握内置方法,在撸代码的过程中就可以让我们的代码更加简洁优雅,提高我们的开发效率,以下是我在日常开发中常用的方法,希望能帮助到大家,话不多说,直接上Demo~~~
一、insert ---------------- 新增
People people= new People();
people.setId("001");
people.setAge("18");
people.setName("xianYu");
peopleDAO.insert (people);
相当于:insert into people(id, age, name) values (‘001’, ‘18’, ‘xianYu’);
二、updateByPrimaryKey ---------------- 根据主键ID更新
People people= new People();
people.setId("001");
people.setAge("20");
people.setName("chouXianYu");
peopleDAO.updateByPrimaryKey(people);
相当于update people set age = ‘20’, name = ‘chouXianYu’ where id = ‘001’
三、selectByPrimaryKey ---------------- 根据主键ID查询
People people = new People();
people = peopleDAO.selectByPrimaryKey("001");
相当于select * form people where id = ‘001’;
四、selectByExample ---------------- 根据条件查询返回列表
Example exampl = new Example (People.class);
Criteria = criteria = exampl .createCriteria();
criteria.andNameEqualTo("xianYu");
criteria.andAgeIsNull();
exampl.setOrderByClause("name asc, age desc");
List<People> people = peopleDAO.selectByExample(exampl);
相当于:select * from people where name = ‘xianYu’ and age is null order by name asc,age desc;
当然在日常撸代码的时候我还是喜欢下面这种写法,各位看官也可以比较比较:
Example exampl = new Example (People.class);
Criteria = criteria = exampl .createCriteria();
criteria.andEqualTo("name","xianYu").andEqualTo("age","18");
List<People> people = peopleDAO.selectByExample(exampl);
相当于:select * from people where name = ‘xianYu’ and age = ‘18’;
Note:在iBator 生成的文件Example.java中包含一个static 的内部类 Criteria ,在Criteria中有很多方法,主要是定义SQL 语句where后的查询条件。
五、selectOne ---------------- 根据条件查询返回对象
People people = new People();
people.setName("xianYu");
people.setAge("18");
people = peopleDAO.selectOne(people);
相当于:select * from people where name = ‘xianYu’ and age = ‘18’;
Note: selectOne方法在使用的时候一定要对查询出的对象做盼空
六、countByExample ---------------->根据条件数量
Example exampl = new Example (People.class);
Criteria = criteria = exampl .createCriteria();
criteria.andNameEqualTo("xianYu");
int count = peopleDAO.countByExample(exampl);
相当于:select count(*) from people where name = ‘xianYu’;
标签:内置,name,People,age,people,xianYu,exampl,快捷,Mybatis 来源: https://blog.csdn.net/weixin_42777004/article/details/106635807