mybatis学习第4天

1pagehelper分页

pagehelper是由刘增辉开发的一个分页插件,支持多种数据库,号称最方便使用的分页插件。分页插件支持任何复杂的单表、多表分页。

使用方式

1.在pom.xml 引入


com.github.pagehelperpagehelper4.1.4

2.在mybatis的配置文件sqlMapConfig.xml配置插件


3.使用

            //1.设置查询的页码和页数Page page= PageHelper.startPage(1, 2);//2.获取解惑List studentList =  iStudentDao2.findAllStudent();//3.获取总页码 对当前页码PageInfo pageinfo=new PageInfo(studentList);System.out.println("pageinfo总条数:"+pageinfo.getTotal());System.out.println("pageinfo每页的记录数:"+pageinfo.getPageSize());System.out.println("pageinfo总页码:"+pageinfo.getPageNum());System.out.println("pageinfo总页码:"+pageinfo.getPages());for (Student student:studentList){System.out.println("student:"+student);}

2.逆向工程MyBatis Generator

MyBatis Generator:简称MBG,是一个专门为MyBatis框架使用者定制的代码生成器,可以快速的根据表生成对应的映射文件,接口,以及bean类。支持基本的增删改查,以及QBC风格的条件查询。但是表连接、 存储过程等这些复杂sql的定义需要我们手工编写。

简单来说就是帮助我们生成实体类,mapper.xml,接口

使用

1.引入依赖

  org.mybatis.generatormybatis-generator-core1.3.5

2.创建生成mapper的配置文件generatorConfig.xml


主要修改一下标签

需要生成mapper对应的表

  

3.生成mapper

public class MybatisGeneratorUtil {public static void main(String[] args) throws IOException, XMLParserException, InvalidConfigurationException, SQLException, InterruptedException {//如果这里出现空指针,直接写绝对路径即可。String genCfg = "C:\\Users\\Admin\\Desktop\\假期\\mybatis\\mybatis04\\mybatis04\\src\\main\\resources\\generatorConfig.xml";List warnings = new ArrayList();boolean overwrite = true;// 指定配置文件File configFile = new File(genCfg);ConfigurationParser cp = new ConfigurationParser(warnings);Configuration config = cp.parseConfiguration(configFile);DefaultShellCallback callback = new DefaultShellCallback(overwrite);MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);myBatisGenerator.generate(null);}}

4使用

  • 简单使用
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);User user =  userMapper.selectByPrimaryKey(1);System.out.println("user:"+user);
  • 高级用法

可以使用 UserExample完成一些定制化的查询

            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);UserExample userExample = new UserExample();// 设置去重userExample.setDistinct(true);// 设置按照名称排序userExample.setOrderByClause("username");List users =  userMapper.selectByExample(userExample);for (User user:users){System.out.println("user:"+user.getUsername());}
  • 通过UserExample.Criteria 生成&的条件查询

相当于 select * from demo WHERE a = ? and b = ?

            UserExample userExample = new UserExample();UserExample.Criteria criteria =  userExample.createCriteria();// 两者为&的条件criteria.andUsernameLike("%user%").andSexEqualTo("男");List users =  userMapper.selectByExample(userExample);for (User user:users){System.out.println("user:"+user.getUsername());}
  • 可以使用多个UserExample.Criteria 完成|的查询

相当于 select count(*) from demo WHERE ( a = ? and b = ? ) or ( a = ? and c = ? )

            UserExample userExample = new UserExample();UserExample.Criteria criteria =  userExample.createCriteria();// 两者为&的条件criteria.andUsernameLike("%user%").andSexEqualTo("男");// 或者关系 orUserExample.Criteria criteria2 =  userExample.createCriteria();criteria2.andSexLike("%F%");// 将多个Criteria 组合在一起userExample.or(criteria2);List users =  userMapper.selectByExample(userExample);for (User user:users){System.out.println("user:"+user.getUsername());}

5updateByPrimaryKeySelective和updateByPrimaryKey的用法区别?

  • updateByPrimaryKeySelective(Object obj)
    updateByPrimaryKeySelective 接收的参数为对应于数据库的实体类对象,利用字段的自动匹配进行更新表的操作,如果传入obj对象中的某个属性值为null,则不进行数据库对应字段的更新。
  • updateByPrimaryKey(Object obj)
    与updateByPrimaryKeySelective的区别在于,如果传入的obj对象中某个属性值为null,会将对应的数据库字段赋值为null。

