文档章节

HibernateCRUD基础框架(1)-实体类

FansUnion
 FansUnion
发布于 2015/05/03 01:31
字数 2124
阅读 12
收藏 0

HibernateCRUD基础框架包括3篇文章,主要讲述整个CRUD基础框架的思路。

第1篇:讲述最基本的实体类,这些实体类是对SQL语言中的一些概念的封装。

第2篇:在这些实体类的基础上,开发一个“HQL语句构造器-HqlQueryBuilder”。

第3篇:构建一套简单的和较为复杂的标准的CRUD API。


优点:提高代码复用,提升编码效率。

缺点:没有过多考虑性能,具体性能没有去检验。

      功能有限,只是针对常用的和较为简单的CRUD功能。


友情提示:注释已经写得比较清楚了,不再过多解释。

                    有问题,可以留言,抽空答复。


第1篇:实体类

1.常量和基础定义

package cn.fansunion.hibernate.sql;

/**
 * SQL关键字常量“and,like,where”,比较符常量">,<,="等常量。
 *
 * @author LeiWen@FansUnion.cn
 */
public class ConstantBase {

    /**
     * SQL关键字or
     */
    public static final String OR = "or";
    /**
     * SQL关键字and
     */
    public static final String AND = "and";
    /**
     * SQL关键字from
     */
    public static final String FROM = "from";
    /**
     * SQL关键字as
     */
    public static final String AS = "as";
    /**
     * SQL关键字where
     */
    public static final String WHERE = "where";
    /**
     * SQL关键字asc
     */
    public static final String ASC = "asc";
    /**
     * SQL关键字desc
     */
    public static final String DESC = "desc";
    /**
     * SQL关键字in
     */
    public static final String IN = "in";
    /**
     * not in
     */
    public static final String NOT_IN = "not in";
    /**
     * SQL关键字like
     */
    public static final String LIKE = "like";
    /**
     * not like
     */
    public static final String NOT_LIKE = "not like";
    /**
     * order by
     */
    public static final String ORDER_BY = "order by";
    /**
     * group by
     */
    public static final String GROUP_BY = "group by";
    /**
     * SQL关键字limit
     */
    public static final String LIMIT = "limit";
    /**
     * 冒号
     */
    public static final String COLON = ":";
    /**
     * 逗号
     */
    public static final String COMMA = ",";
    /**
     * 一个空格
     */
    public static final String BLANK = " ";
    /**
     * 一个空字符串
     */
    public static final String EMPTY = "";
    /**
     *
     */
    public static final boolean AUTO_ADD = true;
    /**
     * 右括号
     */
    public static final String RIGHT_BRACKET = ")";
    /**
     * 左括号
     */
    public static final String LEFT_BRACKET = "(";
    /**
     * 百分号
     */
    public static final String PERCENT = "%";
    /**
     * 单引号
     */
    public static final String SINGLE_QUOTATION_MARK = "'";
    /**
     * 等号
     */
    public static final String EQUALS = "=";
    /**
     * 不等
     */
    public static final String NOT_EQUALS = "!=";
    /**
     * 大于号
     */
    public static final String GREAT_THAN = ">";
    /**
     * 小于号
     */
    public static final String LESS_THAN = "<";
    /**
     * 大于等于
     */
    public static final String GREAT_THAN_EQUALS = ">=";
    /**
     * 小于等于
     */
    public static final String LESS_THAN_EQUALS = "<=";

    // *************************************
    // **********左右分别加1个空格的常量*****************
    // *************************************
    public static final String EQUALS_WITH_BLANK = buildBlank(EQUALS);
    public static final String NOT_EQUALS_WITH_BLANK = buildBlank(NOT_EQUALS);

    public static final String GREAT_THAN_WITH_BLANK = buildBlank(GREAT_THAN);
    public static final String LESS_THAN_WITH_BLANK = buildBlank(LESS_THAN);

    public static final String GREAT_THAN_EQUALS_WITH_BLANK = buildBlank(GREAT_THAN_EQUALS);
    public static final String LESS_THAN_EQUALS_WITH_BLANK = buildBlank(LESS_THAN_EQUALS);

    public static final String IN_WITH_BLANK = buildBlank(IN);
    public static final String NOT_IN_WITH_BLANK = buildBlank(NOT_IN);

    public static final String LIKE_WITH_BLANK = buildBlank(LIKE);
    public static final String NOT_LIKE_WITH_BLANK = buildBlank(NOT_LIKE);

    public static final String ORDER_BY_WITH_BLANK = buildBlank(ORDER_BY);
    public static final String GROUP_BY_WITH_BLANK = buildBlank(GROUP_BY);

