框架搭建
一.SpringDataJpa扩展
1.BaseRepository 接口
@NoRepositoryBean:让SpringdataJpa不要自动为它生成子类
@NoRepositoryBean
public interface BaseRepository<T, ID extends Serializable> extends JpaRepository<T,ID>, JpaSpecificationExecutor<T> {
//根据Query拿到分页对象(分页)
Page findPageByQuery(BaseQuery baseQuery);
//根据Query拿到对应的所有数据(不分页)
List<T> findByQuery(BaseQuery baseQuery);
//根据jpql与对应的参数拿到数据
List findByJpql(String jpql,Object... values);
}
2.BaseRepositoryImpl 实现 BaseRepository
public class BaseRepositoryImpl<T,ID extends Serializable> extends SimpleJpaRepository<T,ID> implements BaseRepository<T,ID> {
private final EntityManager entityManager;
//必需要实现父类的这个构造器
public BaseRepositoryImpl(Class<T> domainClass, EntityManager em) {
super(domainClass, em);
this.entityManager = em;
}
@Override
public Page findPageByQuery(BaseQuery baseQuery) {
//第一步:拿到所有高级查询条件
Specification spec = baseQuery.createSpec();
//第二步:拿到排序的值
Sort sort = baseQuery.createSort();
//第三步:根据条件查询分页数据并且返回
Pageable pageable = new PageRequest(baseQuery.getJpaPage(), baseQuery.getPageSize(),sort);
Page<T> page = super.findAll(spec, pageable);
return page;
}
@Override
public List<T> findByQuery(BaseQuery baseQuery) {
//第一步:拿到所有高级查询条件
Specification spec = baseQuery.createSpec();
//第二步:拿到排序的值
Sort sort = baseQuery.createSort();
//第三步:拿到数据返回
return findAll(spec, sort);
}
@Override
public List findByJpql(String jpql, Object... values) {
//第一步:创建Query对象
Query query = entityManager.createQuery(jpql);
//第二步:把值设置到Query对象中去
if (values!=null) {
for (int i = 0; i < values.length; i++) {
query.setParameter(i + 1, values[i]);
}
}
//第三步:返回数据
return query.getResultList();
}
}
3.让SpringDataJpa使用我们自己的实现
原来默认使用SimpleJpaRepository来实现,把它修改成BaseRepositoryImpl
3.1 BaseRepositoryFactoryBean
/**
* 如果要扩展SpringDataJpa必需写它
*/
public class BaseRepositoryFactoryBean<T extends Repository<S, ID>, S, ID extends Serializable> extends JpaRepositoryFactoryBean<T,S,ID> {
@Override
protected RepositoryFactorySupport createRepositoryFactory(EntityManager entityManager) {
return new MyRepositoryFactory<T,ID>(entityManager); //注:这里创建是我们的自定义类
}
//继承JpaRepositoryFactory后,把返回的对象修改成我们自己的实现
private static class MyRepositoryFactory<T,ID extends Serializable> extends JpaRepositoryFactory {
private final EntityManager entityManager;
/**
* Creates a new {@link JpaRepositoryFactory}.
*
* @param entityManager must not be {@literal null}
*/
public MyRepositoryFactory(EntityManager entityManager) {
super(entityManager);
this.entityManager = entityManager;
}
//这里返回最后的功能对象
@Override
protected Object getTargetRepository(RepositoryInformation information) {
return new BaseRepositoryImpl<T,ID>((Class<T>)information.getDomainType(),entityManager);
}
//确定功能对象的类型
@Override
protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
return BaseRepositoryImpl.class;
}
}
}
3.2 applicationContext.xml配置
关键就是factory-class配置
<!-- 集成SpringDataJpa (这层单独扫描)-->
<jpa:repositories base-package="cn.itsource.aisell.repository"
entity-manager-factory-ref="entityManagerFactory"
transaction-manager-ref="transactionManager"
factory-class="cn.itsource.aisell.repository.BaseRepositoryFactoryBean"
></jpa:repositories>
3.3使用的时候继承BaseRepository
public interface EmployeeRepository extends BaseRepository<Employee,Long>
二.Service层的调用
BaseServiceImpl 实现 IBaseService
IEmployeeService 继承 IBaseService
注意点泛型注入
@Autowired
private BaseRepository<T,ID> baseRepository;
三.集成SpringMVC与EasyUI
3.1 noSession问题
我们在关闭了EntityManager之前,依然在使用它操作数据库(懒加载时出现)
解决方案:web.xml中添加OpenEntityManagerInViewFilter
<!-- 解决no-session的问题 -->
<filter>
<filter-name>openEntityManager</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>openEntityManager</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
3.2 no serializer问题
原因:jpa的懒加载对象自己为加一些属性("hibernateLazyInitializer","handler","fieldHandler") 会影响到SpringMVC返回Json(因为返回时有个内省机制)
解决方案一:加注解
@JsonIgnoreProperties(value={"hibernateLazyInitializer","handler","fieldHandler"})
解决方案二:一劳永逸
- 重写:ObjectMapper
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
//重写了原生的映射关系
public class CustomMapper extends ObjectMapper {
public CustomMapper() {
this.setSerializationInclusion(JsonInclude.Include.NON_NULL);
// 设置 SerializationFeature.FAIL_ON_EMPTY_BEANS 为 false
this.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
}
}
- 在applicationContext-mvc.xml 配置这个映射
<!-- Spring MVC 配置 -->
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json; charset=UTF-8</value>
<value>application/x-www-form-urlencoded; charset=UTF-8</value>
</list>
</property>
<!-- No serializer:配置 objectMapper 为我们自定义扩展后的 CustomMapper,解决了返回对象有关系对象的报错问题 -->
<property name="objectMapper">
<bean class="cn.itsource.aisell.common.CustomMapper"></bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
3.3 分页获取数据
后台返回的是Page对象{content:..,totalElements:..}
前台要拿代码是{rows:..,total:...}
它们的结果对应不上
- 搞了一个UIPage
public class UIPage {
private List rows;
private Long total;
public UIPage(Page page) {
this.rows = page.getContent();
this.total = page.getTotalElements();
}
//省略getter与setter
}
- 返回的时候代码如下:
@RequestMapping("/page")
@ResponseBody
public UIPage page(EmployeeQuery query){
return new UIPage(employeeService.findPageByQuery(query));
}
3.4 分页传数据
传的是page与rows,但是我们之前的query名称没对应上
- BaseQuery加上兼容
//为了兼容前台的easyui而准备的
public void setPage(int page) {
this.currentPage = page;
}
public void setRows(int rows) {
this.pageSize = rows;
}
3.5 高级查询
- 高级查询的时候获取对应的表单值
引入jquery.jdirk.js
它对jQuery的功能进行扩展
<script type="text/javascript" src="/easyui/plugin/jquery.jdirk.js"></script>
获取表单的功能
search(){
//直接获取到表单中的所有值
var params = $("#searchForm").serializeObject();
//进行相应的查询
$("#employeeGrid").datagrid("load",params);
}
转载于:https://my.oschina.net/u/4083667/blog/3074573