通用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基于接口的代理将起作用。

尾言

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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值