    public static final String LIMIT_WITH_BLANK = buildBlank(LIMIT);
    public static final String WHERE_WITH_BLANK = buildBlank(WHERE);
    public static final String AS_WITH_BLANK = buildBlank(AS);

    /**
     * 返回变量对应的字符串值
     *
     * @param or
     * @return true返回“or”,false返回"and"
     */
    public static String isOr(Boolean or) {
        String str = AND;
        if (or) {
            str = OR;
        }
        return str;
    }

    /**
     * 在字符串的左边加上百分号"%",在字符串的右边加上百分号"%"
     *
     * @param str
     *            字符串
     * @return 被"%%"包围起来的新的字符串
     */
    public static String buildLike(Object str) {
        String newStr = PERCENT + str + PERCENT;
        return newStr;
    }

    /**
     * 在一个字符串的左边和右边都加上一个空格
     *
     * @param str
     * @return 新的字符串
     */
    public static String buildBlank(Object str) {
        String newStr = BLANK + str + BLANK;
        return newStr;
    }

    /**
     * 在字符串的左边和右边加上单引号"'"
     *
     * @param str
     *            字符串
     * @return 被"''"包围起来的新的字符串
     */
    public static String buildQuota(Object str) {
        String newStr = SINGLE_QUOTATION_MARK + str + SINGLE_QUOTATION_MARK;
        return newStr;
    }

    /**
     * 在字符串的左边加上左括号"(",在字符串的右边加上右括号")"
     *
     * @param str
     *            字符串
     * @return 被"()"包围起来的新的字符串
     */
    public static String buildBracket(Object str) {
        String newStr = LEFT_BRACKET + str + RIGHT_BRACKET;
        return newStr;
    }

    public static void println(Object object) {
        System.out.println(object);
    }

    public static void print(Object object) {
        System.out.print(object);
    }
}

package cn.fansunion.hibernate.sql;

/**
 * 操作符的类型,如"= != > >= < <="。
 *
 * @author LeiWen@FansUnion.cn
 */
public enum Operator {

    EQUALS, NOT_EQUALS, GREAT_THAN, GREAT_THAN_EQUALS, LESS_THAN, LESS_THAN_EQUALS, LIKE, NOT_LIKE, IN, NOT_IN;
    /**
     * 转化为字符串(TODO 放在一个单独的工具类里比较合适)
     */
    public static String toString(Operator operator) {
        String str = "";

        switch (operator) {
        case EQUALS:
            str = ConstantBase.EQUALS;
            break;

        case NOT_EQUALS:
            str = ConstantBase.NOT_EQUALS;
            break;

        case GREAT_THAN:
            str = ConstantBase.GREAT_THAN;
            break;

        case GREAT_THAN_EQUALS:
            str = ConstantBase.GREAT_THAN_EQUALS;
            break;

        case LESS_THAN:
            str = ConstantBase.LESS_THAN;
            break;

        case LESS_THAN_EQUALS:
            str = ConstantBase.LESS_THAN_EQUALS;
            break;

        case LIKE:
            str = ConstantBase.LIKE;
            break;

        case NOT_LIKE:
            str = ConstantBase.NOT_LIKE;
            break;

        case IN:
            str = ConstantBase.IN;
            break;

        case NOT_IN:
            str = ConstantBase.NOT_IN;
            break;

        default:
            break;
        }
        return str;
    }
}


public enum AndOr {
    AND, OR
}

2.实体类


package cn.fansunion.hibernate.sql.entity;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.text.StrBuilder;

import cn.fansunion.hibernate.sql.ConstantBase;

/**
 * From语句,如"from User user"。
 *
 * @author LeiWen@FansUnion.cn
 */
public class From extends ConstantBase {
    /**
     * 实体类的class,如User.class
     */
    private Class<?> modelClazz;
    /**
     * 实体类Class的字符串表示,如User
     */
    private String model;
    /**
     * 别名,如user
     */
    private String alias;

    public From() {
        super();
    }

    public From(Class<?> modelClazz) {
        super();
        this.modelClazz = modelClazz;
    }

    public From(Class<?> modelClazz, String alias) {
        super();
        this.modelClazz = modelClazz;
        this.alias = alias;
    }

    public From(String model) {
        super();
        this.model = model;
    }

    public From(String model, String alias) {
        super();
        this.model = model;
        this.alias = alias;
    }