测试

           User user = new User();user.setId(1);user.setUsername("xiaomingaaa");// 此时示例中的null 空值不会 数据库中对应以有的字段覆盖userMapper.updateByPrimaryKeySelective(user);// 此时示例中的null 空值会把 数据库中对应以有的字段覆盖//userMapper.updateByPrimaryKey(user);

3.通用mapper

Mapper是刘增辉开发的一个分页插件开发一个通用的插件功能和MyBatis Generator类似,

通用Mapper都可以极大的方便开发人员。可以随意的按照自己的需要选择通用方法,还可以很方便的开发自己的通用方法。

极其方便的使用MyBatis单表的增删改查。

支持单表操作,不支持通用的多表联合查询。

通用 Mapper 支持 Mybatis-3.2.4 及以上版本。

使用

1.引入依赖

     tk.mybatismapper3.3.9

2.编写对应的实体类

/*** 学生实体类 与 student_tb一一对应*/@Table(name = "student_tb")
public class Student2 implements Serializable {@Id@GeneratedValue(generator = "JDBC")private int id;@Column(name="name")private String studentName;private String sex;private int age;private float height;private Date birthday;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return studentName;}public void setName(String name) {this.studentName = name;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public float getHeight() {return height;}public void setHeight(float height) {this.height = height;}public Date getBirthday() {return birthday;}public void setBirthday(Date birthday) {this.birthday = birthday;}@Overridepublic String toString() {return "Student{" +"id=" + id +", name='" + studentName + '\'' +", sex='" + sex + '\'' +", age=" + age +", height=" + height +", birthday=" + birthday +'}';}
}

@NameStyle(value = Style.normal)

normal,                     //原值
camelhump,                  //驼峰转下划线
uppercase,                  //转换为大写
lowercase,                  //转换为小写
camelhumpAndUppercase,      //驼峰转下划线大写形式
camelhumpAndLowercase,      //驼峰转下划线小写形式

@Table(name = "student_tb"):标记实体类对应得表名称

@Id @GeneratedValue(generator = "JDBC"):标记为主键,并且自增

@Column(name="name") 标记 当表字段与java字段不一致也不符合驼峰写法的映射

@Transient 表明不是数据表中的字段

参考:https://github.com/abel533/Mapper/wiki/2.2-mapping

测试

 public static void main(String[] args) {// 1.读取配置文件InputStream in = null;try {in = Resources.getResourceAsStream("sqlMapConfig.xml");// 2.创建session工厂SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(in);//从刚刚创建的 sqlSessionFactory 中获取 sessionSqlSession  session = sqlSessionFactory.openSession();//创建一个MapperHelperMapperHelper mapperHelper = new MapperHelper();mapperHelper.processConfiguration(session.getConfiguration());StudentMapperDao studentMapperDao =   session.getMapper(StudentMapperDao.class);// 查询所有学生studentMapperDao.selectAll();// 也支持多条件查询Example example = new Example(Student2.class);example.createCriteria().andLike("name","%an%");List studentList =  studentMapperDao.selectByExample(example);for (Student2 student2:studentList){System.out.println("student:"+student2);}} catch (IOException e) {e.printStackTrace();}}

生成genreate

https://www.jianshu.com/p/2cace13b7819

https://www.cnblogs.com/alice-cj/p/10482722.html

https://blog.csdn.net/huyiju/article/details/82454735

distinct字段用于指定DISTINCT查询。

    orderByClause字段用于指定ORDER BY条件,这个条件没有构造方法,直接通过传递字符串值指定。oredCriteria字段用于自定义查询条件。这个类是专门用来对这个单表来查询的类,对该单表的CURD操作是脱离sql性质的(已经通过逆向工程生成相应的sql),直接在service层就可以完成相应操作。逆向工程生成的文件XxxExample.java中包含一个static 的内部类 Criteria ,在Criteria中有很多方法,主要是定义SQL 语句where后的查询条件。

————————————————
版权声明:本文为CSDN博主「编程小透明」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/Nerver_77/article/details/79707190

https://blog.csdn.net/Nerver_77/article/details/79707190

https://www.cnblogs.com/kaixinyufeng/p/8329954.html

https://www.iteye.com/blog/shuzheng5201314-2253461

通过用mapper

https://github.com/abel533/Mapper/wiki/1.1-java


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部