首页 \ 问答 \ 弹簧石英的问题(Problem with spring quartz)

弹簧石英的问题(Problem with spring quartz)

我想基于一段时间间隔调用方法,下面是applicationContext.xml中的一些bean

<bean id="MngtTarget"
  class="com.management.engine.Implementation" 
  abstract="false" lazy-init="true" autowire="default" dependency-check="default">

    <bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
      <property name="targetObject" ref="MngtTarget" />
      <property name="targetMethod" value="findItemByPIdEndDate"/>
    </bean>


    <bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">

        <property name="jobDetail" ref="jobDetail" />
        <!-- 10 seconds -->
        <property name="startDelay" value="10000" />
        <!-- repeat every 50 seconds -->
        <property name="repeatInterval" value="20000" />
    </bean>


    <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="triggers">
            <list>
                <ref bean="simpleTrigger" />
            </list>
        </property>
    </bean>

这是我试图调用的方法:

public List<Long> I need findItemByPIdEndDate() throws Exception {

                List<Long> list = null;

                try{
                        Session session = sessionFactory.getCurrentSession();

                        Query query = session.getNamedQuery("endDateChecker");
                        list =  query.list();

                        for(int i=0; i<list.size(); i++)
                        {
                                System.out.println(list.get(i));
                        }

                        System.out.println("Total " + list.size());

                }catch (HibernateException e){
                        throw new DataAccessException(e.getMessage());
                }

                return list;
        }

这是我得到的异常消息:

Invocation of method 'findItemByPIdEndDate' on target class [class com.management.engine.Implementation] failed; nested exception is No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here

到目前为止,我花了很多时间搜索google,还试图修改我的方法,如下所示:

 public List<Long> I need findItemByPIdEndDate() throws Exception {

                    List<Long> list = null;

                    try{
                            Session session = sessionFactory.openSession();

                            Query query = session.getNamedQuery("endDateChecker");
                            list =  query.list();

                            for(int i=0; i<list.size(); i++)
                            {
                                    System.out.println(list.get(i));
                            }

                            System.out.println("Total " + list.size());
                            session.close();
                    }catch (HibernateException e){
                            throw new DataAccessException(e.getMessage());
                    }

                    return list;
            }

我得到不同的错误消息,我得到: Invocation of method 'findItemByPIdEndDate' on target class [class com.management.engine.Implementation] failed; nested exception is could not execute query] Invocation of method 'findItemByPIdEndDate' on target class [class com.management.engine.Implementation] failed; nested exception is could not execute query] ,任何人都知道这是什么,任何建议? 谢谢

也是我的queries.hbm.xml

<hibernate-mapping>

<sql-query name="endDateChecker">
<return-scalar column="PId" type="java.lang.Long"/>
      <![CDATA[select
   item_pid as PId
     from
         item
        where
        end_date < trunc(sysdate)]]>      
 </sql-query> 
</hibernate-mapping>

I'm trying to invoke method based on some interval time, here are some beans inside applicationContext.xml

<bean id="MngtTarget"
  class="com.management.engine.Implementation" 
  abstract="false" lazy-init="true" autowire="default" dependency-check="default">

    <bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
      <property name="targetObject" ref="MngtTarget" />
      <property name="targetMethod" value="findItemByPIdEndDate"/>
    </bean>


    <bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">

        <property name="jobDetail" ref="jobDetail" />
        <!-- 10 seconds -->
        <property name="startDelay" value="10000" />
        <!-- repeat every 50 seconds -->
        <property name="repeatInterval" value="20000" />
    </bean>


    <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="triggers">
            <list>
                <ref bean="simpleTrigger" />
            </list>
        </property>
    </bean>

Here is the method I'm trying to invoke :

public List<Long> I need findItemByPIdEndDate() throws Exception {

                List<Long> list = null;

                try{
                        Session session = sessionFactory.getCurrentSession();

                        Query query = session.getNamedQuery("endDateChecker");
                        list =  query.list();

                        for(int i=0; i<list.size(); i++)
                        {
                                System.out.println(list.get(i));
                        }

                        System.out.println("Total " + list.size());

                }catch (HibernateException e){
                        throw new DataAccessException(e.getMessage());
                }

                return list;
        }

