Intellij IDEA Spring Boot (10) 集成mybatis以及分页

        今天又花了点时间研究了mybatis。 研究了mybatis如何使用 通用mapper,如何分页查询,如何与ehcache集成缓存。

    直接进入主题啦。

    pom依赖

   


   org.mybatis.spring.boot
   mybatis-spring-boot-starter
   1.1.1



   tk.mybatis
   mapper
   3.4.3


   com.github.pagehelper
   pagehelper
   4.2.1


   org.springframework.boot
   spring-boot-starter-cache




   net.sf.ehcache
   ehcache
我对于创建数据库的表,又懒了。所以我希望依赖hibernate的自动建表功能。可选操作啊。


   org.springframework.boot
   spring-boot-starter-data-jpa
其它的pom依赖我也补上吧


   mysql
   mysql-connector-java
   runtime



   org.springframework.boot
   spring-boot-devtools
   true
   true



   com.alibaba
   druid
   1.0.31

   org.springframework.boot
   spring-boot-starter-web

   org.springframework.boot
   spring-boot-starter-test
   test

   
      alimaven
      http://maven.aliyun.com/nexus/content/groups/public/
      
         true
      
      
         true
      
   



   
      alimaven
      http://maven.aliyun.com/nexus/content/groups/public/
      
         true
      
      
         true
      
   

这里忘记说一个重要的事情,就是分页插件的版本,一定要用4.x.x的版本,不要使用5,也不要使用3。我目前使用的是4的最高版本。我实验过了,5的办法,分页似乎有问题,不对劲。只有4的正确。


接下来讲配置:

package com.dashuai.mybatisboot.config;

import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class DruidConfig {

    @Bean
    public ServletRegistrationBean druidStatView() {
        ServletRegistrationBean registration = new ServletRegistrationBean(new StatViewServlet());
        registration.addUrlMappings("/druid/*");
        return registration;
    }

    @Bean
    public FilterRegistrationBean druidWebStatFilter() {
        FilterRegistrationBean registration = new FilterRegistrationBean(new WebStatFilter());
        registration.addInitParameter("exclusions","/css/*,/style/*,/js/*,*.js,*.css,/druid*,/attached/*,*.jsp");
        registration.addInitParameter("principalSessionName","sessionUser");
        registration.addInitParameter("profileEnable","true");
        registration.addUrlPatterns("/*");
        registration.setOrder(1);
        return registration;
    }
}
package com.dashuai.mybatisboot.config;

import com.github.pagehelper.PageHelper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import tk.mybatis.spring.mapper.MapperScannerConfigurer;

import java.util.Properties;

@Configuration
public class MyBatisConfig {

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
        mapperScannerConfigurer.setBasePackage("com.dashuai.mybatisboot.mapper");//扫描该路径下的dao
        Properties properties = new Properties();
        properties.setProperty("mappers", "com.dashuai.mybatisboot.mybatisbase.MyBaseMapper");//通用dao
        properties.setProperty("notEmpty", "false");
        properties.setProperty("IDENTITY", "MYSQL");
        mapperScannerConfigurer.setProperties(properties);
        return mapperScannerConfigurer;
    }

    @Bean
    public PageHelper pageHelper() {
        PageHelper pageHelper = new PageHelper();
        Properties p = new Properties();
        p.setProperty("offsetAsPageNum", "true");
        p.setProperty("rowBoundsWithCount", "true");
        p.setProperty("reasonable", "true");
        pageHelper.setProperties(p);
        return pageHelper;
    }

}


package com.dashuai.mybatisboot.mybatisbase;

import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;

/**
 * 这个MyBaseMapper 不要放在mapper包下,该类不能被当做普通Mapper一样被扫描,否则会出错。
 * 出的错是: sun.reflect.generics.reflectiveObjects.TypeVariableImpl cannot be cast to java.lang.Class
 * @param 
 */
public interface MyBaseMapper extends Mapper,MySqlMapper{

}

application.properties的配置


#log
logging.level.root=info
logging.level.com.dashuai.mybatisboot=debug
#logging.level.org.hibernate.cache=DEBUG
#logging.level.org.springframework=debug
logging.file=mylog.log

