发表于: 2017-12-22 20:40:06

1 664


今天完成的事

spring和mybatis到底结合了什么。

<!-- 配置Mybatis的文件 ,mapperLocations配置**Mapper.xml文件位置,configLocation配置mybatis-config文件位置-->
<!--spring的配置文件一定要加classpath-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
   <property name="dataSource" ref="C3P0dataSource" />
   <property name="mapperLocations" value="classpath:DAO/mapper.xml"/>
   <property name="configLocation" value="classpath:mybatis-config.xml" />
   <property name="typeAliasesPackage" value="pojo"/>
</bean>

这段代码里。

我们知道在Mybatis的所有操作都是基于一个SqlSession的,而SqlSession是由SqlSessionFactory来产生的,SqlSessionFactory又是由SqlSessionFactoryBuilder来生成的。但是Mybatis-Spring是基于SqlSessionFactoryBean的。在使用Mybatis-Spring的时候,我们也需要SqlSession,而且这个SqlSession是内嵌在程序中的,一般不需要我们直接访问。SqlSession也是由SqlSessionFactory来产生的,但是Mybatis-Spring给我们封装了一个SqlSessionFactoryBean,在这个bean里面还是通过SqlSessionFactoryBuilder来建立对应的SqlSessionFactory,进而获取到对应的SqlSession。通过SqlSessionFactoryBean我们可以通过对其指定一些属性来提供Mybatis的一些配置信息。所以接下来我们需要在Spring的applicationContext配置文件中定义一个SqlSessionFactoryBean。

分页查询

项目结构


BaseEntity

package dto;

import java.io.Serializable;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* Created by ${MIND-ZR} on 2017/12/22.
*/

public abstract class BaseEntity implements Serializable {
private static final long serialVersionUID = 1L;

   private static Map<Class<?>, PropertyInfo[]> class2Props = new HashMap<Class<?>, PropertyInfo[]>(128);

   @Override
   public String toString() {
PropertyInfo[] props = class2Props.get(this.getClass());
       if (props == null) {
props = getProps(this.getClass());
       }

StringBuilder builder = new StringBuilder(1024);
       boolean isFirst = true;
       for (int i = 0, n = props.length; i < n; i++) {
try {
PropertyInfo propInfo = props[i];

               Object value = propInfo.getMethod.invoke(this, new Object[0]);
               if (isFirst)
isFirst = false;
               else
                   builder.append(",");
               builder.append(propInfo.propName);
               builder.append(":");
               if (value instanceof String)
builder.append("\"");
               builder.append(value);
               if (value instanceof String)
builder.append("\"");
           } catch (Exception e) {
// ignore
           }
}
return "{" + builder.toString() + "}";
   }

private static PropertyInfo[] getProps(Class<? extends BaseEntity> clazz) {
PropertyInfo[] props;
       Method[] allMethods = clazz.getMethods();
       List<PropertyInfo> propList = new ArrayList<PropertyInfo>();

       for (int i = 0, n = allMethods.length; i < n; i++) {
try {
Method method = allMethods[i];
               if ((method.getModifiers() & Modifier.PUBLIC) == 1
                       && method.getDeclaringClass() != Object.class
                       && (method.getParameterTypes() == null || method
.getParameterTypes().length == 0)) {
String methodName = method.getName();
                   if (methodName.startsWith("get") || methodName.startsWith("is")) {
PropertyInfo propInfo = new PropertyInfo();
                       propInfo.getMethod = method;
                       if (methodName.startsWith("get")) {
propInfo.propName = methodName.substring(3, 4).toLowerCase()
+ methodName.substring(4);
                       } else if (methodName.startsWith("is")) {
propInfo.propName = methodName.substring(2, 3).toLowerCase()
+ methodName.substring(3);
                       }
propList.add(propInfo);
                   }
}
} catch (Exception e) {
}
}

props = new PropertyInfo[propList.size()];
       propList.toArray(props);
       class2Props.put(clazz, props);
       return props;
   }

static class PropertyInfo {
Method getMethod;
       String propName;
   }

}

BeanUtil

package util;

import com.github.pagehelper.Page;

import java.util.List;

/**
* Created by ${MIND-ZR} on 2017/12/22.
*/
public class BeanUtil {

public static <T> PagedResult<T> toPagedResult(List<T> datas) {
PagedResult<T> result = new PagedResult<T>();
       if (datas instanceof Page) {
Page page = (Page) datas;
           result.setPageNo(page.getPageNum());
           result.setPageSize(page.getPageSize());
           result.setDataList(page.getResult());
           result.setTotal(page.getTotal());
           result.setPages(page.getPages());
       }
else {
result.setPageNo(1);
           result.setPageSize(datas.size());
           result.setDataList(datas);
           result.setTotal(datas.size());
       }

return result;
   }
}

PagedResult

package util;

import dto.BaseEntity;

import java.util.List;

/**
* Created by ${MIND-ZR} on 2017/12/22.
*/
public class PagedResult<T> extends BaseEntity {

/*serialVersionUID*/
   private static final long serialVersionUID = 1L;

   private List<T> dataList;//数据

   private long pageNo;//当前页

   private long pageSize;//条数

   private long total;//总条数

   private long pages;//总页面数目

   public List<T> getDataList() {
return dataList;
   }

public void setDataList(List<T> dataList) {
this.dataList = dataList;
   }

public long getPageNo() {
return pageNo;
   }

public void setPageNo(long pageNo) {
this.pageNo = pageNo;
   }

public long getPageSize() {
return pageSize;
   }

public void setPageSize(long pageSize) {
this.pageSize = pageSize;
   }

public long getTotal() {
return total;
   }

public void setTotal(long total) {
this.total = total;
   }

public long getPages() {
return pages;
   }

public void setPages(long pages) {
this.pages = pages;
   }

}

测试类

import dao.UserMapper;
import model.User;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import service.query;
import util.PagedResult;

/**
* Created by ${MIND-ZR} on 2017/12/22.
*/


@ContextConfiguration(locations = {"classpath:application.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
public class CURD {
Logger logger = Logger.getLogger(CURD.class);
   @Autowired
   private UserMapper userMapper;

   @Autowired
   private query query1;

   //查找操作
   @Test
   public void select() {
PagedResult<User> pagedResult = query1.queryByPage("小三", 1, 10);//null表示查全部
       logger.debug("查找结果" + pagedResult);
   }


}

打断点看一下查到没。



遇见的问题


解决方法http://blog.csdn.net/beyond667/article/details/8366010

  <dependency>

           <groupId>javax</groupId>

           <artifactId>javaee-api</artifactId>

           <version>6.0</version>

       </dependency>

由于在pom文件中添加了上面的内容导致一个异常:  删除这个依赖之后, 问题就没有了



收获

熟悉mybatis

明天的计划

准备评审的东西

把分页查询前端写了。


返回列表 返回列表
评论

    分享到