HibernateCRUD基础框架(2)-HQL语句构造器(HqlQueryBuilder,HqlUpdateBuilder)

上篇讲述了最基本的实体类,本篇接着讲述HQL语句构造器,包括查询和更新等。

优点:通过面向对象的方式构造HQL语句,更快捷,不需要手动拼接HQL。

缺点:封装可能降低性能,只能支持常用的和较为简单的HQL构造。

部分功能不完善,待开发。

1.HQL语句构造器

package cn.fansunion.hibernate.sql;

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

import cn.fansunion.hibernate.sql.entity.From;
import cn.fansunion.hibernate.sql.entity.GroupBy;
import cn.fansunion.hibernate.sql.entity.OrderGroup;
import cn.fansunion.hibernate.sql.entity.SearchCondition;

/**
 * HQL语句构造器。
 * <p/>
 * 目前只适用于1张表的情况,只有查询条件支持占位符,建议使用完全构造的sql语句(是否会产生sql注入,待研究)。
 *
 * @author LeiWen@FansUnion.cn
 */
public class HqlQueryBuilder extends ConstantBase {

    // 查询条件组合策略
    // -----------------------------------
    // *************From******************
    // -----------------------------------
    private String select;

    private From from;

    // -----------------------------------
    // *************Where******************
    // -----------------------------------
    private SearchCondition searchCondition;

    // -----------------------------------
    // *************Group by**************
    // -----------------------------------

    private GroupBy groupBy;

    // -----------------------------------
    // *************Order by******************
    // -----------------------------------
    private OrderGroup orderGroup;

    // -----------------------------------
    // 通过构造方法,创建查询构造器。各种字段组合形式的构造方法太多,只给出3种比较常见的。
    // 建议使用链式构造或setter方法设置属性。
    // -----------------------------------
    public HqlQueryBuilder() {

    }

    public HqlQueryBuilder(From from) {
        this.from = from;
    }

    public HqlQueryBuilder(From from, SearchCondition searchCondition,
            GroupBy groupBy, OrderGroup orderGroup) {
        this.from = from;

        this.searchCondition = searchCondition;
        this.groupBy = groupBy;
        this.orderGroup = orderGroup;
    }

    public HqlQueryBuilder select(String select) {
        this.select = select;
        return this;
    }

    // -----------------------------------
    // 支持链式用法,暂时不能很好地支持**************
    // -----------------------------------
    public HqlQueryBuilder from(From from) {
        this.from = from;
        return this;
    }

    public HqlQueryBuilder from(String model) {
        doFrom(model, "");
        return this;
    }

    public HqlQueryBuilder from(String model, String alias) {
        doFrom(model, alias);
        return this;
    }

    public HqlQueryBuilder from(Class<?> clazz) {
        doFrom(clazz.getSimpleName());
        return this;
    }

    public HqlQueryBuilder from(Class<?> clazz, String alias) {
        doFrom(clazz.getSimpleName(), alias);
        return this;
    }

    private void doFrom(String model) {
        doFrom(model, null);
    }

    private void doFrom(String model, String alias) {
        this.from = new From(model, alias);
    }

    public HqlQueryBuilder searchCodition(SearchCondition searchCondition) {
        this.searchCondition = searchCondition;
        return this;
    }

    public HqlQueryBuilder groupBy(GroupBy groupBy) {
        this.groupBy = groupBy;
        return this;
    }

    public HqlQueryBuilder orderBy(OrderGroup orderGroup) {
        this.orderGroup = orderGroup;
        return this;
    }

    /**
     * 转换成HQL语句
     */
    public String toHql() {

        StrBuilder builder = new StrBuilder();
        if (select != null) {
            builder.append(select).append(EMPTY);
        }
        if (from != null) {
            builder.append(from);
        }

        if (searchCondition != null) {
            builder.append(searchCondition);
        }
        if (groupBy != null) {
            builder.append(groupBy);
        }
        if (orderGroup != null) {
            builder.append(orderGroup);
        }

        return builder.toString();
    }

}


