通用Mapper和PageHelper插件 学习笔记

前言

通过Mapper可以极大的方便开发人员。可以随意的按照自己的需要选择通用,极其方便的使用MyBatis单表的CRUD,支持单表操作,不支持通用的多表联合查询。

配置Mapper和PageHelper

  • Maven配置
        <!-- mapper插件 -->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper</artifactId>
            <version>3.4.4</version>
        </dependency>
        
        <!-- 分页插件 -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.1.2</version>
        </dependency>
        
        <!-- jpa -->
        <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>persistence-api</artifactId>
            <version>1.0</version>
        </dependency>
  • Spring.xml中配置分页拦截器插件
   <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="typeAliasesPackage" value="com.helping.wechat.model"></property>
        <property name="mapperLocations" value="classpath*:com/helping/wechat/model/**/mysql/*Mapper.xml" />
        <property name="plugins">
            <array>
                <bean class="com.github.pagehelper.PageInterceptor">
                    <property name="properties">
                        <value>
                            helperDialect=mysql
                            reasonable=true
                            rowBoundsWithCount=true
                        </value>
                    </property>
                </bean> 
            </array>
        </property>
    </bean>

helperDialect=mysql:代表指定分页插件使用mysql
rowBoundsWithCount=true:代表使用RowBounds分页会进行count查询。
reasonable=true:当pageNum <= 0时会查询第一页,pageNum > 总数的时候,会查询最后一页。

更多配置请看PageHelper官方文档

PageHelper配置就是这样了,接下来配置Mapper

  • Spring.xml配置通用Mapper
    <bean class="tk.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.helping.wechat.mapper"/>
        <property name="properties">
            <value>
                mappers=com.helping.wechat.custom.GenericMapper
                notEmpty=true
            </value>
        </property>
    </bean>

mappers=com.helping.wechat.custom.GenericMapper,这里的类我们自定义的mapper类,后面会讲到。
notEmpty=trueinsertupdate中,会判断字符串类型 != ‘’。
更多的配置请看通用Mapper官方文档

我最讨厌去配置繁琐的配置了,配置终于搞定了,接下来可以撸代码了。


自定义Mapper

public interface GenericMapper<T> extends MySqlMapper<T>, Mapper<T>, IdsMapper<T>, ConditionMapper<T> {

}

接口可以多继承,我们自定义的GenericMapper继承了很多接口,体现了多态性。我们这个GenericMapper具有很多功能。

我们可以看到MySqlMapper<T>里面有这些接口,这些接口针支持mysql

public interface MySqlMapper<T> extends
        InsertListMapper<T>,
        InsertUseGeneratedKeysMapper<T> {
}
  • 接口:InsertListMapper<T>

    • 方法:int insertList(List<T> recordList);
    • 说明: 批量插入,支持批量插入的数据库可以使用,例如MySQLH2等,另外该接口限制实体包含id属性并且必须为自增列。
  • 接口: InsertUseGeneratedKeysMapper<T>

    • 方法:int insertUseGeneratedKeys(T record);
    • 说明:插入数据,限制为实体包含id属性并且必须为自增列,实体配置的主键策略无效。

在这里就简单的说几个Mapper的用法,需要知道更详细的,请看移步通用Mapper官方文档


开始写代码

  • 定义一个UserInfo.java。使用@Table,指明我们的数据表名。@GeneratedValue(GenerationType.IDENTITY)是唯一标识的主键。如果我们不加@Column注解在字段上面,默认是在进行sql语句操作的时候,把满足的小驼峰格式的字段,转换成小写加下划线格式的。比如userName,如果要进行sql语句的操作的时候,它就会变成user_name。如果转换后的字段不满足你数据表中的格式时,你可以使用@Column指明该字段所对应的数据表中的字段。
@Table(name = "test")
public class UserInfo {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String userName;
    private String password;

    public UserInfo(Integer id, String userName, String password) {
        super();
        this.id = id;
        this.userName = userName;
        this.password = password;
    }

    public UserInfo() {

    }

    @Override
    public String toString() {
        return new Gson().toJson(this);
    }
}
  • 在去定义个UserMapper.java。这个mapper需要继承我们刚才定义的GenericMapper类。
public interface UserMapper extends GenericMapper<UserInfo>{

}

