Java&JAVA EE程序员Android开发经验谈

通用Mapper和PageHelper插件 学习笔记

2017-11-04  本文已影响492人  cmazxiaoma

前言

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

配置Mapper和PageHelper

        <!-- 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>
   <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

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

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


开始写代码

@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);
    }
}
public interface UserMapper extends GenericMapper<UserInfo>{

}

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


自定义一个BaseService

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;
}
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构造方法。

@Service(value = "userService")
public class UserService extends BaseService<UserInfo> {

}

单元测试之前的准备

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.0.0.RELEASE</version>
            <scope>test</scope>
        </dependency>
@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

@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,知道了应该依赖注入失败了。

image.png

问题分析归纳

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

 private UserService userService;

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

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

      <dependency>
        <groupId>cglib</groupId>
        <artifactId>cglib-nodep</artifactId>
        <version>2.2</version>
      </dependency>

尾言

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

上一篇下一篇

猜你喜欢

热点阅读