2.Hql更新语句构造器

下面这个是构造更新HQL语句的构造器,待完善。

package cn.fansunion.hibernate.sql.update;

import java.util.HashMap;
import java.util.Map;

import cn.fansunion.hibernate.util.Pair;

/**
 * Hql更新语句构造器。(TODO 待完善)
 *
 * @author LeiWen@FansUnion.cn
 */
public class HqlUpdateBuilder {

    private Map<String, Object> params;

    private String model;

    public HqlUpdateBuilder() {
        params = new HashMap<String, Object>();
    }

    public HqlUpdateBuilder(String model) {

    }

    public HqlUpdateBuilder(Class<?> model) {
        this.model = model.getSimpleName();
    }

    public HqlUpdateBuilder model(String model) {
        this.model = model;
        return this;
    }

    public HqlUpdateBuilder model(Class<?> model) {
        this.model = model.getSimpleName();
        return this;
    }

    public HqlUpdateBuilder param(String key, Object value) {
        params.put(key, value);
        return this;
    }

    public HqlUpdateBuilder param(Pair... pair) {
        for (Pair p : pair) {
            params.put(p.getKey(), p.getValue());
        }
        return this;
    }

    public HqlUpdateBuilder param(Map<String, Object> params) {
        this.params.putAll(params);
        return this;
    }

    public String toHql() {
        String hql = "update " + model + " set ";
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            String key = entry.getKey();
            hql += key + "=:" + key + " ";
        }
        return hql;
    }

}


3.原生SQL语句构造器

类似的,有时候,可能不用Hibernate的HQL,而是用原生的SQL。

这个时候,可以编写与HqlQueryBuilder和HqlUpdateBuilder相应的SQL版本。

package cn.fansunion.hibernate.sql;

import cn.fansunion.hibernate.sql.entity.Limit;

/**
 * 原生SQL语句构造器。(TODO 待完善)
 *
 * @author LeiWen@FansUnion.cn
 */
public class SqlQueryBuilder {
    // limit只适用于nativeSQL
    // -----------------------------------
    // *************limit**************
    // -----------------------------------
    private Limit limit;
    
    /**
     * 转换成SQL语句
     */
    
    public String toSql(){
        //TODO
        return null;
    }
}


4.HQL查询构造器使用例子

/**
 * HQL查询构造器使用例子。
 *
 * @author LeiWen@FansUnion.cn
 */
public class HqlQueryBuilderTest extends ConstantBase {

    @Test
    public void test() {
        From from = new From(HqlQueryBuilder.class);
        SearchCondition searchCondition = createSearchCondtion();
        OrderGroup orderGroup = createOrderGroup();
        GroupBy groupBy = createGroupBy();
        HqlQueryBuilder builder = new HqlQueryBuilder(from, searchCondition,
                groupBy, orderGroup);
        // 直接打印,不使用“断言”
        println(builder.toHql());
    }

    private GroupBy createGroupBy() {
        GroupBy groupBy = new GroupBy();
        groupBy.addGroup("name");
        groupBy.addGroup("id");
        return groupBy;
    }

    private OrderGroup createOrderGroup() {
        Order order1 = new Order("id", false);
        Order order2 = new Order("name", "asc");

        OrderGroup orderGroup = new OrderGroup(order1, order2);
        return orderGroup;
    }

    private SearchCondition createSearchCondtion() {
        GroupCondition groupCondition1 = oneGroupCondition();
        GroupCondition groupCondition2 = oneGroupCondition();
        //String groupStr1 = groupCondition1.toString();
        //String groupStr2 = groupCondition2.toString();
        // System.out.println(groupStr1);
        // System.out.println(groupStr2);

        SearchCondition searchCondition = new SearchCondition();
        searchCondition.addGroupCondition(groupCondition1);
        searchCondition.addGroupCondition(groupCondition2, true);
        //String searchStr = searchCondition.toString();
        // System.out.println(searchStr);
        return searchCondition;
    }