Here is the exception message that I get :

Invocation of method 'findItemByPIdEndDate' on target class [class com.management.engine.Implementation] failed; nested exception is No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here

I've spent time googling alot so far also I've tried to modify my method like this :

 public List<Long> I need findItemByPIdEndDate() throws Exception {

                    List<Long> list = null;

                    try{
                            Session session = sessionFactory.openSession();

                            Query query = session.getNamedQuery("endDateChecker");
                            list =  query.list();

                            for(int i=0; i<list.size(); i++)
                            {
                                    System.out.println(list.get(i));
                            }

                            System.out.println("Total " + list.size());
                            session.close();
                    }catch (HibernateException e){
                            throw new DataAccessException(e.getMessage());
                    }

                    return list;
            }

And I get different error msg, I get : Invocation of method 'findItemByPIdEndDate' on target class [class com.management.engine.Implementation] failed; nested exception is could not execute query] , anyone knows what is this all about, any suggestions ? thank you

Also my queries.hbm.xml

<hibernate-mapping>

<sql-query name="endDateChecker">
<return-scalar column="PId" type="java.lang.Long"/>
      <![CDATA[select
   item_pid as PId
     from
         item
        where
        end_date < trunc(sysdate)]]>      
 </sql-query> 
</hibernate-mapping>

原文:https://stackoverflow.com/questions/1613638
更新时间:2024-05-22 12:05

最满意答案

适合我的工作:

public class UserAdminTest {
    static class DBConnection { boolean isAdmin(String userName) { return false; } }

    static class UserAdmin {
        boolean removeUser(String userName) {
            DBConnection dbConnection = new DBConnection();

            if (!dbConnection.isAdmin(userName)) {
                // remove user
                return true;
            }

            return false;
        }
    }

    @Tested UserAdmin userAdmin;
    @Mocked DBConnection dBConnection;

    @Test
    public void doesNotRemoveUserWhenAdmin() throws Exception {
        new Expectations() {{ dBConnection.isAdmin("admin"); result = true; }};

        boolean removedIt = userAdmin.removeUser("admin");

        assertFalse(removedIt);
    }
}

Works fine for me:

public class UserAdminTest {
    static class DBConnection { boolean isAdmin(String userName) { return false; } }

    static class UserAdmin {
        boolean removeUser(String userName) {
            DBConnection dbConnection = new DBConnection();

            if (!dbConnection.isAdmin(userName)) {
                // remove user
                return true;
            }

            return false;
        }
    }

    @Tested UserAdmin userAdmin;
    @Mocked DBConnection dBConnection;

    @Test
    public void doesNotRemoveUserWhenAdmin() throws Exception {
        new Expectations() {{ dBConnection.isAdmin("admin"); result = true; }};

        boolean removedIt = userAdmin.removeUser("admin");

        assertFalse(removedIt);
    }
}

相关问答

