mybatis学习第4天

1pagehelper分页

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

使用方式

1.在pom.xml 引入

<!--配置分页-->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>4.1.4</version>
</dependency>

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


    <plugins>
      <!--  <plugin interceptor="com.wgz.intercptor.MyInterceptor">
            <property name="param1" value="aaa"/>
            <property name="param1" value="bbb"/>
        </plugin>-->


            <!-- com.github.pagehelper为PageHelper类所在包名 -->
            <plugin interceptor="com.github.pagehelper.PageHelper">
                <!-- 使用MySQL方言的分页 -->
                <property name="helperDialect" value="sqlserver"/><!--如果使用mysql,这里value为mysql-->
                <property name="pageSizeZero" value="true"/>
            </plugin>

    </plugins>

3.使用

            //1.设置查询的页码和页数
            Page<Student> page= PageHelper.startPage(1, 2);

            //2.获取解惑
            List<Student> studentList =  iStudentDao2.findAllStudent();

            //3.获取总页码 对当前页码
            PageInfo<Student> 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.引入依赖

  <!-- mybatis-generator-core 反向生成java代码-->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.5</version>
        </dependency>

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

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
    <context id="DB2Tables" targetRuntime="MyBatis3">
        <commentGenerator>
            <!-- 是否去除自动生成的注释 -->
            <property name="suppressAllComments" value="false"/>
        </commentGenerator>
        <!-- Mysql数据库连接的信息:驱动类、连接地址、用户名、密码 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/szqy08"
                        userId="root"
                        password="123456">
        </jdbcConnection>
        <!-- Oracle数据库
            <jdbcConnection driverClass="oracle.jdbc.OracleDriver"
                connectionURL="jdbc:oracle:thin:@127.0.0.1:1521:yycg"
                userId="yycg"
                password="yycg">
            </jdbcConnection>
        -->

        <!-- 默认为false,把JDBC DECIMAL 和NUMERIC类型解析为Integer,为true时
        把JDBC DECIMAL 和NUMERIC类型解析为java.math.BigDecimal -->
        <javaTypeResolver >
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!-- targetProject:生成POJO类的位置 -->
        <javaModelGenerator targetPackage="com.wgz.entity" targetProject="src/main/java">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
            <!-- 从数据库返回的值被清理前后的空格 -->
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <!-- targetProject:mapper映射文件生成的位置 -->
        <sqlMapGenerator targetPackage="com.wgz.dao"  targetProject="src/main/resources">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>

        <!-- targetProject:mapper接口生成的的位置 -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.wgz.dao"  targetProject="src/main/java">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>

        <!-- 指定数据表 -->
        <table schema="" tableName="user"></table>


        <!-- 有些表的字段需要指定java类型
        <table schema="DB2ADMIN" tableName="ALLTYPES" domainObjectName="Customer" >
          <property name="useActualColumnNames" value="true"/>
          <generatedKey column="ID" sqlStatement="DB2" identity="true" />
          <columnOverride column="DATE_FIELD" property="startDate" />
          <ignoreColumn column="FRED" />
          <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" />
        </table> -->

    </context>
</generatorConfiguration>

主要修改一下标签

需要生成mapper对应的表

  <!-- 指定数据表 -->
        <table schema="" tableName="user"></table>

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<String> warnings = new ArrayList<String>();
        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<User> 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<User> 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("男");


            // 或者关系 or
            UserExample.Criteria criteria2 =  userExample.createCriteria();
            criteria2.andSexLike("%F%");
    
           // 将多个Criteria 组合在一起
            userExample.or(criteria2);

           List<User> 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.引入依赖

     <!--通用mapper-->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper</artifactId>
            <version>3.3.9</version>
        </dependency>

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;
    }

    @Override
    public 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 中获取 session
            SqlSession  session = sqlSessionFactory.openSession();
            //创建一个MapperHelper
            MapperHelper 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<Student2> 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值