    private GroupCondition oneGroupCondition() {
        // =,Integer
        String age = "age";
        Integer ageValue = 24;
        Condition condition2 = new Condition(age, Operator.EQUALS, ageValue);
        String str2 = condition2.toString();

        Assert.assertEquals(str2, age + EQUALS_WITH_BLANK + ageValue);

        // =,String
        String name = "name";
        String nameValue = "LeiWen@FansUnion.cn";
        Condition condition = new Condition(name, Operator.EQUALS, nameValue);
        String str = condition.toString();
        Assert.assertEquals(str, name + EQUALS_WITH_BLANK
                + buildQuota(nameValue));

        // =,Date
        String date = "date";
        Date dateValue = new Date();
        Condition condition3 = new Condition(date, Operator.EQUALS, dateValue);
        String str3 = condition3.toString();
        Assert.assertEquals(str3, date + EQUALS_WITH_BLANK
                + buildQuota(dateValue));

        GroupCondition groupCondition1 = new GroupCondition();
        groupCondition1.addCondition(condition);
        groupCondition1.addCondition(condition2, true);
        groupCondition1.addCondition(condition3, false);
        return groupCondition1;
    }

}


5.输出结果

from HqlQueryBuilder where (name = 'LeiWen@FansUnion.cn' or age = 24 and date = 'Mon Dec 30 16:57:21 CST 2013')

or (name = 'LeiWen@FansUnion.cn' or age = 24 and date = 'Mon Dec 30 16:57:21 CST 2013')

group by name,id order by id desc,name asc

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

发布了1313 篇原创文章 · 获赞 2520 · 访问量 339万+
展开阅读全文

springboot集成hibernate

04-08

![图片说明](https://img-ask.csdn.net/upload/201904/08/1554710323_404518.png)![图片说明](https://img-ask.csdn.net/upload/201904/08/1554710334_239729.png)![图片说明](https://img-ask.csdn.net/upload/201904/08/1554710339_812732.png)![图片说明](https://img-ask.csdn.net/upload/201904/08/1554710348_791449.png)![图片说明](https://img-ask.csdn.net/upload/201904/08/1554710360_729464.png) java.lang.IllegalStateException: Failed to load ApplicationContext at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125) at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108) at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:190) at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:132) at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190) at org.junit.runner.JUnitCore.run(JUnitCore.java:137) at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68) at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47) at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242) at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70) Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'TUserDaoImpl': Unsatisfied dependency expressed through method 'setSessionFactoryOverride' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sessionFactory' defined in com.example.demo.DemoApplication: Unsatisfied dependency expressed through method 'sessionFactory' parameter 0; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'sessionFactory': Requested bean is currently in creation: Is there an unresolvable circular reference? at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:676) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1411) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:592) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:849) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775) at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:127) at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99) at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:117) ... 24 more Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sessionFactory' defined in com.example.demo.DemoApplication: Unsatisfied dependency expressed through method 'sessionFactory' parameter 0; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'sessionFactory': Requested bean is currently in creation: Is there an unresolvable circular reference? at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:769) at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:509) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1321) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1160) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1247) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1167) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:668) ... 42 more Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'sessionFactory': Requested bean is currently in creation: Is there an unresolvable circular reference? at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.beforeSingletonCreation(DefaultSingletonBeanRegistry.java:339) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:215) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1247) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1167) at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:857) at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:760) ... 55 more 已经两天了,我快奔溃了,有没有人救救我!!!!!!!! 主要是这个问题Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sessionFactory' defined in com.example.demo.DemoApplication: Unsatisfied dependency expressed through method 'sessionFactory' parameter 0; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'sessionFactory': Requested bean is currently in creation: Is there an unresolvable circular reference? 问答

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 猿与汪的秘密 设计师: 上身试试

分享到微信朋友圈

×

扫一扫,手机浏览