使用的Spring boot +Jpajava
common裏包含了model,以及一些viewModel等等redis
下面就是設計的倉儲模式session
先看下SysUser:app
@MappedSuperclass public class SuperBaseModel { //基本屬性 }
@MappedSuperclass public class BaseModel extends SuperBaseModel { //枚舉值:https://blog.csdn.net/hanjun0612/article/details/72845960 private Integer isValid =EnumList.ValidEnum.Valid.getEnumItem().getItemKey(); @Column(name="IsValid") public Integer getIsValid() { return isValid; } public void setIsValid(Integer isValid) { this.isValid = isValid; } }
@Entity @Table(name = "sys_user", catalog = "kps_business") @DynamicUpdate public class SysUser extends BaseModel implements java.io.Serializable { //get set }
枚舉值,請查看 https://blog.csdn.net/hanjun0612/article/details/72845960ide
@NoRepositoryBean public interface MyJpaRepository<T,ID extends Serializable> extends JpaRepository <T,ID>,JpaSpecificationExecutor<T>{ }
接着建立一個 SysUserDao,裏面額外建立了3個方法。測試
@Repository public interface SysUserDao extends MyJpaRepository<SysUser, String>{ public SysUser getByAccount(String account); public SysUser getByAccountAndPlatformUUID(String account,String platformUUID); public SysUser getByUserUUId(String userUUId); }
這裏MyJpaRepository<SysUser,String>ui
首先傳入的是對象SysUser,其次傳入了一個String 的UUIDthis
若是你是Integer,那你自行修改就能夠了。spa
先建立BaseSuperService.net
public interface BaseSuperService<T extends SuperBaseModel,ID extends Serializable> extends MyJpaRepository<T, ID> { /** * 分頁查詢 */ PageResult<T> pagedList(T entity,Integer currentPage,Integer pageSize,Order...orders); PageResult<T> pagedList(T entity,Integer currentPage,Order...orders); }
接着建立BaseService
public interface BaseService<T extends BaseModel,ID extends Serializable> extends BaseSuperService<T, ID> { /** * 分頁查詢(有效的記錄) */ PageResult<T> pagedListForVaild(T entity,Integer currentPage,Integer pageSize,Order...orders) throws Exception; PageResult<T> pagedListForVaild(T entity,Integer currentPage,Order...orders) throws Exception; }
這裏,你能夠只建立一個BaseService。我是因爲後期有兩個領域模型
第一個領域模型,只須要BaseSuperService的pagedList方法
第二個領域模型,須要BaseSuperService的pagedList方法,以及BaseService的PagedListForVaild方法
所以才建立了兩個層級。
最後建立UserService
public interface SysUserService extends BaseService<SysUser,String>{ public SysUser getByAccountAndPlatformUUID(String account,String platformUUID); public SysUser getByAccount(String account); public SysUser getByUserUUId(String userUUID); }
首先建立BaseSuperServiceImpl
@SuppressWarnings({"unchecked", "rawtypes"}) public class BaseSuperServiceImpl< K extends MyJpaRepository<T,ID>, T extends SuperBaseModel,ID extends Serializable> implements BaseSuperService<T,ID> { protected Class<T> clazz; protected String keyName; //主鍵屬性名 protected Method getMethod; //獲得主鍵對應的get方法 protected String sortName="createTime"; //默認字段排序 因爲個別表key爲UUID,不能按key排序 @Value("${isDebug}") protected boolean isDebug; @Autowired protected K dao; @Autowired protected StringRedisTemplate redisTemplate; @PersistenceContext protected EntityManager em;// 相似hibernate session public BaseSuperServiceImpl() { ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass(); clazz = (Class<T>) type.getActualTypeArguments()[1]; getMethod = HibernateUtil.getKeyMethod(clazz); String idname =getMethod.getName().substring(3); idname = idname.substring(0, 1).toLowerCase() + idname.substring(1); keyName = idname; //獲得主鍵id名 } @Override public List<T> findAll() { return dao.findAll(); } @Override public List<T> findAll(Sort sort) { return dao.findAll(sort); } @Override public Page<T> findAll(Pageable pageable) { return dao.findAll(pageable); } @Override public List<T> findAll(Iterable<ID> integers) { return dao.findAll(integers); } @Override public long count() { return dao.count(); } @Override public void delete(ID id) { dao.delete(id); } @Override public void delete(T entity) { dao.delete(entity); } @Override public void delete(Iterable<? extends T> entities) { dao.delete(entities); } @Override public void deleteAll() { dao.deleteAll(); } @Override public <S extends T> S save(S entity) { try { SysUser curUser = WebUtil.getCurrentUser(isDebug); ID id = (ID) getMethod.invoke(entity); //若是新增,reateTime,createUserUUID沒給值,統一賦值 if(id==null){ if(entity.getCreateTime()==null) entity.setCreateTime(DateUtil.getCurDate()); if(entity.getCreateUserUUID()==null) entity.setCreateUserUUID(curUser.getUserUUId()); } return dao.save(entity); } catch (Exception e) { LogerHelper.error(e); } return null; } @Override public <S extends T> List<S> save(Iterable<S> entities) { return dao.save(entities); } @Override public T findOne(ID id) { return dao.findOne(id); } @Override public boolean exists(ID id) { return dao.exists(id); } @Override public void flush() { dao.flush(); } @Override public <S extends T> S saveAndFlush(S entity) { return dao.saveAndFlush(entity); } @Override public void deleteInBatch(Iterable<T> entities) { dao.deleteInBatch(entities); } @Override public void deleteAllInBatch() { dao.deleteAllInBatch(); } @Override public T getOne(ID id) { return dao.getOne(id); } @Override public <S extends T> S findOne(Example<S> example) { return dao.findOne(example); } @Override public <S extends T> List<S> findAll(Example<S> example) { return dao.findAll(example); } @Override public <S extends T> List<S> findAll(Example<S> example, Sort sort) { return dao.findAll(example,sort); } @Override public <S extends T> Page<S> findAll(Example<S> example, Pageable pageable) { return dao.findAll(example, pageable); } @Override public <S extends T> long count(Example<S> example) { return dao.count(example); } @Override public <S extends T> boolean exists(Example<S> example) { return dao.exists(example); } @Override public PageResult<T> pagedList(T entity, Integer currentPage, Integer pageSize, Order... orders) { Sort s = null; if (orders != null && orders.length > 0) { s = new Sort(orders); } else { s = new Sort(new Order(Direction.DESC, sortName)); } PageRequest pr = new PageRequest(currentPage - 1, pageSize, s); Page<T> p = this.findAll(pr); Integer fromItem = PageUtil.getOffset(currentPage, pageSize); return new PageResult<T>(currentPage, pageSize, p.getContent(), (int)p.getTotalElements(), p.getTotalPages(), fromItem, p.getContent().size()); } @Override public PageResult<T> pagedList(T entity, Integer currentPage, Order... orders) { return this.pagedList(entity, currentPage,PageUtil.PAGE_SIZE,orders); } protected List<Map> exectSqlMap(Query query) { query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP); return query.getResultList(); } protected Map exectSqlMap2(Query query) { List<Map> list = exectSqlMap(query); return ListUtil.notEmpty(list)?list.get(0):null; } protected PageResult<T> gerPageResult(Integer currentPage, Integer pageSize, Specification<T> sf,Order... orders) { //構建分頁信息 Sort s = null; if (orders != null && orders.length > 0) { s = new Sort(orders); } else { s = new Sort(new Order(Direction.DESC, sortName)); } PageRequest pr = new PageRequest(currentPage - 1, pageSize, s); Page<T> p = sf==null?this.findAll(pr):this.findAll(sf,pr); Integer fromItem = PageUtil.getOffset(currentPage, pageSize); return new PageResult<T>(currentPage, pageSize, p.getContent(), (int)p.getTotalElements(), p.getTotalPages(), fromItem, p.getContent().size()); } @Override public T findOne(Specification<T> spec) { return dao.findOne(spec); } @Override public List<T> findAll(Specification<T> spec) { return dao.findAll(spec); } @Override public Page<T> findAll(Specification<T> spec, Pageable pageable) { return dao.findAll(spec, pageable); } @Override public List<T> findAll(Specification<T> spec, Sort sort) { return dao.findAll(spec, sort); } @Override public long count(Specification<T> spec) { return dao.count(spec); } }
基本上,重寫了全部的方法。
而後建立:BaseServiceImpl
public class BaseServiceImpl<K extends MyJpaRepository<T,ID>,T extends BaseModel,ID extends Serializable> extends BaseSuperServiceImpl<K,T,ID> implements BaseService<T,ID> { @Override public PageResult<T> pagedListForVaild(T entity, Integer currentPage, Integer pageSize, Order... orders) throws Exception { Sort s = null; if (orders != null && orders.length > 0) { s = new Sort(orders); } else { s = new Sort(new Order(Direction.DESC, sortName)); } PageRequest pr = new PageRequest(currentPage - 1, pageSize, s); T model = clazz.newInstance(); model.setIsValid(EnumList.ValidEnum.Valid.getEnumItem().getItemKey()); Example<T> example = Example.of(model); Page<T> p = dao.findAll(example, pr); Integer fromItem = PageUtil.getOffset(currentPage, pageSize); return new PageResult<T>(currentPage, pageSize, p.getContent(), (int)p.getTotalElements(), p.getTotalPages(), fromItem, p.getContent().size()); } @Override public <S extends T> S save(S entity) { //若是isValid沒給值,統一賦值 if(entity.getIsValid()==null) entity.setIsValid(EnumList.ValidEnum.Valid.getEnumItem().getItemKey()); return super.save(entity); } @Override public PageResult<T> pagedListForVaild(T entity, Integer currentPage, Order... orders) throws Exception { return this.pagedListForVaild(entity, currentPage,PageUtil.PAGE_SIZE,orders); } }
最後建立UserServiceImpl
@Service("userService") public class SysUserServiceImpl extends BaseServiceImpl<SysUserDao,SysUser,String> implements SysUserService { public SysUser getByUserUUId(String userUUId){ return dao.getByUserUUId(userUUId); } @Override public SysUser getByAccountAndPlatformUUID(String account,String platformUUID) { return dao.getByAccountAndPlatformUUID(account,platformUUID); } @Override public SysUser getByAccount(String account) { return dao.getByAccount(account); } @Override public PageResult<SysUser> pagedList(SysUser entity, Integer currentPage, Integer pageSize, Order... orders) { if(entity==null){ return super.pagedList(entity, currentPage, pageSize, orders); } //構建查詢條件 Specification<SysUser> sf = new Specification<SysUser>(){ @Override public Predicate toPredicate(Root<SysUser> root, CriteriaQuery<?> query, CriteriaBuilder cb) { String name = entity.getUserNameCn(); Integer isValid = entity.getIsValid(); List<Predicate> list = new ArrayList<Predicate>(); if (StringUtils.isNotBlank(name)) { name = name.toLowerCase(); Predicate p1 = cb.like(cb.lower(root.get("userNameCn")), "%" + name + "%"); Predicate p2 = cb.like(cb.lower(root.get("userNameEn")), "%" + name + "%"); Predicate p3 = cb.like(cb.lower(root.get("account")), "%" + name+ "%"); list.add(cb.or(p1,p2,p3)); } if(isValid!=null){ list.add(cb.equal(root.get("isValid"),isValid)); } Predicate[] p = new Predicate[list.size()]; return cb.and(list.toArray(p)); } }; return super.gerPageResult(currentPage, pageSize,sf,orders); } }
這裏,我額外演示一下重寫了PagedList方法。
@RunWith(value=SpringRunner.class) @SpringBootTest(classes={WebAPISYSApp.class}) public class SysUserTest{ @Autowired private SysUserService userService; @Test public void findUser(){ SysUser user = userService.findOne("0c867aca-d1eb-11e8-9aa5-0022198292f8"); logger.info(user.getAccount()); } }