    //
    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }

    public Class<?> getModelClazz() {
        return modelClazz;
    }

    public void setModelClazz(Class<?> modelClazz) {
        this.modelClazz = modelClazz;
    }

    public String getAlias() {
        return alias;
    }

    public void setAlias(String alias) {
        this.alias = alias;
    }
    /**
     * 转化为字符串
     */
    public String toString() {
        if (modelClazz != null) {
            this.model = modelClazz.getSimpleName();
        }

        StrBuilder builder = new StrBuilder();
        if (StringUtils.isNotEmpty(model)) {
            builder.append(FROM).append(BLANK)
                    .append(modelClazz.getSimpleName());
            if (StringUtils.isNotEmpty(alias)) {
                builder.append(AS_WITH_BLANK).append(alias);
            }
        }

        return builder.toString();
    }

}


package cn.fansunion.hibernate.sql.entity;

import java.util.Date;

import cn.fansunion.hibernate.sql.ConstantBase;
import cn.fansunion.hibernate.sql.Operator;

/**
 * 1个查询条件。由3部分构成,键-操作-值,如 "age > 12 ","email ='LeiWen@FansUnion.cn'"等。
 *
 * @author LeiWen@FansUnion.cn
 */
public class Condition extends ConstantBase {
    /**
     * 条件的键
     */
    private String key;
    /**
     * 条件的操作符
     */
    private Operator operator;
    /**
     * 条件的值
     */
    private Object value;

    public Condition() {

    }

    public Condition(String key, Operator operator) {
        super();
        this.key = key;
        this.operator = operator;
    }

    public Condition(String key, Object value) {
        this.key = key;
        this.value = value;
    }

    public Condition(String key, Operator operator, Object value) {
        this.key = key;
        this.operator = operator;
        this.value = value;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public Operator getOperator() {
        return operator;
    }

    public void setOperator(Operator operator) {
        this.operator = operator;
    }

    public Object getValue() {
        return value;
    }

    public void setValue(Object value) {
        this.value = value;
    }

    /**
     * 转化为字符串
     */
    public String toString() {
        String str = "";

        String newValue = "";
        // 构造完整的语句
        if (value != null) {
            // 是否需要自动增加"%%","()"
            if (AUTO_ADD) {
                switch (operator) {
                case LIKE:

                case NOT_LIKE:
                    newValue = buildLike(value);
                    break;

                case IN:
                case NOT_IN:
                    newValue = buildBracket(value);
                    break;

                default:
                    break;
                }

                // 需要添加引号的类型
                boolean isString = value instanceof String;
                boolean isDate = value instanceof Date;
                boolean isSqlDate = value instanceof java.sql.Date;
                if (isString || isDate || isSqlDate) {
                    newValue = buildQuota(value);
                } else {
                    newValue = value.toString();
                }

            }
        }
        // 构造带有占位符的语句
        else {
            newValue = COLON + key;
        }
        // "name=a","name like a",统一都加个空格
        str += key + BLANK + Operator.toString(operator) + BLANK + newValue;
        return str;
    }
}


package cn.fansunion.hibernate.sql.entity;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.text.StrBuilder;

import cn.fansunion.hibernate.AndOr;
import cn.fansunion.hibernate.sql.ConstantBase;
import cn.fansunion.hibernate.util.EmptyUtils;

/**
 * 逻辑上属于1个组的条件。
 *
 * @author LeiWen@FansUnion.cn
 */
public class GroupCondition extends ConstantBase {
    /**
     * 多个条件构成的集合
     */
    private List<Condition> conditionList;

    /**
     * 组内各个条件之间的关系:且|或,默认为且
     */
    private List<Boolean> relationList;

    public static final Boolean AND = true;
    public static final Boolean OR = false;

    public GroupCondition() {
        conditionList = new ArrayList<Condition>();
        relationList = new ArrayList<Boolean>();
    }

    public void addCondition(Condition condition) {
        addCondition(condition, true);
    }

    public void addCondition(Condition condition, boolean or) {
        conditionList.add(condition);
        if (EmptyUtils.notEmpty(conditionList)) {
            relationList.add(or);
        }
    }

    public void addCondition(Condition condition, AndOr ao) {
        conditionList.add(condition);
        if (EmptyUtils.notEmpty(conditionList)) {
            if (ao == AndOr.AND) {
                relationList.add(AND);
            } else {
                relationList.add(OR);
            }
        }
    }

    public void addOr(int index, boolean or) {
        relationList.set(index, or);
    }

