• spring的mybatis-puls 配置,增删改查操作,分页


    pom

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>zys_</groupId>
      <artifactId>mybatis_plus1</artifactId>
      <version>0.0.1-SNAPSHOT</version>
      
      <properties>
            <mybatisplus.version>3.2.0</mybatisplus.version>
            <spring.version>4.3.24.RELEASE</spring.version>
            <mysql.version>8.0.17</mysql.version>
            <!-- 注意只能使用2.0以下的版本 -->
            <log4j.version>1.2.17</log4j.version>
            <lombok.version>1.18.8</lombok.version>
        </properties>
      
      
      <dependencies>
                  <!-- spring配置 -->
            <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>${lombok.version}</version>
                <scope>provided</scope>
            </dependency>
    
            <!-- 引入spring -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aspects</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aop</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-core</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-expression</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-orm</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-tx</artifactId>
                <version>${spring.version}</version>
            </dependency>
    
            <!-- mysql数据库驱动 -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>${mysql.version}</version>
            </dependency>
            <!-- log4j -->
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>${log4j.version}</version>
            </dependency>
    
    
            <!-- 引入mp -->
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus</artifactId>
                <version>${mybatisplus.version}</version>
            </dependency>
    
        </dependencies>
    
      
    </project>

    配置

    driver=com.mysql.cj.jdbc.Driver
    url=jdbc:mysql://127.0.0.1:3306/test_demo?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=UTC
    user=root
    password=root
    <!-- dao层的配置:核心是要产生 Mapper代理类对象 1.引入数据库配置信息 2.数据源配置 3.SqlSessionFactory 
            4.产生Mapper接口的代理类对象 -->
        <!-- 1.引入数据库配置信息 -->
        <context:property-placeholder
            location="classpath:db.properties" system-properties-mode="FALLBACK" />
        <!--2.数据源配置 -->
        <bean id="dataSource"
            class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName" value="${driver}"></property>
            <property name="url" value="${url}"></property>
            <property name="username" value="${user}"></property>
            <property name="password" value="${password}"></property>
        </bean>
    
        <!-- 3.SqlSessionFactory -->
        <bean id="sqlSessionFactory"
            class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource"></property>
            
            <property name="globalConfig" ref="globalConfig"></property>
            <!-- 加载xxMapper.xml -->
            <property name="mapperLocations">
                <array>
                    <value>classpath:mapper/*Mapper.xml</value>
                </array>
            </property>
            <!-- 配置分页插件 -->
            <property name="plugins">
                <array>
                    <bean class="com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor">
                    </bean>
                </array>
            </property>
        </bean>
        <!-- 声明全局配置 -->
        <bean id="globalConfig" class="com.baomidou.mybatisplus.core.config.GlobalConfig">
            <!-- 指定主键自动增长类型 -->
            <property name="dbConfig" ref="dbConfig"></property>
        </bean>
        <bean id="dbConfig" class="com.baomidou.mybatisplus.core.config.GlobalConfig.DbConfig">
            <property name="idType" value="AUTO"></property>
        </bean>
        
        <!-- 4.产生Mapper接口的代理类对象 -->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <!-- 需要生成代理类对象的mapper接口包 -->
            <property name="basePackage"
                value="com.sxt.mapper"></property>
            <!-- sqlSessionFactory 的name 用于为代理类中生成SqlSession -->
            <property name="sqlSessionFactoryBeanName"
                value="sqlSessionFactory"></property>
        </bean>

    创建数据库

    提示:使用query5方法需要配置分页配置

    /**
     * mybatisplus的配置类
     * @author LJH
     *
     */
    @Configuration
    @ConditionalOnClass(value= {PaginationInterceptor.class})
    public class MybatisPlusConfig {
        
        @Bean
        public PaginationInterceptor  paginationInterceptor() {
            return new PaginationInterceptor();
        }
    
    }

    实体类

    import java.io.Serializable;
    import java.util.Date;
    
    import com.baomidou.mybatisplus.annotation.TableField;
    import com.baomidou.mybatisplus.annotation.TableId;
    import com.baomidou.mybatisplus.annotation.TableName;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    import lombok.ToString;
    
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @ToString
    @TableName(value="test_user")//建立User.class和数据的test_user表的关系
    public class User implements Serializable{
        
        /**
         * 
         */
        private static final long serialVersionUID = 1L;
        
        @TableId(value="id")  //代表它是主键
        private Integer id;
        private String name;
        private String pwd;
    }

    创建mapper接口

    public interface UserMapper extends BaseMapper<User>{
    
    }

    创建一个test类

    import java.io.Serializable;
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    import com.baomidou.mybatisplus.core.conditions.Wrapper;
    import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
    import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
    import com.baomidou.mybatisplus.core.metadata.IPage;
    import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
    import com.sxt.domain.User;
    import com.sxt.mapper.UserMapper;
    
    public class TestApp {
        
        
        public static void main(String[] args) {
            ApplicationContext context=new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
            UserMapper userMapper=context.getBean(UserMapper.class);
            User user = new User(1,"xiao","666");
    
            //插入
            //userMapper.insert(user);
    
            //更新
            //updateUser(userMapper);
            //删除
            //deleteUser(userMapper);
            //查询
            query1(userMapper);
            //c查询 返回user集合
            //query2(userMapper);
            //map的用法为and拼接  SELECT id,name,pwd FROM test_user WHERE name = ? AND pwd = ?
            //query3(userMapper);
            //模糊查询
    //        query4(userMapper,"xia");
    
    //        query5(userMapper);
    
            System.out.println("操作成功");
            
        }
        
        private static void query5(UserMapper userMapper) {
            IPage<User> page=new Page<>(1, 5);
            userMapper.selectPage(page, null);
            long total = page.getTotal();
            System.out.println("总条数:"+total);
            List<User> list = page.getRecords();
            print(list);
    
        }
    
        private static void query4(UserMapper userMapper,String name) {
    //        Integer count = userMapper.selectCount(null);
            QueryWrapper<User> queryWrapper=new QueryWrapper<>();
            //模糊查询  判断name不为空
            queryWrapper.like(name!=null, "name", name);
            Integer selectCount = userMapper.selectCount(queryWrapper);
            System.out.println(selectCount);
        }
    
        /**
         * 查询  map为and拼接条件
         * @param userMapper
         */
        private static void query3(UserMapper userMapper) {
            Map<String, Object> columnMap=new HashMap<>();
            columnMap.put("name", "xiao");
            columnMap.put("pwd", "q");
            List<User> list = userMapper.selectByMap(columnMap);
            print(list);
        }
    
    
    
        /**
         * 查询 返回user集合
         * @param userMapper
         */
        private static void query2(UserMapper userMapper) {
            Collection<Serializable> idList=new ArrayList<Serializable>();
            idList.add(2);
            idList.add(3);
            idList.add(4);
            List<User> list = userMapper.selectBatchIds(idList);
            print(list);
        }
        /**
         * 查询
         * @param userMapper
         */
        private static void query1(UserMapper userMapper) {
            User user = userMapper.selectById(2);
            System.out.println(user);
        }
    
        /**
         * 删除用户
         * @param userMapper
         */
        private static void deleteUser(UserMapper userMapper) {
    //        userMapper.deleteById(1);//根据主键删除
            //批量删除
    //        Collection<Serializable> idList=new ArrayList<Serializable>();
    //        idList.add(2);
    //        idList.add(3);
    //        userMapper.deleteBatchIds(idList);
            //批量and删除
    //        Map<String, Object> columnMap=new HashMap<String, Object>();
    //        columnMap.put("id", 6);
    //        columnMap.put("name", "666");
    //        userMapper.deleteByMap(columnMap);
            //区间删除
            QueryWrapper<User> wrapper=new QueryWrapper<>();
            wrapper.between("id", 1, 3);
            userMapper.delete(wrapper);
    
        }
    
        /**
         * 修改
         * @param userMapper
         */
        private static void updateUser(UserMapper userMapper) {
            //userMapper.updateById(new User(1, "q", "q"));//根据主键修改
            UpdateWrapper<User> updateWrapper=new UpdateWrapper<>();
    //        updateWrapper.eq("id", 1);  //sql  ===where id=1
    //        updateWrapper.between("id", 1, 3);
    //        userMapper.update(new User(1, "q", "q"), updateWrapper);
        }
    
        private static void print(List<User> list) {
            for (User user : list) {
                System.out.println(user);
            }
        }
    
    }
  • 相关阅读:
    Sql Server Report 导出到EXCEL 指定行高
    SQLSqlserver中如何将一列数据,不重复的拼接成一个字符串
    SQL Server Management Studio无法记住密码
    nuget.org无法解析的办法
    js获取select标签选中的值及文本
    Word 如何实现表格快速一分为二
    sql server rdl report 如何用动态sql
    浏览器窗口刷新
    SWFUpload 在ie9上出现的bug
    历数PC发展史上的祖先们
  • 原文地址:https://www.cnblogs.com/xiaozhang666/p/12068608.html
Copyright © 2020-2023  润新知