后面会讲到单元测试,去测试我们这些mapper有没有问题。


自定义一个BaseService

  • 我们去把这些mapper所涉及到的CRUD,封装到一个BaseService里面去。首先去定义一个IService接口。
public interface IService<T> {

    void save(T model);

    void save(List<T> models);

    void deleteById(Integer id);

    /**
     * Batch delete, for exmaple ids "1, 2, 3, 4"
     * @param ids
     */
    void deleteByIds(String ids);

    void update(T model);

    T findById(Integer id);

    List<T> findByIds(String ids);

    List<T> findByCondition(Condition condition);

    List<T> findAll();

    T findBy(String fieldName, Object value) throws TooManyResultsException;
}
  • 再去定义一个抽象类BaseService,去实现它。
public abstract class BaseService<T> implements IService<T>{

    private static final Logger log = LoggerFactory.getLogger(BaseService.class);

    @Autowired
    protected GenericMapper<T> mapper;

    private Class<T> modelClass;

    public BaseService() {
        ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
        modelClass = (Class<T>) pt.getActualTypeArguments()[0];
    }

    public void save(T model) {
        mapper.insertSelective(model);
    }

    public void save(List<T> models) {
        mapper.insertList(models);
    }

    public void deleteById(Integer id) {
        mapper.deleteByPrimaryKey(id);
    }

    public void deleteByIds(String ids) {
        mapper.deleteByIds(ids);
    }

    public void update(T model) {
        mapper.updateByPrimaryKeySelective(model);
    }

    public T findById(Integer id) {
        return mapper.selectByPrimaryKey(id);
    }

    public List<T> findByIds(String ids) {
        return mapper.selectByIds(ids);
    }

    public List<T> findByCondition(Condition condition) {
        return mapper.selectByCondition(condition);
    }

    public List<T> findAll() {
        return mapper.selectAll();
    }

    public T findBy(String fieldName, Object value) throws TooManyResultsException {
        try {
            T model = modelClass.newInstance();
            Field field = modelClass.getDeclaredField(fieldName);
            //true 代表能通过访问访问该字段
            field.setAccessible(true);
            field.set(model, value);

            return mapper.selectOne(model);
        } catch (ReflectiveOperationException e) {
            log.info("BaseService have reflect erors = {}", e.getMessage());
            throw new ServiceException(ResultCode.REFLECT_ERROR.setMsg(e.getMessage()));
        }
    }
}

这里用到了反射。ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();返回此Class所表示的实体(类,接口,基本类型或者void)的直接超类的Type,然后将其转换ParameterizedType。getActualTypeArguments()返回此类型实际类型参数的Type对象的数组。简而言之,就是获取超类的泛型参数的实际类型。

那么T model = modelClass.newInstance()这样获取实例的方式和new运算符创建的实例有什么不同呢。

JVM角度讲,使用关键字new创建一个类的时候,这个类可以没有被加载。但是使用new Instance()的时候,就必须保证这个类应该被加载和已经连接了。
newInstance()是弱类型的,效率低,只能调用无参构造方法。而new是强类型的,相对搞笑,能调用任何public构造方法。

  • 写一个UserService.java
@Service(value = "userService")
public class UserService extends BaseService<UserInfo> {

}

单元测试之前的准备

  • 首先pom.xml配置依赖。
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.0.0.RELEASE</version>
            <scope>test</scope>
        </dependency>
  • 在进行单元测试之前,我们先去写一个SpringContextUtil类,不必要每次单元测试就要写ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml")去获取Spring上下文。我们把上下文存放在工具类的静态域里面,方便我们随便获取。
@Component
public class SpringContextUtil implements ApplicationContextAware {

    public static ApplicationContext context = null;

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    public static ApplicationContext getContext() {
        return context;
    }

    public static <T> T getBean(Class<T> requiredType) {
        return getContext().getBean(requiredType);
    }
}

测试UserMapper

  • 测试UserMapper,点击运行。我这里测试,会导致脏数据的产生。因为需求,我现在需要这些脏数据。
    如果不希望脏数据的产生,我们测试类可以去继承AbstractTransactionalJUnit4SpringContextTests。当一个测试方法执行完毕后,会进行事务回滚,从而避免脏数据的产生。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml", "classpath:helping-mvc.xml"})
public class UserMapperTest {
    private UserMapper userMapper;

