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

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

    直接进入主题啦。

    pom依赖

   

<dependency>
   <groupId>org.mybatis.spring.boot</groupId>
   <artifactId>mybatis-spring-boot-starter</artifactId>
   <version>1.1.1</version>
</dependency>

<!--引入通用Mapper -->
<dependency>
   <groupId>tk.mybatis</groupId>
   <artifactId>mapper</artifactId>
   <version>3.4.3</version>
</dependency>
<!--分页插件-->
<dependency>
   <groupId>com.github.pagehelper</groupId>
   <artifactId>pagehelper</artifactId>
   <version>4.2.1</version>
</dependency>
<!-- 添加缓存支持 -->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

<!-- 使用ehcache缓存方案 -->
<dependency>
   <groupId>net.sf.ehcache</groupId>
   <artifactId>ehcache</artifactId>
</dependency>
我对于创建数据库的表,又懒了。所以我希望依赖hibernate的自动建表功能。可选操作啊。

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
其它的pom依赖我也补上吧

<dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <scope>runtime</scope>
</dependency>

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-devtools</artifactId>
   <optional>true</optional>
   <scope>true</scope>
</dependency>

<dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>druid</artifactId>
   <version>1.0.31</version>
</dependency>
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
</dependency>
<repositories>
   <repository>
      <id>alimaven</id>
      <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
      <releases>
         <enabled>true</enabled>
      </releases>
      <snapshots>
         <enabled>true</enabled>
      </snapshots>
   </repository>
</repositories>

<pluginRepositories>
   <pluginRepository>
      <id>alimaven</id>
      <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
      <releases>
         <enabled>true</enabled>
      </releases>
      <snapshots>
         <enabled>true</enabled>
      </snapshots>
   </pluginRepository>
</pluginRepositories>

这里忘记说一个重要的事情,就是分页插件的版本,一定要用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 <T>
 */
public interface MyBaseMapper<T> extends Mapper<T>,MySqlMapper<T>{

}

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


<ehcache name="mybatisboot_Ehcache" updateCheck="false">
    <diskStore path="../mybatisboot_Ehcache"/>
    <!-- hibernate ehcache-->
    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            overflowToDisk="true"
            maxElementsOnDisk="10000000"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU"
    />
    <cache name="org.hibernate.cache.spi.UpdateTimestampsCache"
           maxElementsInMemory="5000"
           eternal="true"
           overflowToDisk="true"/>
    <cache name="org.hibernate.cache.internal.StandardQueryCache"
           maxElementsInMemory="10000"
           eternal="false"
           timeToLiveSeconds="120"
           overflowToDisk="true"/>

    <cache    name="cache_user"
              eternal="false"
              maxElementsInMemory="100"
              overflowToDisk="false"
              diskPersistent="false"
              timeToIdleSeconds="0"
              timeToLiveSeconds="300"
              memoryStoreEvictionPolicy="LRU"
    />

</ehcache>


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<User> {

}

package com.dashuai.mybatisboot.mapper;

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

public interface RoleMapper extends MyBaseMapper<Role>{


}

package com.dashuai.mybatisboot.entity;

import java.util.Map;

public class MyPager {

    int page;
    int rows;

    Map<String,Object> params;

    public MyPager(int page, int rows, Map<String, Object> 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<String, Object> getParams() {
        return params;
    }

    public void setParams(Map<String, Object> 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<User> getAllUsers();

    PageInfo<User> 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<DtoUserRole> getUserHasAndNotHasRoles(String userId);

    List<DtoUserRole> getUserHasRoles(String userId);

    List<User> getUserByRoleName(String rolename);

    PageInfo<User> 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<User> 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<User> getAllUsers() {
        return UserMapper.selectAll();
    }

    @Transactional(readOnly = true)
    @Override
    public PageInfo<User> getPageUsers(MyPager pager) {
        Example example = new Example(User.class);
        Map<String, Object> 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<User> list = UserMapper.selectByExample(example);
        PageInfo<User> 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<Role> 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<DtoUserRole> getUserHasAndNotHasRoles(String userId) {
        return UserRoleMapper.getUserHasAndNotHasRoles(userId);
    }

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

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

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

        PageHelper.startPage(pager.getPage(),pager.getRows());
        List<User> list = UserRoleMapper.getUserByRoleName(rolename);
        PageInfo<User> 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<User> list = userService.getAllUsers();
        logger.info("list: {} ",list.size());
        List<User> 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<User> pageInfo = userService.getPageUsers(myPager);
        logger.info("pageInfo page:{},total:{},totalPage:{} "
                ,pageInfo.getPageNum()
                ,pageInfo.getTotal()
                ,pageInfo.getPages());
        List<User> 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<User> pageInfo = userService.getPageUsers(myPager);
        logger.info("pageInfo: {} ",pageInfo);
    }

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

    @Test
    public void test9(){
        Map<String,Object> 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<User> 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<User> 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<DtoUserRole> list = userRoleService.getUserHasAndNotHasRoles(user.getUuid());
        logger.info("list: {}", list);
    }

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

//    @Test
//    public void saveUserRole() {
//
//        List<User> 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的自动建表功能

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
# 自动创表
spring.jpa.database=mysql
spring.jpa.hibernate.ddl-auto=update

2. 引入了通用的mapper

<!--引入通用Mapper -->
<dependency>
   <groupId>tk.mybatis</groupId>
   <artifactId>mapper</artifactId>
   <version>3.4.3</version>
</dependency>

@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. 分页插件的使用。

<dependency>
   <groupId>com.github.pagehelper</groupId>
   <artifactId>pagehelper</artifactId>
   <version>4.2.1</version>
</dependency>

@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<User> list = UserMapper.selectByExample(example);
PageInfo<User> pageInfo = new PageInfo<>(list);
但注意,startPage紧跟的后面查询语句才会分页,所以不要写多个查询,还指望都能分页。

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

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


4. Ehcache的使用

<!-- 添加缓存支持 -->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

<!-- 使用ehcache缓存方案 -->
<dependency>
   <groupId>net.sf.ehcache</groupId>
   <artifactId>ehcache</artifactId>
</dependency>

# 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<User> 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<DtoUserRole> getUserHasAndNotHasRoles(String userId);
那么基本上,mybatis的基本用法 我算是掌握了一些吧。


 





  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值