    /**
     * 转化为字符串
     */
    public String toString() {
        if (EmptyUtils.isEmpty(conditionList)) {
            return EMPTY;
        }

        StrBuilder builder = new StrBuilder();
        int size = conditionList.size();
        for (int index = 0; index < size; index++) {
            if (index == 0) {
                builder.append(conditionList.get(index));
            } else {
                builder.append(BLANK).append(isOr(relationList.get(index)))
                        .append(BLANK).append(conditionList.get(index));
            }
        }
        return builder.toString();
    }

}

package cn.fansunion.hibernate.sql.entity;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.text.StrBuilder;

import cn.fansunion.hibernate.sql.ConstantBase;
import cn.fansunion.hibernate.util.EmptyUtils;

/**
 * 搜索条件(2个组之间,且|或。)
 *
 * @author LeiWen@FansUnion.cn
 */
public class SearchCondition extends ConstantBase {

    /**
     * 多个组条件构成的集合
     */
    private List<GroupCondition> groupConditionList;

    /**
     * 多个组条件之间的关系:且|或,默认为且
     */
    private List<Boolean> and;

    public SearchCondition() {
        groupConditionList = new ArrayList<GroupCondition>();
        and = new ArrayList<Boolean>();

    }

    public void addGroupCondition(GroupCondition groupCondition) {
        addGroupCondition(groupCondition, false);
    }

    public void addGroupCondition(GroupCondition groupCondition, boolean or) {
        groupConditionList.add(groupCondition);
        if (EmptyUtils.notEmpty(groupConditionList)) {
            and.add(or);
        }
    }

    public void addOr(int index, boolean or) {
        and.set(index, or);
    }

    public List<GroupCondition> getGroupConditionList() {
        return groupConditionList;
    }

    public void setGroupConditionList(List<GroupCondition> groupConditionList) {
        this.groupConditionList = groupConditionList;
    }

    public List<Boolean> getAnd() {
        return and;
    }

    public void setAnd(List<Boolean> and) {
        this.and = and;
    }

    /**
     * 转化为字符串
     */
    public String toString() {
        if (EmptyUtils.isEmpty(groupConditionList)) {
            return EMPTY;
        }

        StrBuilder builder = new StrBuilder();

        int size = groupConditionList.size();
        for (int index = 0; index < size; index++) {
            // 1个组的条件用()包起来
            if (index == 0) {
                builder.append(WHERE_WITH_BLANK).append(
                        buildBracket(groupConditionList.get(index)));

            } else {
                builder.append(BLANK).append(isOr(and.get(index)))
                        .append(BLANK)
                        .append(buildBracket(groupConditionList.get(index)));
            }
        }

        return builder.toString();
    }
}

package cn.fansunion.hibernate.sql.entity;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.text.StrBuilder;

import cn.fansunion.hibernate.sql.ConstantBase;

/**
 *
 * 排序语句,如“order by id desc”。
 *
 * @author LeiWen@FansUnion.cn
 */
public class Order extends ConstantBase {
    /**
     * 排序语句的键
     */
    private String key;
    /**
     * 排序语句的升序或降序(字符串形式)
     */
    private String asc;
    /**
     * 排序语句的升序或降序(布尔形式)
     */
    private Boolean isAsc;

    public Order() {

    }

    public Order(String key, String asc) {
        this.key = key;
        this.asc = asc;
    }

    public Order(String key, Boolean isAsc) {
        super();
        this.key = key;
        this.isAsc = isAsc;
    }

    /**
     * 转化为字符串
     */
    public String toString() {
        String finalSort = DESC;

        if (StringUtils.isNotEmpty(asc)) {
            finalSort = asc;
        } else {
            if (isAsc) {
                finalSort = ASC;
            }
        }

        StrBuilder builder = new StrBuilder();
        builder.append(key).append(BLANK).append(finalSort);
        return builder.toString();
    }

}

package cn.fansunion.hibernate.sql.entity;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.text.StrBuilder;

import cn.fansunion.hibernate.sql.ConstantBase;
import cn.fansunion.hibernate.util.ListUtils;

/**
 * 排序组,如"order by id desc,name asc"。
 *
 * @author LeiWen@FansUnion.cn
 */
public class OrderGroup extends ConstantBase {
    /**
     * 多个排序构成的集合
     */
    private List<Order> orderList;

    public OrderGroup() {
        orderList = new ArrayList<Order>();
    }

    public OrderGroup(Order order) {
        this();
        orderList.add(order);
    }

    public OrderGroup(Order order1, Order order2) {
        this();
        orderList.add(order1);
        orderList.add(order2);
    }

