Просмотр исходного кода

Merge branch 'master' of http://192.168.1.220:10080/EHR/commons

zdm 6 лет назад
Родитель
Сommit
dafe9d736e

+ 67 - 76
commons-data-mysql/src/main/java/com/yihu/ehr/query/BaseJpaService.java

@ -25,7 +25,10 @@ import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
/**
 * Service基础类。此类基于Spring Data JPA进行封装(Spring Data JPA又是基于JPA封装,EHR平台使用Hibernate作为JPA实现者)。
@ -38,20 +41,19 @@ import java.util.*;
 */
@Transactional(propagation = Propagation.SUPPORTS)
public class BaseJpaService<T, R> {
    Class<R> repoClass;
    @PersistenceContext
    protected EntityManager entityManager;
    @Autowired
    protected JdbcTemplate jdbcTemplate;
    @Autowired
    protected ObjectMapper objectMapper;
    Class<R> repoClass;
    public BaseJpaService(){
    public BaseJpaService() {
        Type genType = getClass().getGenericSuperclass();
        if ((genType instanceof ParameterizedType)) {
            Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
            if (params.length==2) {
            if (params.length == 2) {
                repoClass = (Class) params[1];
            }
        }
@ -84,36 +86,44 @@ public class BaseJpaService<T, R> {
        return (Class) parameters[0];
    }
    public List search(String fields, String filters, String sorts, Integer page, Integer size) throws ParseException {
    public List<T> search(String fields, String filters, String sorts, Integer page, Integer size) throws ParseException {
        URLQueryParser queryParser = createQueryParser(fields, filters, sorts);
        CriteriaQuery query = queryParser.makeCriteriaQuery();
        if (page == null || page <= 0) page = PageArg.DefaultPage;
        if (size == null || size <= 0 || size > 10000) size = PageArg.DefaultSize;
        if (page == null || page <= 0) {
            page = PageArg.DefaultPage;
        }
        if (size == null || size <= 0 || size > 10000) {
            size = PageArg.DefaultSize;
        }
        return entityManager
        List resultList = entityManager
                .createQuery(query)
                .setFirstResult((page - 1) * size)
                .setMaxResults(size)
                .getResultList();
        return (List<T>) resultList;
    }
    public List search(String filters) throws ParseException {
    public List<T> search(String filters) throws ParseException {
        URLQueryParser queryParser = createQueryParser("", filters, "");
        CriteriaQuery query = queryParser.makeCriteriaQuery();
        return entityManager
        List resultList = entityManager
                .createQuery(query)
                .getResultList();
        return (List<T>) resultList;
    }
    public List search(String filters,String sorts) throws ParseException {
    public List<T> search(String filters, String sorts) throws ParseException {
        URLQueryParser queryParser = createQueryParser("", filters, sorts);
        CriteriaQuery query = queryParser.makeCriteriaQuery();
        return entityManager
        List resultList = entityManager
                .createQuery(query)
                .getResultList();
        return (List<T>) resultList;
    }
    public long getCount(String filters) throws ParseException {
@ -123,51 +133,15 @@ public class BaseJpaService<T, R> {
        return (long) entityManager.createQuery(query).getSingleResult();
    }
    protected <T> URLQueryParser createQueryParser(String fields, String filters, String orders) {
        URLQueryParser queryParser = new URLQueryParser<T>(fields, filters, orders)
                .setEntityManager(entityManager)
                .setEntityClass(getEntityClass());
        return queryParser;
    }
    protected <T> URLQueryParser createQueryParser(String filters) {
        URLQueryParser queryParser = new URLQueryParser<T>(filters)
                .setEntityManager(entityManager)
                .setEntityClass(getEntityClass());
        return queryParser;
    }
    protected Sort parseSorts(String sorter){
        if (StringUtils.isNotEmpty(sorter)) {
            String[] orderArray = sorter.split(",");
            List<Sort.Order> orderList = new ArrayList<>(orderArray.length);
            Arrays.stream(orderArray).forEach(
                    elem -> orderList.add(
                            elem.startsWith("+") ? new Sort.Order(Sort.Direction.ASC, elem.substring(1)):
                                    new Sort.Order(Sort.Direction.DESC, elem.substring(1))));
            return new Sort(orderList);
        }
        return null;
    }
    protected Session currentSession() {
        return entityManager.unwrap(Session.class);
    }
    public PagingAndSortingRepository getRepository() {
        return (PagingAndSortingRepository) SpringContext.getService(repoClass);
    }
    public JpaRepository getJpaRepository(){
    public JpaRepository getJpaRepository() {
        return (JpaRepository) SpringContext.getService(repoClass);
    }
    public List<T> findByField(String field, Object value){
    public List<T> findByField(String field, Object value) {
        return findByFields(
                new String[]{field},
@ -175,37 +149,38 @@ public class BaseJpaService<T, R> {
        );
    }
    public List<T> findByFields(String[] fields, Object[] values){
    public List<T> findByFields(String[] fields, Object[] values) {
        CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
        CriteriaQuery query = criteriaBuilder.createQuery(getEntityClass());
        Root<T> root = query.from(getEntityClass());
        List<Predicate> ls = new ArrayList<>();
        for(int i=0; i< fields.length; i++){
            if(values[i].getClass().isArray())
                ls.add(criteriaBuilder.in(root.get(fields[i]).in((Object[])values[i])));
            else
        for (int i = 0; i < fields.length; i++) {
            if (values[i].getClass().isArray()) {
                ls.add(criteriaBuilder.in(root.get(fields[i]).in((Object[]) values[i])));
            } else {
                ls.add(criteriaBuilder.equal(root.get(fields[i]), values[i]));
            }
        }
        query.where(ls.toArray(new Predicate[ls.size()]));
        return entityManager
        List resultList = entityManager
                .createQuery(query)
                .getResultList() ;
                .getResultList();
        return (List<T>) resultList;
    }
    public String getClzName(){
    public String getClzName() {
        return getEntityClass().getName();
    }
    public String getEntityIdFiled(){
    public String getEntityIdFiled() {
        EntityType entityType = entityManager.getMetamodel().entity(getEntityClass());
        javax.persistence.metamodel.Type type = entityType.getIdType();
        String s = entityType.getId(type.getJavaType()).getName();
        return s;
    }
    public int delete(Object[] ids){
        String hql = " DELETE FROM "+getEntityClass().getName()+" WHERE "+getEntityIdFiled()+" in(:ids)";
    public int delete(Object[] ids) {
        String hql = " DELETE FROM " + getEntityClass().getName() + " WHERE " + getEntityIdFiled() + " in(:ids)";
        Query query = currentSession().createQuery(hql);
        query.setParameterList("ids", ids);
        return query.executeUpdate();
@ -225,20 +200,36 @@ public class BaseJpaService<T, R> {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }
    /**
     * 获取指定长度的随机字符串
     * @param length
     * @return
     */
    protected String getRandomString(int length) {
        String str = "abcdefghigklmnopkrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ0123456789";
        StringBuffer buffer = new StringBuffer();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(str.length() - 1);//0~61
            buffer.append(str.charAt(number));
    protected <t> URLQueryParser createQueryParser(String fields, String filters, String orders) {
        return new URLQueryParser<t>(fields, filters, orders)
                .setEntityManager(entityManager)
                .setEntityClass(getEntityClass());
    }
    protected <t> URLQueryParser createQueryParser(String filters) {
        return new URLQueryParser<t>(filters)
                .setEntityManager(entityManager)
                .setEntityClass(getEntityClass());
    }
    protected Sort parseSorts(String sorter) {
        if (StringUtils.isNotEmpty(sorter)) {
            String[] orderArray = sorter.split(",");
            List<Sort.Order> orderList = new ArrayList<>(orderArray.length);
            Arrays.stream(orderArray).forEach(
                    elem -> orderList.add(
                            elem.startsWith("+") ? new Sort.Order(Sort.Direction.ASC, elem.substring(1)) :
                                    new Sort.Order(Sort.Direction.DESC, elem.substring(1))));
            return new Sort(orderList);
        }
        return buffer.toString();
        return null;
    }
    protected Session currentSession() {
        return entityManager.unwrap(Session.class);
    }
}

+ 33 - 10
commons-data-redis/src/main/java/com/yihu/ehr/redis/client/RedisClient.java

@ -6,6 +6,8 @@ import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.StringRedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.stereotype.Service;
import org.springframework.util.SerializationUtils;
@ -46,11 +48,11 @@ public class RedisClient {
     * @param key
     * @param value
     */
    public void set(final String key, final Serializable value,long seconds) {
    public void set(final String key, final Serializable value, long seconds) {
        redisTemplate.execute((RedisCallback<Object>) connection -> {
            byte[] key_ = key.getBytes();
            byte[] value_ = SerializationUtils.serialize(value);
            connection.setEx(key_,seconds, value_);
            connection.setEx(key_, seconds, value_);
            return true;
        });
    }
@ -60,12 +62,12 @@ public class RedisClient {
     *
     * @param data
     */
    public void multiSet(Map<Serializable, Serializable> data){
    public void multiSet(Map<Serializable, Serializable> data) {
        redisTemplate.executePipelined(new RedisCallback<Object>() {
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                StringRedisConnection stringRedisConn = (StringRedisConnection)connection;
                for(Serializable key : data.keySet()){
                StringRedisConnection stringRedisConn = (StringRedisConnection) connection;
                for (Serializable key : data.keySet()) {
                    Serializable value = data.get(key);
                    connection.rPushX(SerializationUtils.serialize(key), SerializationUtils.serialize(value));
                }
@ -80,7 +82,7 @@ public class RedisClient {
     *
     * @param data
     */
    public void multiSetData(Map<String, Serializable> data){
    public void multiSetData(Map<String, Serializable> data) {
        redisTemplate.executePipelined(new RedisCallback<Object>() {
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
@ -104,10 +106,12 @@ public class RedisClient {
     * @return
     */
    public <T> T get(final String key) {
        return (T)redisTemplate.execute((RedisCallback<Serializable>) connection -> {
        return (T) redisTemplate.execute((RedisCallback<Serializable>) connection -> {
            byte[] keyBytes = key.getBytes();
            byte[] bytes = connection.get(keyBytes);
            if(bytes == null) return null;
            if (bytes == null) {
                return null;
            }
            return (Serializable) SerializationUtils.deserialize(bytes);
        });
@ -119,8 +123,24 @@ public class RedisClient {
     * @param keys
     * @return
     */
    public List<Serializable> multiGet(Collection<String> keys){
        return redisTemplate.opsForValue().multiGet(keys);
    public List<Object> multiGet(Collection<String> keys) {
        return redisTemplate.executePipelined((RedisCallback<Object>) connection -> {
            keys.forEach(key -> {
                byte[] keyBytes = key.getBytes();
                connection.get(keyBytes);
            });
            return null;
        }, new RedisSerializer<Serializable>() {
            @Override
            public byte[] serialize(Serializable serializable) throws SerializationException {
                return SerializationUtils.serialize(serializable);
            }
            @Override
            public Serializable deserialize(byte[] bytes) throws SerializationException {
                return (Serializable) SerializationUtils.deserialize(bytes);
            }
        });
    }
    /**
@ -134,6 +154,7 @@ public class RedisClient {
    /**
     * 删除多条记录,如果Key集合过大,建议使用Key模糊匹配删除
     *
     * @param keys
     */
    public void delete(Collection<String> keys) {
@ -142,6 +163,7 @@ public class RedisClient {
    /**
     * 匹配特定模式的Key列表
     *
     * @param pattern
     * @return
     */
@ -158,6 +180,7 @@ public class RedisClient {
    /**
     * 是否包含指定Key
     *
     * @param key
     * @return
     */

+ 2 - 2
commons-util/src/main/java/com/yihu/ehr/util/encrypt/RSA.java

@ -77,7 +77,7 @@ public class RSA {
    /**
     * @param data 明文
     * @param key  密钥
     * @return HexString密文
     * @return Base64String密文
     * @throws Exception
     */
    public static String encrypt(String data, Key key) throws Exception {
@ -88,7 +88,7 @@ public class RSA {
    }
    /**
     * @param data HexString密文
     * @param data Base64String密文
     * @param key  密钥
     * @return 明文
     * @throws Exception

+ 2 - 8
hos-web-framework/pom.xml

@ -18,9 +18,8 @@
    <dependencies>
        <dependency>
            <groupId>happy.fish</groupId>
            <artifactId>fastDFS</artifactId>
            <version>1.1.0</version>
            <groupId>com.yihu.ehr</groupId>
            <artifactId>commons-data-fastdfs</artifactId>
        </dependency>
        <dependency>
@ -63,11 +62,6 @@
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <scope>${dependency.scope}</scope>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>

+ 2 - 0
pom.xml

@ -16,6 +16,7 @@
    <description>EHR library parent pom</description>
    <modules>
        <module>ehr-cloud-parent</module>
        <module>commons-ehr-constants</module>
        <module>commons-ui-swagger</module>
        <module>commons-util</module>
@ -34,5 +35,6 @@
        <module>commons-metrics</module>
        <module>commons-entity</module>
        <module>commons-cat</module>
        <module>hos-web-framework</module>
    </modules>
</project>