#mysql
spring.datasource.driver-class-name= com.mysql.jdbc.Driver
spring.datasource.url=jdbc\:mysql\://localhost\:3306/mybatis?useUnicode\=true&characterEncoding\=UTF-8
spring.datasource.username=root
spring.datasource.password=123456

#druid
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.filters=stat
spring.datasource.maxActive= 20
spring.datasource.initialSize= 1
spring.datasource.maxWait= 60000
spring.datasource.minIdle =1
spring.datasource.timeBetweenEvictionRunsMillis= 60000
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery= select 'x'
spring.datasource.testWhileIdle= true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn= false
spring.datasource.poolPreparedStatements=true
spring.datasource.maxOpenPreparedStatements= 20

# 自动创表
spring.jpa.database=mysql
spring.jpa.hibernate.ddl-auto=update

# ehcache的配置
spring.cache.type=ehcache
spring.cache.ehcache.config=classpath:ehcache.xml



    
    
    
    
    

    



 
  
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@EnableTransactionManagement
@SpringBootApplication
@EnableCaching
public class MybatisbootApplication {

   public static void main(String[] args) {
      SpringApplication.run(MybatisbootApplication.class, args);
   }
}

package com.dashuai.mybatisboot.entity;

import com.fasterxml.jackson.annotation.JsonFormat;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
import java.util.Date;

@Entity
@Table(name="tb_user")
public class User implements Serializable {

    @Id
    private String uuid; // 表主键
    @Column
    private String username; // 登录用户名
    @Column
    private String password; // 登录密码
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @Column
    private Date registerDate;
    @Column
    private Integer status; // 账号状态: 0:正常;1:禁用

    public String getUuid() {
        return uuid;
    }