更多
  • 我认为你让这个过于复杂。 你根本不应该使用期望块。 你需要做的就是这样的事情: @Test public void testParsingForCommas() { StringToTransaction tested = new StringToTransaction(); List expected = new ArrayList(); // Add expected strings list here.. List actual ...
  • 适合我的工作: public class UserAdminTest { static class DBConnection { boolean isAdmin(String userName) { return false; } } static class UserAdmin { boolean removeUser(String userName) { DBConnection dbConnection = new DBConnection() ...
  • 你正在客户端传递一个client.HttpResponse("asd"), "100"而你的模拟方法需要一个HttpClient你需要模拟方法, @Mock String HttpResponse(String client) { return "100"; } 在你的MockUP或 您需要更改调用以使用HttpClient而不是String You are passing a String at line client.HttpResponse("asd"), "100" wh ...
  • 我一直遇到同样的问题 - 这似乎已经为我解决了这个问题,并希望能帮助其他人。 如果您通过ant运行此命令,请确保您的javac目标的debuglevel参数中没有变量。 以下目标将导致错误。 将其更改为:
  • 当你模拟ClassA , doSomeAStuff()的真正实现被doSomeAStuff()拦截,所以它不会调用doSomeBStuff() 。 在System上执行单元测试时,您只应该模拟ClassA 。 @RunWith(JMockit.class) public class SomeTest { @Tested private System1 system; @Injectable private ClassA memberA; @Test pub ...
  • 和JMockit这么多东西一样,这很容易做到。 尝试这个.. @Test public void testSystemCurrentTimeMillis(@Mocked final System unused) { new NonStrictExpectations() {{ System.currentTimeMillis(); result = 1438357206679L; }}; long currentTime = System.currentTimeMil ...
  • 我找到了一个解决方案:如果我使用Run As -> JUnit Test在Eclipse中执行Run As -> JUnit Test ,一切正常。 如果我使用Run As -> JUnit Plugin Test执行Run As -> JUnit Plugin Test ,则会发生同样的错误。 研究没有给出结果,JMockit的支持被取消 (“不会修复”)。 由于“正常”测试工作正常,我可以使用“normale”maven-surefire-plugin而不是tycho-surefire-plugin。 ...
  • 您需要javaOptions in Test javaOptions javaOptions in Test更改为javaOptions in Test (注意javaOptions in Test的T是大写的)。 您可以通过执行show test:javaOptions来检查您的选项 > show test:javaOptions [info] List(-javaagent:/home/lpiepiora/.ivy2/cache/com.googlecode.jmockit/jmockit/jars/j ...
  • 编写测试的一种方法是使用部分模拟和严格的期望: public class TestAClass { @Test public void test1() { final ClassToMock classToMockInstance = new ClassToMock(); new Expectations(ClassToMock.class) {{ classToMockInstance.methodToMock(); re ...
  • 测试使不必要的事情复杂化。 请尝试以下方法: @Test public void registerNewFoo_fooAddedToList() { Bar bar = new Bar(m_mockFooList); bar.registerNewFoo("test id"); new Verifications() {{ m_mockFooList.addNewFoo((Foo) withNotNull()); }}; } 注意:如果没有记录期望, m_mockFooList. ...

相关文章

更多

最新问答

更多
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)
  • 是否可以嵌套hazelcast IMaps?(Is it possible to nest hazelcast IMaps? And whick side effects can I expect? Is it a good Idea anyway?)
  • UIViewAnimationOptionRepeat在两个动画之间暂停(UIViewAnimationOptionRepeat pausing in between two animations)
  • 在x-kendo-template中使用Razor查询(Using Razor query within x-kendo-template)
  • 在BeautifulSoup中替换文本而不转义(Replace text without escaping in BeautifulSoup)
  • 如何在存根或模拟不存在的方法时配置Rspec以引发错误?(How can I configure Rspec to raise error when stubbing or mocking non-existing methods?)
  • asp用javascript(asp with javascript)
  • “%()s”在sql查询中的含义是什么?(What does “%()s” means in sql query?)
  • 如何为其编辑的内容提供自定义UITableViewCell上下文?(How to give a custom UITableViewCell context of what it is editing?)
  • c ++十进制到二进制,然后使用操作,然后回到十进制(c++ Decimal to binary, then use operation, then back to decimal)
  • 以编程方式创建视频?(Create videos programmatically?)
  • 无法在BeautifulSoup中正确解析数据(Unable to parse data correctly in BeautifulSoup)
  • webform和mvc的区别 知乎
  • 如何使用wadl2java生成REST服务模板,其中POST / PUT方法具有参数?(How do you generate REST service template with wadl2java where POST/PUT methods have parameters?)
  • 我无法理解我的travis构建有什么问题(I am having trouble understanding what is wrong with my travis build)
  • iOS9 Scope Bar出现在Search Bar后面或旁边(iOS9 Scope Bar appears either behind or beside Search Bar)
  • 为什么开机慢上面还显示;Inetrnet,Explorer
  • 有关调用远程WCF服务的超时问题(Timeout Question about Invoking a Remote WCF Service)