    public void addOrder(Order order) {
        orderList.add(order);
    }
    /**
     * 转化为字符串
     */
    public String toString() {
        StrBuilder builder = new StrBuilder();
        if (ListUtils.notEmpty(orderList)) {
            String orders = ListUtils.list2String(orderList);
            builder.append(ORDER_BY_WITH_BLANK).append(orders);
        }
        return builder.toString();
    }

}

package cn.fansunion.hibernate.sql.entity;

import java.util.ArrayList;
import java.util.List;

import cn.fansunion.hibernate.sql.ConstantBase;
import cn.fansunion.hibernate.util.EmptyUtils;
import cn.fansunion.hibernate.util.ListUtils;

/**
 * 分组语句,如"group by id,name"。
 *
 * @author LeiWen@FansUnion.cn
 */
public class GroupBy extends ConstantBase {

    /**
     * 分组的字段名称构成的集合,暂时不支持having子句
     */
    private List<String> group;

    public GroupBy() {
        group = new ArrayList<String>();
    }

    public List<String> getGroup() {
        return group;
    }

    /**
     * 转化为字符串
     */
    public String toString() {
        if (EmptyUtils.notEmpty(group)) {
            String groupStr = ListUtils.list2String(group);
            return GROUP_BY_WITH_BLANK + groupStr;
        }
        return EMPTY;
    }

    public void addGroup(String g) {
        this.group.add(g);
    }
}

原文链接http://blog.fansunion.cn/articles/3616(小雷博客-blog.fansunion.cn)

© 著作权归作者所有

FansUnion
粉丝 60
博文 858
码字总数 825464
作品 0
丰台
高级程序员
私信 提问
海子cq/osframe

#osframe 框架介绍 本项目是一个基础后台开发框架,基于springmvc+spring+hibernate搭建,前端采用angular js+sea js +bootstrap展现。基础框架中包含了用户管理、权限管理等基础模块,提供了...

海子cq
2016/06/28
0
0
2.osframe框架开发说明书

开源项目名称: osframe管理系统 托管地址: http://git.oschina.net/haizicq/osframe 主要技术: spring mvc、spring、hibernate、angular js、seajs、bootstrap、shiro 框架介绍: 本框架是...

王春-海子
2016/06/28
171
1
【从零开始搭建自己的.NET Core Api框架】(六)泛型仓储的作用

系列目录 一. 创建项目并集成swagger   1.1 创建   1.2 完善 二. 搭建项目整体架构 三. 集成轻量级ORM框架——SqlSugar   3.1 搭建环境   3.2 实战篇:利用SqlSugar快速实现CRUD   ...

在7楼
2018/08/18
0
0
Entity Framework 实体框架的形成之旅--数据传输模型DTO和实体模型Entity的分离与联合B

在使用Entity Framework 实体框架的时候,我们大多数时候操作的都是实体模型Entity,这个和数据库操作上下文结合,可以利用LINQ等各种方便手段,实现起来非常方便,一切看起来很美好。但是如...

walb呀
2017/12/04
0
0
WCF项目中出现常见错误的解决方法:基础连接已经关闭: 连接被意外关闭

在我们开发WCF项目的时候,常常会碰到一些莫名其妙的错误,有时候如果根据它的错误提示信息,一般很难定位到具体的问题所在,而由于WCF服务的特殊性,调试起来也不是那么方便,因此往往会花费...

walb呀
2017/12/04
0
0

没有更多内容

加载失败,请刷新页面

加载更多

c++队列(转自本人csdn)

#include using namespace std;int main(){char input, alphabet = ‘A’;cout << "输入最后一个大写字母: ";cin >> input;for(int i = 1; i <= (input-'A'+1); ++i)......

WinkJie
30分钟前
1
0
外观模式(Facade)

//这篇写的可以 https://www.jianshu.com/p/f71051475e32

南桥北木
48分钟前
2
0
锤子科技确认卖身,官网微博均变更所属公司

年前曾有过消息,罗永浩创办的锤子科技将被今日头条和抖音的母公司字节跳动收购。其中的部分工作人员将随专利一同成为字节跳动所属,而罗永浩本人将离开锤子科技。 今天我们终于看到了锤子科...

linux-tao
55分钟前
2
0
[json]阿里fastjson1.2.24字符串转为json对象/数组

java.lang.ClassCastException: com.alibaba.fastjson.JSONArray cannot be cast to com.alibaba.fastjson.JSONObject at com.alibaba.fastjson.JSON.parseObject(JSON.java:206) 多行要用J......

Danni3
今天
1
0
关于jenkins 构建打包的技巧

关于jenkins 构建打包的技巧 jenkins是一个专业构建平台,在各大公司内部比较受欢迎,可以自定义构建方式,以下整理一些技巧,防止以后忘记。 邮件通知 jenkins 自带邮件通知功能,但是比较单...

shzwork
今天
4
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部