    public void setUuid(String uuid) {
        this.uuid = uuid;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Date getRegisterDate() {
        return registerDate;
    }

    public void setRegisterDate(Date registerDate) {
        this.registerDate = registerDate;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    @Override
    public String toString() {
        return "\nUser [uuid=" + uuid + ", username=" + username + ", password=" + password + ", registerDate="
                + registerDate + ", status=" + status + "]\n";
    }


}

package com.dashuai.mybatisboot.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;

@Entity
@Table(name="tb_role")
public class Role implements Serializable {

    @Id
    private String uuid; // 表主键
    @Column
    private String roleName; // 角色名
    @Column
    private String roleDesc; // 角色描述

    public String getUuid() {
        return uuid;
    }

    public void setUuid(String uuid) {
        this.uuid = uuid;
    }

    public String getRoleName() {
        return roleName;
    }

    public void setRoleName(String roleName) {
        this.roleName = roleName;
    }

    public String getRoleDesc() {
        return roleDesc;
    }

    public void setRoleDesc(String roleDesc) {
        this.roleDesc = roleDesc;
    }


}
package com.dashuai.mybatisboot.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;

@Entity
@Table(name="tb_user_role")
public class UserRole implements Serializable {
    @Id
    private String uuid; // 表主键
    @Column
    private String userId;
    @Column
    private String roleId;

    public String getUuid() {
        return uuid;
    }

    public void setUuid(String uuid) {
        this.uuid = uuid;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getRoleId() {
        return roleId;
    }

    public void setRoleId(String roleId) {
        this.roleId = roleId;
    }

}

package com.dashuai.mybatisboot.mapper;

import com.dashuai.mybatisboot.entity.User;
import com.dashuai.mybatisboot.mybatisbase.MyBaseMapper;

public interface UserMapper extends MyBaseMapper {

}

package com.dashuai.mybatisboot.mapper;

import com.dashuai.mybatisboot.entity.Role;
import com.dashuai.mybatisboot.mybatisbase.MyBaseMapper;

public interface RoleMapper extends MyBaseMapper{


}

package com.dashuai.mybatisboot.entity;

import java.util.Map;

public class MyPager {

    int page;
    int rows;

    Map params;

    public MyPager(int page, int rows, Map params) {
        this.page = page;
        this.rows = rows;
        this.params = params;
    }

    public int getPage() {
        if(page<1){
            page=1;
        }
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public int getRows() {
        if(rows<1){
            rows=1;
        }
        return rows;
    }

    public void setRows(int rows) {
        this.rows = rows;
    }

    public Map getParams() {
        return params;
    }

    public void setParams(Map params) {
        this.params = params;
    }
}

package com.dashuai.mybatisboot.entity.dto;

/**
 * 根据用户Id 查询出 role实体类
 */
public class DtoUserRole {

    private String userId; // 为null就是没有拥有角色。
    private String roleId;
    private String roleName;
    private String roleDesc;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getRoleId() {
        return roleId;
    }

    public void setRoleId(String roleId) {
        this.roleId = roleId;
    }

    public String getRoleName() {
        return roleName;
    }

    public void setRoleName(String roleName) {
        this.roleName = roleName;
    }

    public String getRoleDesc() {
        return roleDesc;
    }

    public void setRoleDesc(String roleDesc) {
        this.roleDesc = roleDesc;
    }

    @Override
    public String toString() {
        return "\nDtoUserRole{" +
                "\nuserId='" + userId + '\'' +
                "\n, roleId='" + roleId + '\'' +
                "\n, roleName='" + roleName + '\'' +
                "\n, roleDesc='" + roleDesc + '\'' +
                '}';
    }

}

package com.dashuai.mybatisboot.service;

import com.dashuai.mybatisboot.entity.MyPager;
import com.dashuai.mybatisboot.entity.User;
import com.github.pagehelper.PageInfo;

import java.util.List;

public interface UserService {

    User saveUser(User user);

    User getUserByUsername(String username);

    void deleteUserByUUID(String uuid);

    void updateUser(User user);

    List getAllUsers();

    PageInfo getPageUsers(MyPager pager);


}


package com.dashuai.mybatisboot.service;

import com.dashuai.mybatisboot.entity.Role;

public interface RoleService {

     Role saveRole(Role role);

     Role findRoleByName(String name);


}

package com.dashuai.mybatisboot.service;

import com.dashuai.mybatisboot.entity.MyPager;
import com.dashuai.mybatisboot.entity.User;
import com.dashuai.mybatisboot.entity.UserRole;
import com.dashuai.mybatisboot.entity.dto.DtoUserRole;
import com.github.pagehelper.PageInfo;

import java.util.List;

public interface UserRoleService {

    public void saveUserRole(UserRole userRole);

    List getUserHasAndNotHasRoles(String userId);

    List getUserHasRoles(String userId);

    List getUserByRoleName(String rolename);

    PageInfo getUserPageByRoleName(MyPager pager, String rolename);

}

package com.dashuai.mybatisboot.service.impl;

import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.dashuai.mybatisboot.entity.MyPager;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dashuai.mybatisboot.entity.User;
import com.dashuai.mybatisboot.mapper.UserMapper;
import com.dashuai.mybatisboot.service.UserService;
import tk.mybatis.mapper.entity.Example;

@Service("userService")
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper UserMapper;

    @Override
    public User saveUser(User user) {
        user.setUuid(UUID.randomUUID().toString().replace("-", ""));
        UserMapper.insert(user);
        return user;
    }

    @Transactional(readOnly = true)
    @Override
    public User getUserByUsername(String username) {
        Example example = new Example(User.class);
        example.createCriteria().andEqualTo("username", username);
        List list = UserMapper.selectByExample(example);
        if (null != list && !list.isEmpty()) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public void deleteUserByUUID(String uuid) {
        UserMapper.deleteByPrimaryKey(uuid);
    }

    @Override
    public void updateUser(User user) {
        UserMapper.updateByPrimaryKey(user);
    }

    @Cacheable(cacheNames = "cache_user")
    @Transactional(readOnly = true)
    @Override
    public List getAllUsers() {
        return UserMapper.selectAll();
    }

    @Transactional(readOnly = true)
    @Override
    public PageInfo getPageUsers(MyPager pager) {
        Example example = new Example(User.class);
        Map params = pager.getParams();
        if (null != params && !params.isEmpty()) {
            Example.Criteria criteria = example.createCriteria();
            if (params.containsKey("username")) {
                criteria.andLike("username", "%" + params.get("username") + "%");
            }
            if (params.containsKey("status")) {
                criteria.andEqualTo("status", params.get("status"));
            }
            if (params.containsKey("registerDate")) {
                criteria.andGreaterThan("registerDate", params.get("registerDate"));
            }
        }
        //PageHelper.startPage(pager.getPage(),pager.getRows());
        PageHelper.startPage(pager.getPage(), pager.getRows(), "register_date desc");
        List list = UserMapper.selectByExample(example);
        PageInfo pageInfo = new PageInfo<>(list);

        return pageInfo;
    }


}

package com.dashuai.mybatisboot.service.impl;

import com.dashuai.mybatisboot.entity.Role;
import com.dashuai.mybatisboot.mapper.RoleMapper;
import com.dashuai.mybatisboot.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.UUID;

@Transactional
@Service("roleService")
public class RoleServiceImpl implements RoleService {

    @Autowired
    RoleMapper RoleMapper;

    @Override
    public Role saveRole(Role role) {
        role.setUuid(UUID.randomUUID().toString().replace("-",""));
        RoleMapper.insert(role);
        return role;
    }

    @Transactional(readOnly = true)
    @Override
    public Role findRoleByName(String name) {

        Example example = new Example(Role.class);
        example.createCriteria().andEqualTo("roleName",name);
        List list= RoleMapper.selectByExample(example);
        if(null!=list&&!list.isEmpty()){
            return list.get(0);
        }
        return null;
    }
}

package com.dashuai.mybatisboot.service.impl;

import com.dashuai.mybatisboot.entity.MyPager;
import com.dashuai.mybatisboot.entity.User;
import com.dashuai.mybatisboot.entity.UserRole;
import com.dashuai.mybatisboot.entity.dto.DtoUserRole;
import com.dashuai.mybatisboot.mapper.UserRoleMapper;
import com.dashuai.mybatisboot.service.UserRoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.UUID;

@Transactional
@Service("userRoleService")
public class UserRoleServiceImpl implements UserRoleService {

    @Autowired
    UserRoleMapper UserRoleMapper;

    @Override
    public void saveUserRole(UserRole userRole) {
        userRole.setUuid(UUID.randomUUID().toString().replace("-",""));
        UserRoleMapper.insert(userRole);
    }

    @Transactional(readOnly = true)
    @Override
    public List getUserHasAndNotHasRoles(String userId) {
        return UserRoleMapper.getUserHasAndNotHasRoles(userId);
    }

    @Transactional(readOnly = true)
    @Override
    public List getUserHasRoles(String userId) {
        return UserRoleMapper.getUserHasRoles(userId);
    }

    @Cacheable(cacheNames = "cache_user")
    @Transactional(readOnly = true)
    @Override
    public List getUserByRoleName(String rolename) {
        return UserRoleMapper.getUserByRoleName(rolename);
    }

    @Transactional(readOnly = true)
    @Override
    public PageInfo getUserPageByRoleName(MyPager pager,String rolename) {

        PageHelper.startPage(pager.getPage(),pager.getRows());
        List list = UserRoleMapper.getUserByRoleName(rolename);
        PageInfo pageInfo=new PageInfo<>(list);

        return pageInfo;
    }

}

测试类

package com.dashuai.mybatisboot;

import com.dashuai.mybatisboot.entity.MyPager;
import com.dashuai.mybatisboot.entity.User;
import com.dashuai.mybatisboot.service.UserService;
import com.github.pagehelper.PageInfo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.*;

@RunWith(SpringRunner.class)
@SpringBootTest
public class TestUser {

    @Autowired
    UserService userService;

    Logger logger = LoggerFactory.getLogger(getClass());

//    @Test
//    public void test1(){
//        for(int i=1;i<21;i++){
//            User user = new User();
//            user.setPassword("123456");
//            user.setUsername("zhangsan"+i);
//            user.setRegisterDate(new Date());
//            user.setStatus(0);
//            userService.saveUser(user);
//        }
//    }

    @Test
    public void test2(){
        List list = userService.getAllUsers();
        logger.info("list: {} ",list.size());
        List list2 = userService.getAllUsers();
        logger.info("list: {} ",list2.size());
    }

    @Test
    public void test3(){
        User user = userService.getUserByUsername("zhangsan15");
        logger.info("user: {} ",user);
    }

    @Test
    public void test4(){
        User user = userService.getUserByUsername("zhangsan6");
        if(null!=user){
            userService.deleteUserByUUID(user.getUuid());
        }
    }

    @Test
    public void test5(){
        User user = userService.getUserByUsername("zhangsan7");
        if(null!=user){
            user.setPassword("1234567");
            userService.updateUser(user);
        }
    }

    @Test
    public void test6(){
        MyPager myPager = new MyPager(3,10,null);
        PageInfo pageInfo = userService.getPageUsers(myPager);
        logger.info("pageInfo page:{},total:{},totalPage:{} "
                ,pageInfo.getPageNum()
                ,pageInfo.getTotal()
                ,pageInfo.getPages());
        List list = pageInfo.getList();
        for(User u:list){
            logger.info("User {}",u);
        }
        logger.info("pageInfo {}",pageInfo);
    }

    @Test
    public void test7(){
        MyPager myPager = new MyPager(2,10,null);
        PageInfo pageInfo = userService.getPageUsers(myPager);
        logger.info("pageInfo: {} ",pageInfo);
    }

    @Test
    public void test8(){
        Map params = new HashMap<>();
        params.put("username","zhangsan1");
        MyPager myPager = new MyPager(1,10,params);
        PageInfo pageInfo = userService.getPageUsers(myPager);
        logger.info("pageInfo: {} ",pageInfo);
    }

    @Test
    public void test9(){
        Map params = new HashMap<>();
        params.put("username","zhangsan1");
        params.put("status",0);
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY,8);
        params.put("registerDate", calendar.getTime());
        MyPager myPager = new MyPager(2,10,params);
        PageInfo pageInfo = userService.getPageUsers(myPager);
        logger.info("pageInfo: {} ",pageInfo);
    }

}

package com.dashuai.mybatisboot;

import com.dashuai.mybatisboot.entity.MyPager;
import com.dashuai.mybatisboot.entity.Role;
import com.dashuai.mybatisboot.entity.User;
import com.dashuai.mybatisboot.entity.UserRole;
import com.dashuai.mybatisboot.entity.dto.DtoUserRole;
import com.dashuai.mybatisboot.service.RoleService;
import com.dashuai.mybatisboot.service.UserRoleService;
import com.dashuai.mybatisboot.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class TestRole {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    UserService userService;

    @Autowired
    RoleService roleService;

    @Autowired
    UserRoleService userRoleService;

//    @Test
//    public void saveRole(){
//        for(int i=1;i<15;i++){
//            Role role = new Role();
//            role.setRoleName("vip"+i);
//            role.setRoleDesc("会员等级"+i+"级");
//            roleService.saveRole(role);
//        }
//    }

//    @Test
//    public void saveUserRole(){
//
//       List list =  userService.getAllUsers();
//       Role role = roleService.findRoleByName("vip1");
//
//       for(User user:list){
//           UserRole userRole = new UserRole();
//           userRole.setRoleId(role.getUuid());
//           userRole.setUserId(user.getUuid());
//           userRoleService.saveUserRole(userRole);
//       }
//
//    }

    @Test
    public void find1() {
        User user = userService.getUserByUsername("zhangsan1");
        List list = userRoleService.getUserHasAndNotHasRoles(user.getUuid());
        logger.info("list: {}", list);
    }

    @Test
    public void find2() {
        User user = userService.getUserByUsername("zhangsan1");
        List list = userRoleService.getUserHasRoles(user.getUuid());
        logger.info("list: {}", list);
    }

//    @Test
//    public void saveUserRole() {
//
//        List list = userService.getAllUsers();
//        Role role = roleService.findRoleByName("vip2");
//        for (int i = 0; i < list.size(); i++) {
//            if (i % 3 == 0) {
//                UserRole userRole = new UserRole();
//                userRole.setRoleId(role.getUuid());
//                userRole.setUserId(list.get(i).getUuid());
//                userRoleService.saveUserRole(userRole);
//            }
//        }
//    }

    @Test
    public void find3(){
        for(int i=1;i<3;i++){
            logger.info("list: {}", userRoleService.getUserByRoleName("vip1"));
            System.err.println("==================================================");
            logger.info("list: {}", userRoleService.getUserByRoleName("vip2"));
        }
    }

    @Test
    public void find4(){
        for(int i=1;i<3;i++) {
            MyPager pager = new MyPager(2, 10, null);
            logger.info("list: {}", userRoleService.getUserPageByRoleName(pager, "vip1"));
            System.err.println("==================================================");
            logger.info("list: {}", userRoleService.getUserPageByRoleName(pager, "vip2"));
        }
    }

}

代码什么的,基本都粘贴上去了。总结一下。

1. 使用了Hibernate的自动建表功能


   org.springframework.boot
   spring-boot-starter-data-jpa
# 自动创表
spring.jpa.database=mysql
spring.jpa.hibernate.ddl-auto=update

2. 引入了通用的mapper



   tk.mybatis
   mapper
   3.4.3

@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
    MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
    mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
    mapperScannerConfigurer.setBasePackage("com.dashuai.mybatisboot.mapper");//扫描该路径下的dao
    Properties properties = new Properties();
    properties.setProperty("mappers", "com.dashuai.mybatisboot.mybatisbase.MyBaseMapper");//通用dao
    properties.setProperty("notEmpty", "false");
    properties.setProperty("IDENTITY", "MYSQL");
    mapperScannerConfigurer.setProperties(properties);
    return mapperScannerConfigurer;
}

使用的时候,弄一个baseMapper,然后让其他Mapper继承baseMapper就行了,基本没有需要添加的代码了。

配置的时候,请参见MyBatisConfig

 
  

唯一要注意的是,baseMapper和其他实体类对应的mapper不要放在相同包中,否则会报异常。sun.reflect.generics.reflectiveObjects.TypeVariableImpl cannot be cast to java.lang.Class

3. 分页插件的使用。


   com.github.pagehelper
   pagehelper
   4.2.1

@Bean
public PageHelper pageHelper() {
    PageHelper pageHelper = new PageHelper();
    Properties p = new Properties();
    p.setProperty("offsetAsPageNum", "true");
    p.setProperty("rowBoundsWithCount", "true");
    p.setProperty("reasonable", "true");
    pageHelper.setProperties(p);
    return pageHelper;
}

版本确定是4.x.x。我用了5的反而不能正确分页,应该是没有正确配置。用法类似如下。

PageHelper.startPage(pager.getPage(), pager.getRows(), "register_date desc");
List list = UserMapper.selectByExample(example);
PageInfo pageInfo = new PageInfo<>(list);
但注意,startPage紧跟的后面查询语句才会分页,所以不要写多个查询,还指望都能分页。

还有一个稀奇的事情,就是 log日志输出 PageInfo的时候,你可能看不到List,不是不存在,只是不知道为什么它转换toString 的时候是Page对象,所以如果你想看到正确的log日志,比如,List list = pageInfo.getList();

然后for循环list。这个小问题,我发现这个插件的5.x.x版本修复了,但是这个5.x.x版本的,我怎么都无法让他显示正确的分页。所以我还是 选用4.x.x版本的。


4. Ehcache的使用



   org.springframework.boot
   spring-boot-starter-cache




   net.sf.ehcache
   ehcache

# ehcache的配置
spring.cache.type=ehcache
spring.cache.ehcache.config=classpath:ehcache.xml
@EnableAutoConfiguration
@SpringBootApplication
@EnableCaching
public class MybatisbootApplication {

   public static void main(String[] args) {
      SpringApplication.run(MybatisbootApplication.class, args);
   }
}

第四步,再需要使用缓存的方法上面加上@Cacheable注解,但是还必须加上cacheNames的属性值。

所以你会在ehcache.xml中看到 我配置的 cache_user的cache

@Cacheable(cacheNames = "cache_user")
@Transactional(readOnly = true)
@Override
public List getAllUsers() {
    return UserMapper.selectAll();
}

如果哪个方法不用缓存,那就不加@Cacheable注解,加了就表示要使用缓存。

好了,终于对 mybatis的使用 有了一个 更加熟练的掌握了。mybatis也可以做的非常简单的嘛。用用通用Mapper,用用分页插件,其实也不是那么多复杂嘛。如果需要用连接查询,看到我写的嘛,用注解嘛

// 根据用户的uuid查询该用户拥有的角色和未拥有的角色
@Select("select  r.role_name as roleName," +
        "r.role_desc as roleDesc," +
        "r.uuid as roleId," +
        "ur.user_id as userId from tb_role r  " +
        "left join tb_user_role ur  " +
        "on r.uuid = ur.role_id  " +
        "and ur.user_id =#{userId}  ")
public List getUserHasAndNotHasRoles(String userId);
那么基本上,mybatis的基本用法 我算是掌握了一些吧。


 
  





你可能感兴趣的:(IntelliJ,IDEA)