    @Before
    public void setUp() throws Exception {
        this.userMapper = SpringContextUtil.getBean(UserMapper.class);
    }

    @Test
    public void selectOne() {
        UserInfo userInfo = userMapper.selectByPrimaryKey(new Integer(1));
        System.out.println(userInfo);
    }

    /**
     * select * from test where id in (?,?,?,?)
     */
    @Test
    public void selectByExample() {
        Example example = new Example(UserInfo.class);
        List<Integer> ids = new ArrayList<Integer>();
        ids.add(1);
        ids.add(2);
        ids.add(3);
        ids.add(4);
        example.createCriteria().andIn("id", ids);
        example.setOrderByClause("id desc");
        List<UserInfo> users = this.userMapper.selectByExample(example);
        System.out.println(users);
    }

    /**
     * Tests pagination
     */
    @Test
    public void selectByPage() {
        PageHelper.startPage(1, 2);
/*        PageHelper.orderBy("user_name");*/
        List<UserInfo> users = this.userMapper.selectAll();

        for (UserInfo user : users) {
            System.out.println(user);
        }
    }

    @Test
    public void addTestData() {
/*        List<UserInfo> datas = new ArrayList<UserInfo>();

        for (int i = 0; i < 900000; i++) {
            UserInfo userInfo = new UserInfo(0, "test" + i, "test" + i);
            datas.add(userInfo);
        }
        int result = this.userMapper.insertList(datas);
        System.out.println(result);*/
    }
}

测试成功,美滋滋。


image.png

测试UserService

运行UserServiceTest,我们会发现Failed to load ApplicationContext这个错误,会导致测试失败。

image.png
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml", "classpath:helping-mvc.xml"})
public class UserServiceTest {

    private UserService userService;

    @Before
    public void setUp() throws Exception {
        userService = SpringContextUtil.getBean(UserService.class);
    }

    @Test
    public void selectOne() {
        UserInfo userInfo = userService.findById(new Integer(1));
        System.out.println(userInfo);
    }

    @Test
    public void findBy() {
        UserInfo userInfo = userService.findBy("userName", "sally");
        System.out.println(userInfo);
    }

    @Test
    public void findByIds() {
        List<UserInfo> users = userService.findByIds("1,2,3");

        for (UserInfo user : users) {
            System.out.println(user);
        }
    }
}
  • 我们观察控制台,发现会输出这个异常,
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ordinaryUserController': Injection of resource dependencies failed; nested exception is org.springfra
mework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'ordinaryUserService' must be of type [com.helping.wechat.service.admin.impl.OrdinaryUserService], but was actually of type [com.sun.pro
xy.$Proxy38]

我们通过看这一行代码Injection of resource dependencies failed,知道了应该依赖注入失败了。

  • 我们只需要在Spring.xml加上<aop:aspectj-autoproxy /> <aop:config proxy-target-class="true"></aop:config>就行了。重新run一遍,看测试结果,都是绿色的。
image.png

问题分析归纳

为什么我们加上<aop:aspectj-autoproxy /> <aop:config proxy-target-class="true"></aop:config>2行代码就能解决依赖注入失败的问题。

  • 由于UserService继承了BaseService类,它是一个类,不能使用JDK的动态代理注入。
 private UserService userService;

    @Before
    public void setUp() throws Exception {
        userService = SpringContextUtil.getBean(UserService.class);
    }

JDK的动态代理不支持类的注入,只支持接口方式的注入,如果确实不想使用Spring提供的动态代理,我们可以选择使用cglib代理解决。

  • cglibpom.xml配置:
      <dependency>
        <groupId>cglib</groupId>
        <artifactId>cglib-nodep</artifactId>
        <version>2.2</version>
      </dependency>
  • proxy-target-class属性值决定是基于接口还是基于类的代理被创建。如果是true,那么基于类的代理起作用,如果为false或者这个属性被忽略,那么标准的JDK基于接口的代理将起作用。

尾言

勿以善小而不为,勿以恶小而为之。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 220,884评论 6 513
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,212评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 167,351评论 0 360
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,412评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,438评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,127评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,714评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,636评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,173评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,264评论 3 339
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,402评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,073评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,763评论 3 332
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,253评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,382评论 1 271
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,749评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,403评论 2 358

推荐阅读更多精彩内容