问:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeRepo':
I have used Spring with spring data, while it's giving below error.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeRepo': Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: org/springframework/core/DecoratingProxy
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
      at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
      at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
      at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
      at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
      at org.spring
  Caused by: java.lang.ClassNotFoundException: org.springframework.core.DecoratingProxy

Spring-Servlet.xml

```<code><beans:bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <beans:property name="prefix" value="/WEB-INF/views/"/>
    <beans:property name="suffix" value=".jsp"/>
</beans:bean>

<beans:bean
        id="employeeRepo" class="com.spring.crud.dao.EmployeeRepo" abstract="true"/>

<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
            destroy-method="close">
    <beans:property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <beans:property name="url"
                    value="jdbc:mysql://localhost:3306/crud?createDatabaseIfNotExist=true"/>
    <beans:property name="username" value="gppuser"/>
    <beans:property name="password" value="da123abc"/>
</beans:bean>

<beans:bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">

</beans:bean>

<beans:bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <beans:property name="dataSource" ref="dataSource"/>
    <beans:property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter"/>
    <beans:property name="packagesToScan" value="com.spring.crud.entity"/>
    <beans:property name="jpaProperties">
        <beans:props>
            <beans:prop key="hibernate.dialect">${hibernate.dialect}</beans:prop>
            <beans:prop key="hibernate.dialect">${hibernate.hbm2ddl.auto}</beans:prop>
            <beans:prop key="hibernate.dialect">${hibernate.ejb.naming_strategy}</beans:prop>
            <beans:prop key="hibernate.dialect">${hibernate.show_sql}</beans:prop>
            <beans:prop key="hibernate.dialect">${hibernate.format_sql}</beans:prop>

        </beans:props>

    </beans:property>
</beans:bean>

<beans:bean id="hibernateJpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>

<beans:bean id="hibernate4AnnotatedSessionFactory"
            class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <beans:property name="dataSource" ref="dataSource"/>
    <beans:property name="annotatedClasses">
        <beans:list>
            <beans:value>com.spring.crud.entity.Employee</beans:value>
        </beans:list>
    </beans:property>
    <beans:property name="hibernateProperties">
        <beans:props>
            <beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
            </beans:prop>
            <beans:prop key="hibernate.show_sql">true</beans:prop>
        </beans:props>
    </beans:property>
</beans:bean>

<context:component-scan base-package="com.spring.crud.*"/>

<jpa:repositories base-package="com.spring.crud" />

<!--<tx:annotation-driven transaction-manager="transactionManager"/>-->

<!--<beans:bean id="transactionManager"-->
            <!--class="org.springframework.orm.hibernate4.HibernateTransactionManager">-->
    <!--<beans:property name="sessionFactory"-->
                    <!--ref="hibernate4AnnotatedSessionFactory"/>-->
<!--</beans:bean>-->
</code>```

EmployeeService.java

```<code>@Service("employeeService")
public class EmployeeService {

    @Autowired
    private EmployeeRepo employeeRepo;

    @Transactional
    public List<Employee> getAllEmployee() {
        return (List<Employee>) employeeRepo.findAll();
    }
}
</code>```

EmployeeRepo

```<code>@Repository
public interface EmployeeRepo extends CrudRepository<Employee,Long>{

}
</code>```

Pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.spring.crud</groupId>
    <artifactId>springMvcAssignment</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.4.1</version>
        </dependency>
        <!-- Hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>

        <!-- Apache Commons DBCP -->
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>
        <!-- Spring ORM -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-jpa -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>1.11.1.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-releasetrain</artifactId>
            <version>Kay-M4</version>
            <scope>import</scope>
            <type>pom</type>
        </dependency>

        <!-- AspectJ -->
        <!--<dependency>-->
            <!--<groupId>org.aspectj</groupId>-->
            <!--<artifactId>aspectjrt</artifactId>-->
            <!--<version>${org.aspectj-version}</version>-->
        <!--</dependency>-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/jstl/jstl -->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>${jdk.version}</source>
                    <target>${jdk.version}</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
        </plugins>

    </build>
    <properties>
        <spring.version>4.2.1.RELEASE</spring.version>
        <security.version>4.0.3.RELEASE</security.version>
        <jdk.version>1.7</jdk.version>
        <hibernate.version>4.3.5.Final</hibernate.version>
        <org.aspectj-version>1.7.4</org.aspectj-version>
    </properties>
</project>
</code>```

mvn dependency:tree

```<code>[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building springMvcAssignment 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-dependency-plugin:2.1:tree (default-cli) @ springMvcAssignment ---
[INFO] com.spring.crud:springMvcAssignment:war:0.0.1-SNAPSHOT
[INFO] +- junit:junit:jar:3.8.1:test
[INFO] +- javax.servlet:javax.servlet-api:jar:3.1.0:compile
[INFO] +- org.springframework:spring-core:jar:4.2.1.RELEASE:compile
[INFO] |  \- commons-logging:commons-logging:jar:1.2:compile
[INFO] +- org.springframework:spring-webmvc:jar:4.2.1.RELEASE:compile
[INFO] |  +- org.springframework:spring-beans:jar:4.2.1.RELEASE:compile
[INFO] |  +- org.springframework:spring-context:jar:4.2.1.RELEASE:compile
[INFO] |  |  \- org.springframework:spring-aop:jar:4.3.7.RELEASE:compile
[INFO] |  |     \- aopalliance:aopalliance:jar:1.0:compile
[INFO] |  +- org.springframework:spring-expression:jar:4.2.1.RELEASE:compile
[INFO] |  \- org.springframework:spring-web:jar:4.2.1.RELEASE:compile
[INFO] +- com.fasterxml.jackson.core:jackson-databind:jar:2.4.1:compile
[INFO] |  +- com.fasterxml.jackson.core:jackson-annotations:jar:2.4.0:compile
[INFO] |  \- com.fasterxml.jackson.core:jackson-core:jar:2.4.1:compile
[INFO] +- org.hibernate:hibernate-core:jar:4.3.5.Final:compile
[INFO] |  +- org.jboss.logging:jboss-logging:jar:3.1.3.GA:compile
[INFO] |  +- org.jboss.logging:jboss-logging-annotations:jar:1.2.0.Beta1:compile
[INFO] |  +- org.jboss.spec.javax.transaction:jboss-transaction-api_1.2_spec:jar:1.0.0.Final:compile
[INFO] |  +- dom4j:dom4j:jar:1.6.1:compile
[INFO] |  |  \- xml-apis:xml-apis:jar:1.0.b2:compile
[INFO] |  +- org.hibernate.common:hibernate-commons-annotations:jar:4.0.4.Final:compile
[INFO] |  +- org.hibernate.javax.persistence:hibernate-jpa-2.1-api:jar:1.0.0.Final:compile
[INFO] |  +- org.javassist:javassist:jar:3.18.1-GA:compile
[INFO] |  +- antlr:antlr:jar:2.7.7:compile
[INFO] |  \- org.jboss:jandex:jar:1.1.0.Final:compile
[INFO] +- org.hibernate:hibernate-entitymanager:jar:4.3.5.Final:compile
[INFO] +- commons-dbcp:commons-dbcp:jar:1.4:compile
[INFO] |  \- commons-pool:commons-pool:jar:1.5.4:compile
[INFO] +- org.springframework:spring-orm:jar:4.2.1.RELEASE:compile
[INFO] |  +- org.springframework:spring-jdbc:jar:4.2.1.RELEASE:compile
[INFO] |  \- org.springframework:spring-tx:jar:4.2.1.RELEASE:compile
[INFO] +- org.springframework.data:spring-data-jpa:jar:1.11.1.RELEASE:provided
[INFO] |  +- org.springframework.data:spring-data-commons:jar:1.13.1.RELEASE:provided
[INFO] |  +- org.aspectj:aspectjrt:jar:1.8.10:provided
[INFO] |  +- org.slf4j:slf4j-api:jar:1.7.24:provided
[INFO] |  \- org.slf4j:jcl-over-slf4j:jar:1.7.24:provided
[INFO] +- org.springframework.data:spring-data-releasetrain:pom:Kay-M4:provided
[INFO] +- mysql:mysql-connector-java:jar:5.1.6:compile
[INFO] \- jstl:jstl:jar:1.2:compile
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.661s
[INFO] Finished at: Tue Nov 14 18:06:45 IST 2017
[INFO] Final Memory: 10M/244M
[INFO] --------------------------------------------------------------------
</code>```

答:
@Repository is for annotation configuration. You try to define bean in 2 ways, in xml and by annotation - that's a bad practice and can lead to further problems.

Try to remove next line from xml:
<beans:bean id="employeeRepo" class="com.spring.crud.dao.EmployeeRepo" abstract="true"/>

I suppose that you use @ComponentScan annotation.

Body:
I have used Spring with spring data, while it's giving below error.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeRepo': Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: org/springframework/core/DecoratingProxy
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
      at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
      at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
      at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
      at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
      at org.spring
  Caused by: java.lang.ClassNotFoundException: org.springframework.core.DecoratingProxy

Spring-Servlet.xml

<beans:bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <beans:property name="prefix" value="/WEB-INF/views/"/>
    <beans:property name="suffix" value=".jsp"/>
</beans:bean>

<beans:bean
        id="employeeRepo" class="com.spring.crud.dao.EmployeeRepo" abstract="true"/>

<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
            destroy-method="close">
    <beans:property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <beans:property name="url"
                    value="jdbc:mysql://localhost:3306/crud?createDatabaseIfNotExist=true"/>
    <beans:property name="username" value="gppuser"/>
    <beans:property name="password" value="da123abc"/>
</beans:bean>

<beans:bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">

</beans:bean>

<beans:bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <beans:property name="dataSource" ref="dataSource"/>
    <beans:property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter"/>
    <beans:property name="packagesToScan" value="com.spring.crud.entity"/>
    <beans:property name="jpaProperties">
        <beans:props>
            <beans:prop key="hibernate.dialect">${hibernate.dialect}</beans:prop>
            <beans:prop key="hibernate.dialect">${hibernate.hbm2ddl.auto}</beans:prop>
            <beans:prop key="hibernate.dialect">${hibernate.ejb.naming_strategy}</beans:prop>
            <beans:prop key="hibernate.dialect">${hibernate.show_sql}</beans:prop>
            <beans:prop key="hibernate.dialect">${hibernate.format_sql}</beans:prop>

        </beans:props>

    </beans:property>
</beans:bean>

<beans:bean id="hibernateJpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>

<beans:bean id="hibernate4AnnotatedSessionFactory"
            class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <beans:property name="dataSource" ref="dataSource"/>
    <beans:property name="annotatedClasses">
        <beans:list>
            <beans:value>com.spring.crud.entity.Employee</beans:value>
        </beans:list>
    </beans:property>
    <beans:property name="hibernateProperties">
        <beans:props>
            <beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
            </beans:prop>
            <beans:prop key="hibernate.show_sql">true</beans:prop>
        </beans:props>
    </beans:property>
</beans:bean>

<context:component-scan base-package="com.spring.crud.*"/>

<jpa:repositories base-package="com.spring.crud" />

EmployeeService.java

@Service("employeeService")
public class EmployeeService {

    @Autowired
    private EmployeeRepo employeeRepo;

    @Transactional
    public List<Employee> getAllEmployee() {
        return (List<Employee>) employeeRepo.findAll();
    }
}

EmployeeRepo

@Repository
public interface EmployeeRepo extends CrudRepository<Employee,Long>{

}

Pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.spring.crud</groupId>
    <artifactId>springMvcAssignment</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.4.1</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>

        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>1.11.1.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-releasetrain</artifactId>
            <version>Kay-M4</version>
            <scope>import</scope>
            <type>pom</type>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>

        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>${jdk.version}</source>
                    <target>${jdk.version}</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
        </plugins>

    </build>
    <properties>
        <spring.version>4.2.1.RELEASE</spring.version>
        <security.version>4.0.3.RELEASE</security.version>
        <jdk.version>1.7</jdk.version>
        <hibernate.version>4.3.5.Final</hibernate.version>
        <org.aspectj-version>1.7.4</org.aspectj-version>
    </properties>
</project>

mvn dependency:tree

[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building springMvcAssignment 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-dependency-plugin:2.1:tree (default-cli) @ springMvcAssignment ---
[INFO] com.spring.crud:springMvcAssignment:war:0.0.1-SNAPSHOT
[INFO] +- junit:junit:jar:3.8.1:test
[INFO] +- javax.servlet:javax.servlet-api:jar:3.1.0:compile
[INFO] +- org.springframework:spring-core:jar:4.2.1.RELEASE:compile
[INFO] |  \- commons-logging:commons-logging:jar:1.2:compile
[INFO] +- org.springframework:spring-webmvc:jar:4.2.1.RELEASE:compile
[INFO] |  +- org.springframework:spring-beans:jar:4.2.1.RELEASE:compile
[INFO] |  +- org.springframework:spring-context:jar:4.2.1.RELEASE:compile
[INFO] |  |  \- org.springframework:spring-aop:jar:4.3.7.RELEASE:compile
[INFO] |  |     \- aopalliance:aopalliance:jar:1.0:compile
[INFO] |  +- org.springframework:spring-expression:jar:4.2.1.RELEASE:compile
[INFO] |  \- org.springframework:spring-web:jar:4.2.1.RELEASE:compile
[INFO] +- com.fasterxml.jackson.core:jackson-databind:jar:2.4.1:compile
[INFO] |  +- com.fasterxml.jackson.core:jackson-annotations:jar:2.4.0:compile
[INFO] |  \- com.fasterxml.jackson.core:jackson-core:jar:2.4.1:compile
[INFO] +- org.hibernate:hibernate-core:jar:4.3.5.Final:compile
[INFO] |  +- org.jboss.logging:jboss-logging:jar:3.1.3.GA:compile
[INFO] |  +- org.jboss.logging:jboss-logging-annotations:jar:1.2.0.Beta1:compile
[INFO] |  +- org.jboss.spec.javax.transaction:jboss-transaction-api_1.2_spec:jar:1.0.0.Final:compile
[INFO] |  +- dom4j:dom4j:jar:1.6.1:compile
[INFO] |  |  \- xml-apis:xml-apis:jar:1.0.b2:compile
[INFO] |  +- org.hibernate.common:hibernate-commons-annotations:jar:4.0.4.Final:compile
[INFO] |  +- org.hibernate.javax.persistence:hibernate-jpa-2.1-api:jar:1.0.0.Final:compile
[INFO] |  +- org.javassist:javassist:jar:3.18.1-GA:compile
[INFO] |  +- antlr:antlr:jar:2.7.7:compile
[INFO] |  \- org.jboss:jandex:jar:1.1.0.Final:compile
[INFO] +- org.hibernate:hibernate-entitymanager:jar:4.3.5.Final:compile
[INFO] +- commons-dbcp:commons-dbcp:jar:1.4:compile
[INFO] |  \- commons-pool:commons-pool:jar:1.5.4:compile
[INFO] +- org.springframework:spring-orm:jar:4.2.1.RELEASE:compile
[INFO] |  +- org.springframework:spring-jdbc:jar:4.2.1.RELEASE:compile
[INFO] |  \- org.springframework:spring-tx:jar:4.2.1.RELEASE:compile
[INFO] +- org.springframework.data:spring-data-jpa:jar:1.11.1.RELEASE:provided
[INFO] |  +- org.springframework.data:spring-data-commons:jar:1.13.1.RELEASE:provided
[INFO] |  +- org.aspectj:aspectjrt:jar:1.8.10:provided
[INFO] |  +- org.slf4j:slf4j-api:jar:1.7.24:provided
[INFO] |  \- org.slf4j:jcl-over-slf4j:jar:1.7.24:provided
[INFO] +- org.springframework.data:spring-data-releasetrain:pom:Kay-M4:provided
[INFO] +- mysql:mysql-connector-java:jar:5.1.6:compile
[INFO] \- jstl:jstl:jar:1.2:compile
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.661s
[INFO] Finished at: Tue Nov 14 18:06:45 IST 2017
[INFO] Final Memory: 10M/244M
[INFO] --------------------------------------------------------------------


来源: stackexchange

问:
I forgot the password I entered during PostgreSQL installation
I either forgot or mistyped (during the installation) the password to the default user of PostgreSQL. I can't seem to be able to run it, and I get the following error:

psql: FATAL:  password authentication failed for user "hisham"
hisham-agil: hisham$ psql
```

Is there a way to reset the password or how do I create a new user with superuser privileges?

I am new to PostgreSQL and just installed it for the first time. I am trying to use it with Ruby on Rails and I am running Mac OS X v10.7 (Lion).

答:
I did this to resolve the same problem:

Open the pg_hba.conf file with the gedit editor from the terminal:

sudo gedit /etc/postgresql/9.5/main/pg_hba.conf
```
<p>It will ask for a password. Enter your admin login password.
This will open gedit with the file. Paste the following line:</p>
<pre class="lang-none prettyprint-override"><code>host  all   all  127.0.0.1/32  trust
just below -

# Database administrative login by Unix domain socket
</code>```

Save and close it.

Close the terminal, open it again and run this command:

psql -U postgres
```
<p>You will now enter the <em>psql</em> console.</p>
<p>Now change the password by entering this:</p>
<pre class="lang-none prettyprint-override"><code>ALTER USER [your preferred user name] with password '[desired password]';
</code>```

If it says the user does not exist then instead of ALTER, use CREATE.

Lastly, remove that certain line you pasted in pg_hba and save it.

ContentLicense: CC BY-SA 4.0

Body:
I either forgot or mistyped (during the installation) the password to the default user of PostgreSQL. I can't seem to be able to run it, and I get the following error:

psql: FATAL:  password authentication failed for user "hisham"
hisham-agil: hisham$ psql

Is there a way to reset the password or how do I create a new user with superuser privileges?

I am new to PostgreSQL and just installed it for the first time. I am trying to use it with Ruby on Rails and I am running Mac OS X v10.7 (Lion).

Body:
I did this to resolve the same problem:

Open the pg_hba.conf file with the gedit editor from the terminal:

sudo gedit /etc/postgresql/9.5/main/pg_hba.conf

It will ask for a password. Enter your admin login password.
This will open gedit with the file. Paste the following line:

host  all   all  127.0.0.1/32  trust
just below -

# Database administrative login by Unix domain socket

Save and close it.

Close the terminal, open it again and run this command:

psql -U postgres

You will now enter the psql console.

Now change the password by entering this:

ALTER USER [your preferred user name] with password '[desired password]';

If it says the user does not exist then instead of ALTER, use CREATE.

Lastly, remove that certain line you pasted in pg_hba and save it.


问:
Change highcharts data label position
This is my jsfiddle link http://jsfiddle.net/bb1m6xyk/1/

I want that all my labels like my data: 0 etc are positioned at the base and in center of each zone.

```<code>$('#container').highcharts({
    chart: {
      type: 'area'
    },
    yAxis: {
      title: {
        text: 'Percent'
      }
    },
    plotOptions: {
      area: {
        enableMouseTracking: false,
        showInLegend: false,
        stacking: 'percent',
        lineWidth: 0,
        marker: {
          enabled: false
        },
        dataLabels: {
            className:'highlight',
          enabled: true,
          formatter: function () {
            console.log(this);
            return this.point.myData
          }
        }
      }
    },
    series: [{
      name: 'over',
      color: 'none',
      data: overData
    }, {
      id: 's1',
      name: 'Series 1',
      data: data,
      showInLegend: true,
      zoneAxis: 'x',
      zones: zones
    }]
  });
</code>```

Is this possible? I tried it using className on dataLabels but it doesn't take that into effect.

Any help is appreciated.

答:
There are a few ways to render labels on a chart.

The Renderer

Live example: http://jsfiddle.net/11rj6k6p/

You can use Renderer.label to render the label on the chart - this is a low level approach but it gives you full control how the labels will be rendered. You can loop the zones and set x and y attributes of the labels, e.g. like this:

```<code>const labels = ['l1', 'l2', 'l3', 'l4', 'l5']

function drawLabels() {
  const zonesLabels = this.zonesLabels

  const series = this.get('s1')
  const { yAxis, xAxis } = series
  const y = yAxis.toPixels(0) - 20 // -20 is an additional offset in px

  series.zones.reduce((prev, curr, i) => {
    if (curr.value !== undefined) {
      const x = (xAxis.toPixels(prev.value) + xAxis.toPixels(curr.value)) / 2
      if (!zonesLabels[i]) {
        zonesLabels.push(
          this.renderer.label(labels[i], x, y).add().attr({
            align: 'center',
            zIndex: 10
          })
        )
      } else {
        zonesLabels[i].attr({ x, y })
      }
    }

   return curr
  }, { value: series.dataMin })
}
</code>```

Then set the function on load - to render the labels, and on redraw - to reposition the labels if the chart size changed.

```<code>chart: {
  type: 'area',
  events: {
    load: function() {
      this.zonesLabels = []

      drawLabels.call(this)
    },
    redraw: drawLabels
  }
},
</code>```

The annotations module

Live example: http://jsfiddle.net/a5gb7aqz/

If you do not want to use the Renderer API, you can use the annotations module which allows to declare labels in a chart config.

Add the module

```<code><script src="https://code.highcharts.com/modules/annotations.js"></script>
</code>```

Map zones to the labels config object

```<code>const labels = ['l1', 'l2', 'l3', 'l4', 'l5']

function annotationsLabels() {
  const zonesLabels = []

  zones.reduce((prev, curr, i) => {
    zonesLabels.push({
      text: labels[i],
      point: {
        x: (prev.value + curr.value) / 2,
        y: 0,
        xAxis: 0,
        yAxis: 0
      }
    })

   return curr
  }, { value: 0 })

  return zonesLabels
}
</code>```

Set the annotations options

```<code>annotations: [{
  labels: annotationsLabels(),
  labelOptions: {
    shape: 'rect',
    backgroundColor: 'none',
    borderColor: 'none',
    x: 0,
    y: 0
  }
}],
</code>```

Data labels and a new series

Live example: http://jsfiddle.net/wpk1495g/

You can create a new scatter series which will not respond to mouse events and it won't be visible in the legend. The labels can be displayed as data labels.

Map zones to series points

```<code>const labels = ['l1', 'l2', 'l3', 'l4', 'l5']

function seriesData() {
  const points = []

  zones.reduce((prev, curr, i) => {
    points.push( {
      x: (prev.value + curr.value) / 2,
      y: 50,
      dataLabels: {
        enabled: true,
        format: labels[i]
      }
    })

    return curr
  }, { value: 0 })

 return points
}
</code>```

Set the series options in the chart config

```<code>, {
  type: 'scatter',
  enableMouseTracking: false,
  showInLegend: false,
  data: seriesData(),
  zIndex: 10,
  color: 'none',
  dataLabels: { style: { textOutline: false }, x: 0, y: 0 }
}
</code>```

Output

ContentLicense: CC BY-SA 3.0

Title: Change highcharts data label position

Body:
This is my jsfiddle link http://jsfiddle.net/bb1m6xyk/1/

I want that all my labels like my data: 0 etc are positioned at the base and in center of each zone.

$('#container').highcharts({
    chart: {
      type: 'area'
    },
    yAxis: {
      title: {
        text: 'Percent'
      }
    },
    plotOptions: {
      area: {
        enableMouseTracking: false,
        showInLegend: false,
        stacking: 'percent',
        lineWidth: 0,
        marker: {
          enabled: false
        },
        dataLabels: {
            className:'highlight',
          enabled: true,
          formatter: function () {
            console.log(this);
            return this.point.myData
          }
        }
      }
    },
    series: [{
      name: 'over',
      color: 'none',
      data: overData
    }, {
      id: 's1',
      name: 'Series 1',
      data: data,
      showInLegend: true,
      zoneAxis: 'x',
      zones: zones
    }]
  });

Is this possible? I tried it using className on dataLabels but it doesn't take that into effect.

Any help is appreciated.

Body:
There are a few ways to render labels on a chart.

The Renderer

Live example: http://jsfiddle.net/11rj6k6p/

You can use Renderer.label to render the label on the chart - this is a low level approach but it gives you full control how the labels will be rendered. You can loop the zones and set x and y attributes of the labels, e.g. like this:

const labels = ['l1', 'l2', 'l3', 'l4', 'l5']

function drawLabels() {
  const zonesLabels = this.zonesLabels

  const series = this.get('s1')
  const { yAxis, xAxis } = series
  const y = yAxis.toPixels(0) - 20 // -20 is an additional offset in px

  series.zones.reduce((prev, curr, i) => {
    if (curr.value !== undefined) {
      const x = (xAxis.toPixels(prev.value) + xAxis.toPixels(curr.value)) / 2
      if (!zonesLabels[i]) {
        zonesLabels.push(
          this.renderer.label(labels[i], x, y).add().attr({
            align: 'center',
            zIndex: 10
          })
        )
      } else {
        zonesLabels[i].attr({ x, y })
      }
    }

   return curr
  }, { value: series.dataMin })
}

Then set the function on load - to render the labels, and on redraw - to reposition the labels if the chart size changed.

chart: {
  type: 'area',
  events: {
    load: function() {
      this.zonesLabels = []

      drawLabels.call(this)
    },
    redraw: drawLabels
  }
},

The annotations module

Live example: http://jsfiddle.net/a5gb7aqz/

If you do not want to use the Renderer API, you can use the annotations module which allows to declare labels in a chart config.

Add the module

<script src="https://code.highcharts.com/modules/annotations.js"></script>

Map zones to the labels config object

const labels = ['l1', 'l2', 'l3', 'l4', 'l5']

function annotationsLabels() {
  const zonesLabels = []

  zones.reduce((prev, curr, i) => {
    zonesLabels.push({
      text: labels[i],
      point: {
        x: (prev.value + curr.value) / 2,
        y: 0,
        xAxis: 0,
        yAxis: 0
      }
    })

   return curr
  }, { value: 0 })

  return zonesLabels
}

Set the annotations options

annotations: [{
  labels: annotationsLabels(),
  labelOptions: {
    shape: 'rect',
    backgroundColor: 'none',
    borderColor: 'none',
    x: 0,
    y: 0
  }
}],

Data labels and a new series

Live example: http://jsfiddle.net/wpk1495g/

You can create a new scatter series which will not respond to mouse events and it won't be visible in the legend. The labels can be displayed as data labels.

Map zones to series points

const labels = ['l1', 'l2', 'l3', 'l4', 'l5']

function seriesData() {
  const points = []

  zones.reduce((prev, curr, i) => {
    points.push( {
      x: (prev.value + curr.value) / 2,
      y: 50,
      dataLabels: {
        enabled: true,
        format: labels[i]
      }
    })

    return curr
  }, { value: 0 })

 return points
}

Set the series options in the chart config

, {
  type: 'scatter',
  enableMouseTracking: false,
  showInLegend: false,
  data: seriesData(),
  zIndex: 10,
  color: 'none',
  dataLabels: { style: { textOutline: false }, x: 0, y: 0 }
}

Output


问:
Add Overlay to Image in HTML EMail Compatible With Most Desktop and Web EMail Clients
Is there a way in 2017 to display either an image- or text-based overlay over the main image inside an HTML email, so that it is properly rendered by most of the current Desktop and Web email clients: Outlook 2007+, Thunderbird, Mobile Clients, GMail, Outlook.com, Yahoo Mail, etc.?

As an example, it could be a small play button rendering over the main image, that when clicked would take you to a video url.

答:
Using VML is still the only way to get background image support on Outlook environments.
So you'll want to use this tool
https://backgrounds.cm/

Drop your image url in, set it to 'single table sell' and set some dimensions, then you just build your overlay content between the
 tags

Body:
Using VML is still the only way to get background image support on Outlook environments.
So you'll want to use this tool
https://backgrounds.cm/

Drop your image url in, set it to 'single table sell' and set some dimensions, then you just build your overlay content between the <div> tags


问:
Find and return JSON differences using newtonsoft in C#?
I'd like to get a list of the JSON parts that don't match when doing a comparison using Newtonsoft.

I have this code that compares:

```<code>JObject xpctJSON = JObject.Parse(expectedJSON);
JObject actJSON = JObject.Parse(actualJSON);

bool res = JToken.DeepEquals(xpctJSON, actJSON);
</code>```

But can't find anything that returns the diff's.

答:
Just to help future queries. There's a nice json diff tool I came across. It works flawlessly for diff/patch of json structures:

jsondiffpatch.net
There's also a nuget package for it.

usage is straightforward.

```<code>var jdp = new JsonDiffPatch();
JToken diffResult = jdp.Diff(leftJson, rightJson);
</code>```

Body:
I'd like to get a list of the JSON parts that don't match when doing a comparison using Newtonsoft.

I have this code that compares:

JObject xpctJSON = JObject.Parse(expectedJSON);
JObject actJSON = JObject.Parse(actualJSON);

bool res = JToken.DeepEquals(xpctJSON, actJSON);

But can't find anything that returns the diff's.

Body:
Just to help future queries. There's a nice json diff tool I came across. It works flawlessly for diff/patch of json structures:

jsondiffpatch.net
There's also a nuget package for it.

usage is straightforward.

var jdp = new JsonDiffPatch();
JToken diffResult = jdp.Diff(leftJson, rightJson);


问:
Get innerhtml from external page with Javascript
I'm trying to get innerHTML of a DIV that is located on external page. It is possible to do this using this kind javascript code?</p>

```<code>    <script type="text/javascript">
        $(document).ready(function(){
            var html = document.getElementById("glr1").src='/my_page.html'.innerHTML ;
            alert(html);
        });
    </script>
</code>```

答:
You cannot get the html from an external html due to security issues.

You can get the html only from a frame located on the same domain.

ContentLicense: CC BY-SA 2.5


问:
xgboost multinomial classification error: "label and prediction size not match"
Forward that I'm fairly new to both xgboost and R.

I am using xgboost in R to perform a multinomial classification on my data dtrain. The label I am using has six levels, so my code looks like this:

```<code>param1 <- list(objective = "multi:softprob"
          , num_class = 6
          , booster = "gbtree"
          , eta = 0.5
          , max.depth = 7
          , min_child_weight = 10
          , max_delta_step = 5
          , subsample = 0.8
          , colsample_bytree = 0.8
          , lambda  = 3 # L2
          , alpha = 5 # L1
)
set.seed(2016)
xgbcv1 <- xgb.cv(params = param1, data = dtrain, nround = 3000, nfold = 3,
             metrics = list("error", "auc"), maximize = T,
             print_every_n = 10, early_stopping_rounds = 10)
</code>```

This throws me the following error:

```<code>Error in xgb.iter.update(fd$bst, fd$dtrain, iteration - 1, obj) :
amalgamation/../src/objective/multiclass_obj.cc:75: Check failed:
label_error >= 0 && label_error < nclass SoftmaxMultiClassObj: label must be in [0, num_class), num_class=6 but found 6 in label.
</code>```

So I tried setting num_class = 7, which throws this error:

```<code>Error in xgb.iter.eval(fd$bst, fd$watchlist, iteration - 1, feval) :
amalgamation/../src/metric/elementwise_metric.cc:28: Check failed:
(preds.size()) == (info.labels.size()) label and prediction size not match, hint: use merror or mlogloss for multi-class classification
</code>```

What's going on here? Does num_class need to be greater than label_error or equal to it?

答: if number of levels in the dependent variable is 6 then give num_class = 7. Meaning specify num_class = levels(Dependent Variable) + 1</p>

Body:
Forward that I'm fairly new to both xgboost and R.

I am using xgboost in R to perform a multinomial classification on my data dtrain. The label I am using has six levels, so my code looks like this:

param1 <- list(objective = "multi:softprob"
          , num_class = 6
          , booster = "gbtree"
          , eta = 0.5
          , max.depth = 7
          , min_child_weight = 10
          , max_delta_step = 5
          , subsample = 0.8
          , colsample_bytree = 0.8
          , lambda  = 3 # L2
          , alpha = 5 # L1
)
set.seed(2016)
xgbcv1 <- xgb.cv(params = param1, data = dtrain, nround = 3000, nfold = 3,
             metrics = list("error", "auc"), maximize = T,
             print_every_n = 10, early_stopping_rounds = 10)

This throws me the following error:

Error in xgb.iter.update(fd$bst, fd$dtrain, iteration - 1, obj) :
amalgamation/../src/objective/multiclass_obj.cc:75: Check failed:
label_error >= 0 && label_error < nclass SoftmaxMultiClassObj: label must be in [0, num_class), num_class=6 but found 6 in label.

So I tried setting num_class = 7, which throws this error:

Error in xgb.iter.eval(fd$bst, fd$watchlist, iteration - 1, feval) :
amalgamation/../src/metric/elementwise_metric.cc:28: Check failed:
(preds.size()) == (info.labels.size()) label and prediction size not match, hint: use merror or mlogloss for multi-class classification

What's going on here? Does num_class need to be greater than label_error or equal to it?


问:
How does Flexible Search query translate to SQL query in Hybris?
As far as I know, Hybris uses FlexibleSearchQuery to query data. So to query the database, I need to translate FlexibleSearchQuery into SQL. I still do not know how Hybris does it.Can you help me understand?

I have stack trace code as follows:

I see: TranslatedQuery tQuery(class: FlexibleSearch method: executeSearch) = this.cacheKey.tq (class: FlexibleSearchCacheUnit method: compute).

So, Where does this.cacheKey.tq value come from?

```PreparedStatementImpl   executeQuery

public ResultSet executeQuery() throws SQLException {
        if (this.isLoggingActivated()) {
            long startTime = System.currentTimeMillis();

            ResultSet var5;
            try {
                var5 = this.wrapResultSet(this.prepStmtPassthru.executeQuery());
            } catch (SQLException var9) {
                this.getConnection().notifyError(var9);
                this.getConnection().logError(var9, "error executing query");
                throw var9;
            } finally {
                this.connection.getDataSource().getLogUtils().logElapsed(Thread.currentThread().getId(), this.connection.getConnectionID(), startTime, "statement", this.preparedQueryWithoutStackTrace, this.assembleQueryFromPreparedStatement());
            }

            return var5;
        } else {
            try {
                return this.wrapResultSet(this.prepStmtPassthru.executeQuery());
            } catch (SQLException var11) {
                this.getConnection().notifyError(var11);
                this.getConnection().logError(var11, "error executing query");
                throw var11;
            }
        }
    }

FlexibleSearchExecutor  execute

public SearchResult execute(int start, int count, boolean dontNeedTotal, TranslatedQuery translatedQuery, List<Class<?>> resultClasses, Map values, PK languagePK, int prefetchSize, Set<PK> prefetchLanguages) {
        ConversionMetaInformation conversionResult = this.convertResultClasses(resultClasses);
        ExecutableQuery executableQuery = this.getExecutableQuery(translatedQuery, values, languagePK);
        JDBCValueMappings jdbcVM = JDBCValueMappings.getInstance();
        LimitStatementBuilder limitBuilder = this.limitStatementFactory.getLimitStatementBuilder(executableQuery, start, count);
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        String query = null;

        SearchResult result;
        try {
            String errorMessageSecondPart;
            try {
                connection = this.tenant.getDataSource().getConnection();
                if (this.isNeedTotalAndCountIsZero(count, dontNeedTotal)) {
                    int totalCount = jdbcVM.getTotalCountFromCountQuery(connection, executableQuery.getCountSQL(), executableQuery.getCountValueList());
                    result = SQLSearchResultFactory.createCountOnlyResult(totalCount, start, count, executableQuery.getSQL(), executableQuery.getValueList());
                } else {
                    query = limitBuilder.getModifiedStatement();
                    statement = connection.prepareStatement(query);
                    jdbcVM.fillStatement(statement, limitBuilder.getModifiedStatementValues());
                    long t1 = 0L;
                    long t2 = 0L;
                    long t3 = 0L;
                    long t4 = 0L;
                    if (LOG.isDebugEnabled()) {
                        t1 = System.currentTimeMillis();
                    }

                    resultSet = statement.executeQuery();
                    if (LOG.isDebugEnabled()) {
                        t2 = System.currentTimeMillis();
                    }

                    int _start = limitBuilder.getOriginalStart();
                    int _count = limitBuilder.getOriginalCount();
                    if (limitBuilder.hasDbEngineLimitSupport()) {
                        _start = 0;
                        _count = -1;
                    }

                    if (LOG.isDebugEnabled()) {
                        t3 = System.currentTimeMillis();
                    }

                    RowFetchResult rowFetchResult = jdbcVM.getQueryResults(resultSet, conversionResult.getConvertedClasses(), _start, _count);
                    if (LOG.isDebugEnabled()) {
                        t4 = System.currentTimeMillis();
                    }

                    int totalCount = dontNeedTotal ? rowFetchResult.rows.size() : jdbcVM.getTotalCount(resultSet, rowFetchResult, start, count, connection, executableQuery, limitBuilder.hasDbEngineLimitSupport());
                    if (LOG.isDebugEnabled()) {
                        LOG.debug(this.getInfoForLogging(executableQuery.getSQL(), limitBuilder.getModifiedStatement(), conversionResult.getConvertedClasses(), executableQuery.getValueList(), ", original range=[" + limitBuilder.getOriginalStart() + "," + limitBuilder.getOriginalCount() + "], rowcount=" + totalCount + ", query=" + (t2 - t1) / 1000L + "ms, fetch=" + (t4 - t3) / 1000L + "ms"));
                    }

                    result = SQLSearchResultFactory.createCacheable(new CacheableResultHolder(rowFetchResult, prefetchSize, prefetchLanguages, conversionResult), totalCount, start, count, limitBuilder.getModifiedStatement(), executableQuery.getValueList());
                }
            } catch (IllegalArgumentException var35) {
                errorMessageSecondPart = Config.getBoolean("flexible.search.exception.show.query.details", false) ? var35.getMessage() + " query = '" + executableQuery.getSQL() + "', values = " + executableQuery.getValueList() : "enable the property 'flexible.search.exception.show.query.details' for more details";
                throw new FlexibleSearchException(var35, "wrong flexible search parameter - " + errorMessageSecondPart, 0);
            } catch (SQLException var36) {
                errorMessageSecondPart = Config.getBoolean("flexible.search.exception.show.query.details", false) ? var36.getMessage() + " query = '" + query + "', values = " + executableQuery.getValueList() : "enable the property 'flexible.search.exception.show.query.details' for more details";
                throw new FlexibleSearchException(var36, "SQL search error - " + errorMessageSecondPart, 0);
            }
        } finally {
            Utilities.tryToCloseJDBC(connection, statement, resultSet);
        }

        return result;
    }

FlexibleSearch  executeSearch

protected SearchResult executeSearch(TranslatedQuery tQuery, Map values, PK langPK, List<Class<?>> resultClasses, boolean dontNeedTotal, int start, int count, int prefetchSize, Set<PK> prefetchLanguages, boolean doExecuteQuery) throws FlexibleSearchException {
        return doExecuteQuery ? this.fsExecutor.execute(start, count, dontNeedTotal, tQuery, resultClasses, values, langPK, prefetchSize, prefetchLanguages) : this.fsExecutor.simulate(start, count, tQuery, values, langPK);
    }

FlexibleSearchCacheUnit compute

public final Object compute() throws FlexibleSearchException {
        this.usedCachedResult = false;
        StandardSearchResult ret = (StandardSearchResult)this.fs.executeSearch(this.cacheKey.tq, this.values, this.cacheKey.langPK, Arrays.asList(this.cacheKey.resultClasses), this.cacheKey.hasModifier(1), this.cacheKey.start, this.cacheKey.count, this.prefetchSize, this.prefetchLanguages, this.cacheKey.hasModifier(2));
        ret.setUnitHash(System.identityHashCode(this));
        return ret;
    }

AbstractCacheUnit   privateGetNoLock

private final Object privateGetNoLock() throws Exception {
        Object ret = this.value;
        if (this.isValueUnknown(ret)) {
            ret = this.compute();
            this.value = ret;
        }

        return ret;
    }

AbstractCacheUnit   privateGet

private final Object privateGet() throws Exception {
        return this.getTransactionAwareCache().isForceExclusiveComputation(this) ? this.privateGetSynchronized() : this.privateGetNoLock();
    }

AbstractCacheUnit   get

public final Object get() throws Exception {
        if (!this.useCache()) {
            return this.computeUncached();
        } else {
            TransactionAwareCache transactionAwareCache = this.getTransactionAwareCache();
            boolean success = false;
            AbstractCacheUnit valueUnit = transactionAwareCache.getOrAddUnit(this);
            Object ret = valueUnit.value;

            try {
                ret = this.isValueUnknown(ret) ? valueUnit.privateGet() : ret;
                success = true;
            } catch (CacheValueLoadException var9) {
                if (var9.getCause() instanceof Exception) {
                    throw (Exception)var9.getCause();
                }

                throw var9;
            } finally {
                if (!success) {
                    transactionAwareCache.removeUnit(valueUnit);
                }

            }

            return ret;
        }
    }

FlexibleSearchCacheUnit myGet

public final StandardSearchResult myGet() throws Exception {
        StandardSearchResult ret = (StandardSearchResult)this.get();
        ret.setFromCache(this.usedCachedResult);
        return ret;
    }

FlexibleSearch  search

public SearchResult search(SessionContext _ctx, String query, Map values, List resultClasses, boolean failOnUnknownFields, boolean dontNeedTotal, int start, int count) throws FlexibleSearchException {
        TranslatedQuery tQuery = null;
        int prefetchSize = this.getSearchPrefetchSize(_ctx);
        if (LOG.isDebugEnabled()) {
            LOG.debug(this.getSearchDebug(_ctx, query, resultClasses, failOnUnknownFields, dontNeedTotal, start, count, prefetchSize));
        }

        boolean doExecuteQuery = !this.disableExecution(_ctx);
        SessionContext localCtx = null;

        SearchResult var22;
        try {
            if (_ctx != null) {
                localCtx = JaloSession.getCurrentSession(this.getTenant()).createLocalSessionContext(_ctx);
                localCtx.setAttribute("disableExecution", Boolean.FALSE);
            }

            PK langPK = this.getSearchLangPK(localCtx);
            tQuery = this.translate(localCtx, this.getRestrictionPrincipal(localCtx), query, values != null ? values.size() : 0, langPK != null, failOnUnknownFields, this.disableRestrictions(localCtx), this.disablePrincipalGroupRestrictions(localCtx), values);
            Map _values = tQuery.removeUnusedValues(this.translatePathValueKeys(localCtx, tQuery.getValueKeys(), new CaseInsensitiveParameterMap(values != null ? values : Collections.EMPTY_MAP)));
            Set<PK> queryTCs = tQuery.getTypePKs();
            Set<Integer> beanTCs = new HashSet(queryTCs.size() * 4);
            PersistenceManager pm = this.getTenant().getPersistenceManager();
            Iterator var19 = queryTCs.iterator();

            while(var19.hasNext()) {
                PK typePK = (PK)var19.next();
                beanTCs.addAll(pm.getBeanTypeCodes(typePK));
            }

            if (beanTCs.isEmpty()) {
                throw new JaloInvalidParameterException("empty bean typcode list ( typePKs = " + tQuery.getTypePKs() + ", query = " + tQuery.getSQLTemplate() + " )", 0);
            }

            try {
                if (!this.isCachingDisabled(localCtx)) {
                    int ttl = this.getTTL(localCtx);
                    FlexibleSearch.FlexibleSearchCacheKey cacheKey = this.createCacheKey(resultClasses, dontNeedTotal, start, count, tQuery, doExecuteQuery, langPK, _values, beanTCs, ttl);
                    FlexibleSearchCacheUnit cacheUnit = this.createCacheUnit(prefetchSize, WrapperFactory.getPrefetchLanguages(localCtx), _values, cacheKey);
                    var22 = this.wrapSearchResult(cacheUnit.myGet());
                    return var22;
                }

                var22 = this.wrapSearchResult(this.executeSearch(tQuery, _values, langPK, resultClasses, dontNeedTotal, start, count, prefetchSize, WrapperFactory.getPrefetchLanguages(localCtx), doExecuteQuery));
            } catch (FlexibleSearchException var28) {
                throw var28;
            } catch (Exception var29) {
                throw new FlexibleSearchException(var29, var29.getMessage(), 0);
            }
        } catch (FlexibleSearchException var30) {
            LOG.error("Flexible search error occured...");
            if (tQuery == null) {
                LOG.error("Query translation was not successful.");
            }

            throw var30;
        } catch (JaloItemNotFoundException var31) {
            throw new JaloInternalException(var31, "cannot get type by translated query type pk", 0);
        } finally {
            if (localCtx != null) {
                JaloSession.getCurrentSession(this.getTenant()).removeLocalSessionContext();
            }

        }

        return var22;
    }

FlexibleSearch  search

public SearchResult search(String query, Map values, List resultClasses, boolean failOnUnknownFields, boolean dontNeedTotal, int start, int count) throws FlexibleSearchException {
        return this.search(JaloSession.hasCurrentSession() ? this.getSession().getSessionContext() : null, query, values, resultClasses, failOnUnknownFields, dontNeedTotal, start, count);
    }

DefaultFlexibleSearchService$2  execute

    private <T> de.hybris.platform.jalo.SearchResult<T> getJaloResult(final FlexibleSearchQuery query) {
        return (de.hybris.platform.jalo.SearchResult)this.getSessionService().executeInLocalView(new SessionExecutionBody() {
            public de.hybris.platform.jalo.SearchResult<T> execute() {
                DefaultFlexibleSearchService.this.getQueryPreprocessorRegistry().executeAllPreprocessors(query);
                Map queryParams = (Map)DefaultFlexibleSearchService.this.toPersistenceLayer(query.getQueryParameters());

                try {
                    return FlexibleSearch.getInstance().search(query.getQuery(), queryParams, this.convertModelClassList(query), query.isFailOnUnknownFields(), !query.isNeedTotal(), query.getStart(), query.getCount());
                } catch (FlexibleSearchException var3) {
                    throw new de.hybris.platform.servicelayer.search.exceptions.FlexibleSearchException(var3.getMessage(), var3);
                }
            }

            private List<Class> convertModelClassList(FlexibleSearchQuery queryx) {
                List<Class> resultClassList = new ArrayList(queryx.getResultClassList().size());
                Iterator var4 = queryx.getResultClassList().iterator();

                while(var4.hasNext()) {
                    Class modelClass = (Class)var4.next();
                    resultClassList.add(DefaultFlexibleSearchService.this.getModelService().getModelTypeClass(modelClass));
                }

                return resultClassList;
            }
        });
    }

DefaultFlexibleSearchService$2  execute

DefaultSessionService   executeInLocalView

public Object executeInLocalView(SessionExecutionBody body) {
        Object var3;
        try {
            this.getOrCreateCurrentJaloSession().createLocalSessionContext();
            var3 = body.execute();
        } finally {
            this.getOrCreateCurrentJaloSession().removeLocalSessionContext();
        }

        return var3;
    }

DefaultFlexibleSearchService    getJaloResult

private <T> de.hybris.platform.jalo.SearchResult<T> getJaloResult(final FlexibleSearchQuery query) {
        return (de.hybris.platform.jalo.SearchResult)this.getSessionService().executeInLocalView(new SessionExecutionBody() {
            public de.hybris.platform.jalo.SearchResult<T> execute() {
                DefaultFlexibleSearchService.this.getQueryPreprocessorRegistry().executeAllPreprocessors(query);
                Map queryParams = (Map)DefaultFlexibleSearchService.this.toPersistenceLayer(query.getQueryParameters());

                try {
                    return FlexibleSearch.getInstance().search(query.getQuery(), queryParams, this.convertModelClassList(query), query.isFailOnUnknownFields(), !query.isNeedTotal(), query.getStart(), query.getCount());
                } catch (FlexibleSearchException var3) {
                    throw new de.hybris.platform.servicelayer.search.exceptions.FlexibleSearchException(var3.getMessage(), var3);
                }
            }

            private List<Class> convertModelClassList(FlexibleSearchQuery queryx) {
                List<Class> resultClassList = new ArrayList(queryx.getResultClassList().size());
                Iterator var4 = queryx.getResultClassList().iterator();

                while(var4.hasNext()) {
                    Class modelClass = (Class)var4.next();
                    resultClassList.add(DefaultFlexibleSearchService.this.getModelService().getModelTypeClass(modelClass));
                }

                return resultClassList;
            }
        });
    }

DefaultFlexibleSearchService    search

public <T> SearchResult<T> search(FlexibleSearchQuery query) {
        ServicesUtil.validateParameterNotNull(query, "The 'query' is null!");
        de.hybris.platform.jalo.SearchResult<T> jaloResult = this.getJaloResult(query);
        if (jaloResult.getCount() == 0) {
            return this.createEmptyResult(jaloResult);
        } else {
            return jaloResult instanceof StandardSearchResult ? this.wrapOrConvert(query, (StandardSearchResult)jaloResult, () -> {
                return this.convert(jaloResult);
            }) : this.convert(jaloResult);
        }
    }

DefaultPagedFlexibleSearchService   search

public <T> SearchPageData<T> search(final String query, final Map<String, ?> queryParams, final PageableData pageableData)
    {
        validateParameterNotNull(query, "query cannot be null");
        validateParameterNotNull(pageableData, "pageableData cannot be null");
        Assert.isTrue(pageableData.getCurrentPage() >= 0, "pageableData current page must be zero or greater");
        Assert.isTrue(pageableData.getPageSize() > 0, "pageableData page size must be greater than zero");

        final FlexibleSearchQuery searchQuery = new FlexibleSearchQuery(query);
        if (queryParams != null && !queryParams.isEmpty())
        {
            searchQuery.addQueryParameters(queryParams);
        }

        searchQuery.setNeedTotal(true);
        searchQuery.setStart(pageableData.getCurrentPage() * pageableData.getPageSize());
        searchQuery.setCount(pageableData.getPageSize());

        final SearchResult<T> searchResult = getFlexibleSearchService().search(searchQuery);

        // Create the paged search result
        final SearchPageData<T> result = createSearchPageData();
        result.setResults(searchResult.getResult());
        result.setPagination(createPagination(pageableData, searchResult));
        // Note: does not set sorts

        return result;
    }

DefaultPagedFlexibleSearchService   search

public <T> SearchPageData<T> search(final List<SortQueryData> sortQueries, final String defaultSortCode,
            final Map<String, ?> queryParams, final PageableData pageableData)
    {
        validateParameterNotNull(sortQueries, "sortQueries cannot be null");
        validateParameterNotNull(defaultSortCode, "defaultSortCode cannot be null");
        validateParameterNotNull(pageableData, "pageableData cannot be null");
        Assert.isTrue(!sortQueries.isEmpty(), "sortQueries must not be empty");
        Assert.isTrue(pageableData.getCurrentPage() >= 0, "pageableData current page must be zero or greater");
        Assert.isTrue(pageableData.getPageSize() > 0, "pageableData page size must be greater than zero");

        // Work out which sort and query to use
        final SortQueryData selectedSortQuery = findSortQueryData(sortQueries, pageableData.getSort(), defaultSortCode);

        // Execute the query
        final SearchPageData<T> searchPageData = search(selectedSortQuery.getQuery(), queryParams, pageableData);

        // Specify which sort was used
        searchPageData.getPagination().setSort(selectedSortQuery.getSortCode());
        searchPageData.setSorts(createSorts(sortQueries, selectedSortQuery.getSortCode()));
        return searchPageData;
    }

DefaultCustomerAccountDao   findOrdersByCustomerAndStore

public SearchPageData<OrderModel> findOrdersByCustomerAndStore(final CustomerModel customerModel, final BaseStoreModel store,
            final OrderStatus[] status, final PageableData pageableData)
    {
        validateParameterNotNull(customerModel, "Customer must not be null");
        validateParameterNotNull(store, "Store must not be null");

        final Map<String, Object> queryParams = new HashMap<String, Object>();
        queryParams.put("customer", customerModel);
        queryParams.put("store", store);

        String filterClause = StringUtils.EMPTY;
        if (CollectionUtils.isNotEmpty(getFilterOrderStatusList()))
        {
            queryParams.put("filterStatusList", getFilterOrderStatusList());
            filterClause = FILTER_ORDER_STATUS;
        }

        final List<SortQueryData> sortQueries;

        if (ArrayUtils.isNotEmpty(status))
        {
            queryParams.put("statusList", Arrays.asList(status));
            sortQueries = Arrays.asList(
                    createSortQueryData("byDate",
                            createQuery(FIND_ORDERS_BY_CUSTOMER_STORE_QUERY_AND_STATUS, filterClause, SORT_ORDERS_BY_DATE)),
                    createSortQueryData("byOrderNumber",
                            createQuery(FIND_ORDERS_BY_CUSTOMER_STORE_QUERY_AND_STATUS, filterClause, SORT_ORDERS_BY_CODE)));
        }
        else
        {
            sortQueries = Arrays
                    .asList(
                            createSortQueryData("byDate",
                                    createQuery(FIND_ORDERS_BY_CUSTOMER_STORE_QUERY, filterClause, SORT_ORDERS_BY_DATE)),
                            createSortQueryData("byOrderNumber",
                                    createQuery(FIND_ORDERS_BY_CUSTOMER_STORE_QUERY, filterClause, SORT_ORDERS_BY_CODE)));
        }
        }

        return getPagedFlexibleSearchService().search(sortQueries, "byDate", queryParams, pageableData);
    }

DefaultCustomerAccountService   getOrderList

public SearchPageData<OrderModel> getOrderList(final CustomerModel customerModel, final BaseStoreModel store,
            final OrderStatus[] status, final PageableData pageableData)
    {
        validateParameterNotNull(customerModel, "Customer model cannot be null");
        validateParameterNotNull(store, "Store must not be null");
        validateParameterNotNull(pageableData, "PageableData must not be null");
        return getCustomerAccountDao().findOrdersByCustomerAndStore(customerModel, store, status, pageableData);
    }

DefaultOrderFacade  getPagedOrderHistoryForStatuses

public SearchPageData<OrderHistoryData> getPagedOrderHistoryForStatuses(final PageableData pageableData,
            final OrderStatus... statuses)
    {
        final CustomerModel currentCustomer = (CustomerModel) getUserService().getCurrentUser();
        final BaseStoreModel currentBaseStore = getBaseStoreService().getCurrentBaseStore();
        final SearchPageData<OrderModel> orderResults = getCustomerAccountService().getOrderList(currentCustomer, currentBaseStore,
                statuses, pageableData);

        return convertPageData(orderResults, getOrderHistoryConverter());
    }

AccountPageController   orders
public String orders(@RequestParam(value = "page", defaultValue = "0") final int page,
            @RequestParam(value = "show", defaultValue = "Page") final ShowMode showMode,
            @RequestParam(value = "sort", required = false) final String sortCode, final Model model) throws CMSItemNotFoundException
    {
        // Handle paged search results
        final PageableData pageableData = createPageableData(page, 5, sortCode, showMode);
        final SearchPageData<OrderHistoryData> searchPageData = vinOrderFacade.getPagedOrderHistoryForStatuses(pageableData);
        populateModel(model, searchPageData, showMode);

        storeCmsPageInModel(model, getContentPageForLabelOrId(ORDER_HISTORY_CMS_PAGE));
        setUpMetaDataForContentPage(model, getContentPageForLabelOrId(ORDER_HISTORY_CMS_PAGE));
        model.addAttribute(BREADCRUMBS_ATTR, accountBreadcrumbBuilder.getBreadcrumbs("text.account.orderHistory"));
        model.addAttribute(ThirdPartyConstants.SeoRobots.META_ROBOTS, ThirdPartyConstants.SeoRobots.NOINDEX_NOFOLLOW);
        model.addAttribute("isASM", assistedServiceFacade.isAssistedServiceAgentLoggedIn());
        return getViewForPage(model);
    }
```

答:
If you want to test your flex search queries, see the SQL output and the result, you can do this from HAC -> Console -> Flexible Search. The interface is quite simple and useful. </p>

<p>If you want to get all the sql queries, you can go again to HAC -> Monitoring -> Database -> JDBC Logging. </p>

Body:
As far as I know, Hybris uses FlexibleSearchQuery to query data. So to query the database, I need to translate FlexibleSearchQuery into SQL. I still do not know how Hybris does it.Can you help me understand?

I have stack trace code as follows:

I see: TranslatedQuery tQuery(class: FlexibleSearch method: executeSearch) = this.cacheKey.tq (class: FlexibleSearchCacheUnit method: compute).

So, Where does this.cacheKey.tq value come from?

PreparedStatementImpl   executeQuery

public ResultSet executeQuery() throws SQLException {
        if (this.isLoggingActivated()) {
            long startTime = System.currentTimeMillis();

            ResultSet var5;
            try {
                var5 = this.wrapResultSet(this.prepStmtPassthru.executeQuery());
            } catch (SQLException var9) {
                this.getConnection().notifyError(var9);
                this.getConnection().logError(var9, "error executing query");
                throw var9;
            } finally {
                this.connection.getDataSource().getLogUtils().logElapsed(Thread.currentThread().getId(), this.connection.getConnectionID(), startTime, "statement", this.preparedQueryWithoutStackTrace, this.assembleQueryFromPreparedStatement());
            }

            return var5;
        } else {
            try {
                return this.wrapResultSet(this.prepStmtPassthru.executeQuery());
            } catch (SQLException var11) {
                this.getConnection().notifyError(var11);
                this.getConnection().logError(var11, "error executing query");
                throw var11;
            }
        }
    }

FlexibleSearchExecutor  execute

public SearchResult execute(int start, int count, boolean dontNeedTotal, TranslatedQuery translatedQuery, List<Class<?>> resultClasses, Map values, PK languagePK, int prefetchSize, Set<PK> prefetchLanguages) {
        ConversionMetaInformation conversionResult = this.convertResultClasses(resultClasses);
        ExecutableQuery executableQuery = this.getExecutableQuery(translatedQuery, values, languagePK);
        JDBCValueMappings jdbcVM = JDBCValueMappings.getInstance();
        LimitStatementBuilder limitBuilder = this.limitStatementFactory.getLimitStatementBuilder(executableQuery, start, count);
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        String query = null;

        SearchResult result;
        try {
            String errorMessageSecondPart;
            try {
                connection = this.tenant.getDataSource().getConnection();
                if (this.isNeedTotalAndCountIsZero(count, dontNeedTotal)) {
                    int totalCount = jdbcVM.getTotalCountFromCountQuery(connection, executableQuery.getCountSQL(), executableQuery.getCountValueList());
                    result = SQLSearchResultFactory.createCountOnlyResult(totalCount, start, count, executableQuery.getSQL(), executableQuery.getValueList());
                } else {
                    query = limitBuilder.getModifiedStatement();
                    statement = connection.prepareStatement(query);
                    jdbcVM.fillStatement(statement, limitBuilder.getModifiedStatementValues());
                    long t1 = 0L;
                    long t2 = 0L;
                    long t3 = 0L;
                    long t4 = 0L;
                    if (LOG.isDebugEnabled()) {
                        t1 = System.currentTimeMillis();
                    }

                    resultSet = statement.executeQuery();
                    if (LOG.isDebugEnabled()) {
                        t2 = System.currentTimeMillis();
                    }

                    int _start = limitBuilder.getOriginalStart();
                    int _count = limitBuilder.getOriginalCount();
                    if (limitBuilder.hasDbEngineLimitSupport()) {
                        _start = 0;
                        _count = -1;
                    }

                    if (LOG.isDebugEnabled()) {
                        t3 = System.currentTimeMillis();
                    }

                    RowFetchResult rowFetchResult = jdbcVM.getQueryResults(resultSet, conversionResult.getConvertedClasses(), _start, _count);
                    if (LOG.isDebugEnabled()) {
                        t4 = System.currentTimeMillis();
                    }

                    int totalCount = dontNeedTotal ? rowFetchResult.rows.size() : jdbcVM.getTotalCount(resultSet, rowFetchResult, start, count, connection, executableQuery, limitBuilder.hasDbEngineLimitSupport());
                    if (LOG.isDebugEnabled()) {
                        LOG.debug(this.getInfoForLogging(executableQuery.getSQL(), limitBuilder.getModifiedStatement(), conversionResult.getConvertedClasses(), executableQuery.getValueList(), ", original range=[" + limitBuilder.getOriginalStart() + "," + limitBuilder.getOriginalCount() + "], rowcount=" + totalCount + ", query=" + (t2 - t1) / 1000L + "ms, fetch=" + (t4 - t3) / 1000L + "ms"));
                    }

                    result = SQLSearchResultFactory.createCacheable(new CacheableResultHolder(rowFetchResult, prefetchSize, prefetchLanguages, conversionResult), totalCount, start, count, limitBuilder.getModifiedStatement(), executableQuery.getValueList());
                }
            } catch (IllegalArgumentException var35) {
                errorMessageSecondPart = Config.getBoolean("flexible.search.exception.show.query.details", false) ? var35.getMessage() + " query = '" + executableQuery.getSQL() + "', values = " + executableQuery.getValueList() : "enable the property 'flexible.search.exception.show.query.details' for more details";
                throw new FlexibleSearchException(var35, "wrong flexible search parameter - " + errorMessageSecondPart, 0);
            } catch (SQLException var36) {
                errorMessageSecondPart = Config.getBoolean("flexible.search.exception.show.query.details", false) ? var36.getMessage() + " query = '" + query + "', values = " + executableQuery.getValueList() : "enable the property 'flexible.search.exception.show.query.details' for more details";
                throw new FlexibleSearchException(var36, "SQL search error - " + errorMessageSecondPart, 0);
            }
        } finally {
            Utilities.tryToCloseJDBC(connection, statement, resultSet);
        }

        return result;
    }

FlexibleSearch  executeSearch

protected SearchResult executeSearch(TranslatedQuery tQuery, Map values, PK langPK, List<Class<?>> resultClasses, boolean dontNeedTotal, int start, int count, int prefetchSize, Set<PK> prefetchLanguages, boolean doExecuteQuery) throws FlexibleSearchException {
        return doExecuteQuery ? this.fsExecutor.execute(start, count, dontNeedTotal, tQuery, resultClasses, values, langPK, prefetchSize, prefetchLanguages) : this.fsExecutor.simulate(start, count, tQuery, values, langPK);
    }

FlexibleSearchCacheUnit compute

public final Object compute() throws FlexibleSearchException {
        this.usedCachedResult = false;
        StandardSearchResult ret = (StandardSearchResult)this.fs.executeSearch(this.cacheKey.tq, this.values, this.cacheKey.langPK, Arrays.asList(this.cacheKey.resultClasses), this.cacheKey.hasModifier(1), this.cacheKey.start, this.cacheKey.count, this.prefetchSize, this.prefetchLanguages, this.cacheKey.hasModifier(2));
        ret.setUnitHash(System.identityHashCode(this));
        return ret;
    }

AbstractCacheUnit   privateGetNoLock

private final Object privateGetNoLock() throws Exception {
        Object ret = this.value;
        if (this.isValueUnknown(ret)) {
            ret = this.compute();
            this.value = ret;
        }

        return ret;
    }

AbstractCacheUnit   privateGet

private final Object privateGet() throws Exception {
        return this.getTransactionAwareCache().isForceExclusiveComputation(this) ? this.privateGetSynchronized() : this.privateGetNoLock();
    }

AbstractCacheUnit   get

public final Object get() throws Exception {
        if (!this.useCache()) {
            return this.computeUncached();
        } else {
            TransactionAwareCache transactionAwareCache = this.getTransactionAwareCache();
            boolean success = false;
            AbstractCacheUnit valueUnit = transactionAwareCache.getOrAddUnit(this);
            Object ret = valueUnit.value;

            try {
                ret = this.isValueUnknown(ret) ? valueUnit.privateGet() : ret;
                success = true;
            } catch (CacheValueLoadException var9) {
                if (var9.getCause() instanceof Exception) {
                    throw (Exception)var9.getCause();
                }

                throw var9;
            } finally {
                if (!success) {
                    transactionAwareCache.removeUnit(valueUnit);
                }

            }

            return ret;
        }
    }

FlexibleSearchCacheUnit myGet

public final StandardSearchResult myGet() throws Exception {
        StandardSearchResult ret = (StandardSearchResult)this.get();
        ret.setFromCache(this.usedCachedResult);
        return ret;
    }

FlexibleSearch  search

public SearchResult search(SessionContext _ctx, String query, Map values, List resultClasses, boolean failOnUnknownFields, boolean dontNeedTotal, int start, int count) throws FlexibleSearchException {
        TranslatedQuery tQuery = null;
        int prefetchSize = this.getSearchPrefetchSize(_ctx);
        if (LOG.isDebugEnabled()) {
            LOG.debug(this.getSearchDebug(_ctx, query, resultClasses, failOnUnknownFields, dontNeedTotal, start, count, prefetchSize));
        }

        boolean doExecuteQuery = !this.disableExecution(_ctx);
        SessionContext localCtx = null;

        SearchResult var22;
        try {
            if (_ctx != null) {
                localCtx = JaloSession.getCurrentSession(this.getTenant()).createLocalSessionContext(_ctx);
                localCtx.setAttribute("disableExecution", Boolean.FALSE);
            }

            PK langPK = this.getSearchLangPK(localCtx);
            tQuery = this.translate(localCtx, this.getRestrictionPrincipal(localCtx), query, values != null ? values.size() : 0, langPK != null, failOnUnknownFields, this.disableRestrictions(localCtx), this.disablePrincipalGroupRestrictions(localCtx), values);
            Map _values = tQuery.removeUnusedValues(this.translatePathValueKeys(localCtx, tQuery.getValueKeys(), new CaseInsensitiveParameterMap(values != null ? values : Collections.EMPTY_MAP)));
            Set<PK> queryTCs = tQuery.getTypePKs();
            Set<Integer> beanTCs = new HashSet(queryTCs.size() * 4);
            PersistenceManager pm = this.getTenant().getPersistenceManager();
            Iterator var19 = queryTCs.iterator();

            while(var19.hasNext()) {
                PK typePK = (PK)var19.next();
                beanTCs.addAll(pm.getBeanTypeCodes(typePK));
            }

            if (beanTCs.isEmpty()) {
                throw new JaloInvalidParameterException("empty bean typcode list ( typePKs = " + tQuery.getTypePKs() + ", query = " + tQuery.getSQLTemplate() + " )", 0);
            }

            try {
                if (!this.isCachingDisabled(localCtx)) {
                    int ttl = this.getTTL(localCtx);
                    FlexibleSearch.FlexibleSearchCacheKey cacheKey = this.createCacheKey(resultClasses, dontNeedTotal, start, count, tQuery, doExecuteQuery, langPK, _values, beanTCs, ttl);
                    FlexibleSearchCacheUnit cacheUnit = this.createCacheUnit(prefetchSize, WrapperFactory.getPrefetchLanguages(localCtx), _values, cacheKey);
                    var22 = this.wrapSearchResult(cacheUnit.myGet());
                    return var22;
                }

                var22 = this.wrapSearchResult(this.executeSearch(tQuery, _values, langPK, resultClasses, dontNeedTotal, start, count, prefetchSize, WrapperFactory.getPrefetchLanguages(localCtx), doExecuteQuery));
            } catch (FlexibleSearchException var28) {
                throw var28;
            } catch (Exception var29) {
                throw new FlexibleSearchException(var29, var29.getMessage(), 0);
            }
        } catch (FlexibleSearchException var30) {
            LOG.error("Flexible search error occured...");
            if (tQuery == null) {
                LOG.error("Query translation was not successful.");
            }

            throw var30;
        } catch (JaloItemNotFoundException var31) {
            throw new JaloInternalException(var31, "cannot get type by translated query type pk", 0);
        } finally {
            if (localCtx != null) {
                JaloSession.getCurrentSession(this.getTenant()).removeLocalSessionContext();
            }

        }

        return var22;
    }

FlexibleSearch  search

public SearchResult search(String query, Map values, List resultClasses, boolean failOnUnknownFields, boolean dontNeedTotal, int start, int count) throws FlexibleSearchException {
        return this.search(JaloSession.hasCurrentSession() ? this.getSession().getSessionContext() : null, query, values, resultClasses, failOnUnknownFields, dontNeedTotal, start, count);
    }

DefaultFlexibleSearchService$2  execute

    private <T> de.hybris.platform.jalo.SearchResult<T> getJaloResult(final FlexibleSearchQuery query) {
        return (de.hybris.platform.jalo.SearchResult)this.getSessionService().executeInLocalView(new SessionExecutionBody() {
            public de.hybris.platform.jalo.SearchResult<T> execute() {
                DefaultFlexibleSearchService.this.getQueryPreprocessorRegistry().executeAllPreprocessors(query);
                Map queryParams = (Map)DefaultFlexibleSearchService.this.toPersistenceLayer(query.getQueryParameters());

                try {
                    return FlexibleSearch.getInstance().search(query.getQuery(), queryParams, this.convertModelClassList(query), query.isFailOnUnknownFields(), !query.isNeedTotal(), query.getStart(), query.getCount());
                } catch (FlexibleSearchException var3) {
                    throw new de.hybris.platform.servicelayer.search.exceptions.FlexibleSearchException(var3.getMessage(), var3);
                }
            }

            private List<Class> convertModelClassList(FlexibleSearchQuery queryx) {
                List<Class> resultClassList = new ArrayList(queryx.getResultClassList().size());
                Iterator var4 = queryx.getResultClassList().iterator();

                while(var4.hasNext()) {
                    Class modelClass = (Class)var4.next();
                    resultClassList.add(DefaultFlexibleSearchService.this.getModelService().getModelTypeClass(modelClass));
                }

                return resultClassList;
            }
        });
    }

DefaultFlexibleSearchService$2  execute

DefaultSessionService   executeInLocalView

public Object executeInLocalView(SessionExecutionBody body) {
        Object var3;
        try {
            this.getOrCreateCurrentJaloSession().createLocalSessionContext();
            var3 = body.execute();
        } finally {
            this.getOrCreateCurrentJaloSession().removeLocalSessionContext();
        }

        return var3;
    }

DefaultFlexibleSearchService    getJaloResult

private <T> de.hybris.platform.jalo.SearchResult<T> getJaloResult(final FlexibleSearchQuery query) {
        return (de.hybris.platform.jalo.SearchResult)this.getSessionService().executeInLocalView(new SessionExecutionBody() {
            public de.hybris.platform.jalo.SearchResult<T> execute() {
                DefaultFlexibleSearchService.this.getQueryPreprocessorRegistry().executeAllPreprocessors(query);
                Map queryParams = (Map)DefaultFlexibleSearchService.this.toPersistenceLayer(query.getQueryParameters());

                try {
                    return FlexibleSearch.getInstance().search(query.getQuery(), queryParams, this.convertModelClassList(query), query.isFailOnUnknownFields(), !query.isNeedTotal(), query.getStart(), query.getCount());
                } catch (FlexibleSearchException var3) {
                    throw new de.hybris.platform.servicelayer.search.exceptions.FlexibleSearchException(var3.getMessage(), var3);
                }
            }

            private List<Class> convertModelClassList(FlexibleSearchQuery queryx) {
                List<Class> resultClassList = new ArrayList(queryx.getResultClassList().size());
                Iterator var4 = queryx.getResultClassList().iterator();

                while(var4.hasNext()) {
                    Class modelClass = (Class)var4.next();
                    resultClassList.add(DefaultFlexibleSearchService.this.getModelService().getModelTypeClass(modelClass));
                }

                return resultClassList;
            }
        });
    }

DefaultFlexibleSearchService    search

public <T> SearchResult<T> search(FlexibleSearchQuery query) {
        ServicesUtil.validateParameterNotNull(query, "The 'query' is null!");
        de.hybris.platform.jalo.SearchResult<T> jaloResult = this.getJaloResult(query);
        if (jaloResult.getCount() == 0) {
            return this.createEmptyResult(jaloResult);
        } else {
            return jaloResult instanceof StandardSearchResult ? this.wrapOrConvert(query, (StandardSearchResult)jaloResult, () -> {
                return this.convert(jaloResult);
            }) : this.convert(jaloResult);
        }
    }

DefaultPagedFlexibleSearchService   search

public <T> SearchPageData<T> search(final String query, final Map<String, ?> queryParams, final PageableData pageableData)
    {
        validateParameterNotNull(query, "query cannot be null");
        validateParameterNotNull(pageableData, "pageableData cannot be null");
        Assert.isTrue(pageableData.getCurrentPage() >= 0, "pageableData current page must be zero or greater");
        Assert.isTrue(pageableData.getPageSize() > 0, "pageableData page size must be greater than zero");

        final FlexibleSearchQuery searchQuery = new FlexibleSearchQuery(query);
        if (queryParams != null && !queryParams.isEmpty())
        {
            searchQuery.addQueryParameters(queryParams);
        }

        searchQuery.setNeedTotal(true);
        searchQuery.setStart(pageableData.getCurrentPage() * pageableData.getPageSize());
        searchQuery.setCount(pageableData.getPageSize());

        final SearchResult<T> searchResult = getFlexibleSearchService().search(searchQuery);

        // Create the paged search result
        final SearchPageData<T> result = createSearchPageData();
        result.setResults(searchResult.getResult());
        result.setPagination(createPagination(pageableData, searchResult));
        // Note: does not set sorts

        return result;
    }

DefaultPagedFlexibleSearchService   search

public <T> SearchPageData<T> search(final List<SortQueryData> sortQueries, final String defaultSortCode,
            final Map<String, ?> queryParams, final PageableData pageableData)
    {
        validateParameterNotNull(sortQueries, "sortQueries cannot be null");
        validateParameterNotNull(defaultSortCode, "defaultSortCode cannot be null");
        validateParameterNotNull(pageableData, "pageableData cannot be null");
        Assert.isTrue(!sortQueries.isEmpty(), "sortQueries must not be empty");
        Assert.isTrue(pageableData.getCurrentPage() >= 0, "pageableData current page must be zero or greater");
        Assert.isTrue(pageableData.getPageSize() > 0, "pageableData page size must be greater than zero");

        // Work out which sort and query to use
        final SortQueryData selectedSortQuery = findSortQueryData(sortQueries, pageableData.getSort(), defaultSortCode);

        // Execute the query
        final SearchPageData<T> searchPageData = search(selectedSortQuery.getQuery(), queryParams, pageableData);

        // Specify which sort was used
        searchPageData.getPagination().setSort(selectedSortQuery.getSortCode());
        searchPageData.setSorts(createSorts(sortQueries, selectedSortQuery.getSortCode()));
        return searchPageData;
    }

DefaultCustomerAccountDao   findOrdersByCustomerAndStore

public SearchPageData<OrderModel> findOrdersByCustomerAndStore(final CustomerModel customerModel, final BaseStoreModel store,
            final OrderStatus[] status, final PageableData pageableData)
    {
        validateParameterNotNull(customerModel, "Customer must not be null");
        validateParameterNotNull(store, "Store must not be null");

        final Map<String, Object> queryParams = new HashMap<String, Object>();
        queryParams.put("customer", customerModel);
        queryParams.put("store", store);

        String filterClause = StringUtils.EMPTY;
        if (CollectionUtils.isNotEmpty(getFilterOrderStatusList()))
        {
            queryParams.put("filterStatusList", getFilterOrderStatusList());
            filterClause = FILTER_ORDER_STATUS;
        }

        final List<SortQueryData> sortQueries;

        if (ArrayUtils.isNotEmpty(status))
        {
            queryParams.put("statusList", Arrays.asList(status));
            sortQueries = Arrays.asList(
                    createSortQueryData("byDate",
                            createQuery(FIND_ORDERS_BY_CUSTOMER_STORE_QUERY_AND_STATUS, filterClause, SORT_ORDERS_BY_DATE)),
                    createSortQueryData("byOrderNumber",
                            createQuery(FIND_ORDERS_BY_CUSTOMER_STORE_QUERY_AND_STATUS, filterClause, SORT_ORDERS_BY_CODE)));
        }
        else
        {
            sortQueries = Arrays
                    .asList(
                            createSortQueryData("byDate",
                                    createQuery(FIND_ORDERS_BY_CUSTOMER_STORE_QUERY, filterClause, SORT_ORDERS_BY_DATE)),
                            createSortQueryData("byOrderNumber",
                                    createQuery(FIND_ORDERS_BY_CUSTOMER_STORE_QUERY, filterClause, SORT_ORDERS_BY_CODE)));
        }
        }

        return getPagedFlexibleSearchService().search(sortQueries, "byDate", queryParams, pageableData);
    }

DefaultCustomerAccountService   getOrderList

public SearchPageData<OrderModel> getOrderList(final CustomerModel customerModel, final BaseStoreModel store,
            final OrderStatus[] status, final PageableData pageableData)
    {
        validateParameterNotNull(customerModel, "Customer model cannot be null");
        validateParameterNotNull(store, "Store must not be null");
        validateParameterNotNull(pageableData, "PageableData must not be null");
        return getCustomerAccountDao().findOrdersByCustomerAndStore(customerModel, store, status, pageableData);
    }

DefaultOrderFacade  getPagedOrderHistoryForStatuses

public SearchPageData<OrderHistoryData> getPagedOrderHistoryForStatuses(final PageableData pageableData,
            final OrderStatus... statuses)
    {
        final CustomerModel currentCustomer = (CustomerModel) getUserService().getCurrentUser();
        final BaseStoreModel currentBaseStore = getBaseStoreService().getCurrentBaseStore();
        final SearchPageData<OrderModel> orderResults = getCustomerAccountService().getOrderList(currentCustomer, currentBaseStore,
                statuses, pageableData);

        return convertPageData(orderResults, getOrderHistoryConverter());
    }

AccountPageController   orders
public String orders(@RequestParam(value = "page", defaultValue = "0") final int page,
            @RequestParam(value = "show", defaultValue = "Page") final ShowMode showMode,
            @RequestParam(value = "sort", required = false) final String sortCode, final Model model) throws CMSItemNotFoundException
    {
        // Handle paged search results
        final PageableData pageableData = createPageableData(page, 5, sortCode, showMode);
        final SearchPageData<OrderHistoryData> searchPageData = vinOrderFacade.getPagedOrderHistoryForStatuses(pageableData);
        populateModel(model, searchPageData, showMode);

        storeCmsPageInModel(model, getContentPageForLabelOrId(ORDER_HISTORY_CMS_PAGE));
        setUpMetaDataForContentPage(model, getContentPageForLabelOrId(ORDER_HISTORY_CMS_PAGE));
        model.addAttribute(BREADCRUMBS_ATTR, accountBreadcrumbBuilder.getBreadcrumbs("text.account.orderHistory"));
        model.addAttribute(ThirdPartyConstants.SeoRobots.META_ROBOTS, ThirdPartyConstants.SeoRobots.NOINDEX_NOFOLLOW);
        model.addAttribute("isASM", assistedServiceFacade.isAssistedServiceAgentLoggedIn());
        return getViewForPage(model);
    }

Body:
If you want to test your flex search queries, see the SQL output and the result, you can do this from HAC -> Console -> Flexible Search. The interface is quite simple and useful.

If you want to get all the sql queries, you can go again to HAC -> Monitoring -> Database -> JDBC Logging.


问:
jQuery - Looping through elements with specific Attribute
I know how to loop through the inputs below, searching for the ones with a specific class of "testers"

And here's how I do that:

```<code><input type='text' name='firstname' class="testing" value='John'>
<input type='text' name='lastname' class="testing" value='Smith'>

<script type="text/javascript">
$(document).ready(function(){

 $.each($('.testing'), function() {
   console.log($(this).val());
 });

});
</script>
</code>```

It outputs the "John", "Smith" as expected.

I want to not use the class="testing" and use a custom attribute: testdata="John".

So this is what I'd be doing:

```<code><input type='text' name='firstname' testdata='John'>
<input type='text' name='lastname' testdata='Smith'>
</code>```

My goal is to auto-populate the values of each input with whatever is inside testdata, but only those detected to have the testdata attribute.

This was my failed attempt at using the $.each loop:

```<code>$.each($('input').attr('testdata'), function() {
  var testdata = $(this).attr('testdata');
  $(this).val(testdata);
});
</code>```

I get this response: Uncaught TypeError: Cannot read property 'length' of undefined
Can anyone see what I'm doing wrong?

答:
For iterating over all elements with testdata attribute and assigning form fields with what their attribute holds try

```<code>$("[testdata]").each(function(){
    $(this).val($(this).attr('testdata'))
})
</code>```

[works with all elements i guess]

Body:
I know how to loop through the inputs below, searching for the ones with a specific class of "testers"

And here's how I do that:

<input type='text' name='firstname' class="testing" value='John'>
<input type='text' name='lastname' class="testing" value='Smith'>

It outputs the "John", "Smith" as expected.

I want to not use the class="testing" and use a custom attribute: testdata="John".

So this is what I'd be doing:

<input type='text' name='firstname' testdata='John'>
<input type='text' name='lastname' testdata='Smith'>

My goal is to auto-populate the values of each input with whatever is inside testdata, but only those detected to have the testdata attribute.

This was my failed attempt at using the $.each loop:

$.each($('input').attr('testdata'), function() {
  var testdata = $(this).attr('testdata');
  $(this).val(testdata);
});

I get this response: Uncaught TypeError: Cannot read property 'length' of undefined
Can anyone see what I'm doing wrong?

Body:
For iterating over all elements with testdata attribute and assigning form fields with what their attribute holds try

$("[testdata]").each(function(){
    $(this).val($(this).attr('testdata'))
})

[works with all elements i guess]


问:
How to design a query where I retrieve last data from resource that I want to apply filter to in RESTful way?
How should a query look like when I want to retrieve last measurements from installations that aren't removed?

Something like that?

```<code>/my-web-service/installations/measurements/last?removed=false
</code>```

The thing is, I don't want to retrieve last measurements that weren't removed from installations. I want to retrieve last measurements from installations that weren't removed.

答:
According to this best practices article, you could use "aliases for common queries":

To make the API experience more pleasant for the average consumer,
  consider packaging up sets of conditions into easily accessible
  RESTful paths. For example, the recently closed tickets query above
  could be packaged up as GET /tickets/recently_closed

So, in your case, it could be:

```<code>/my-web-service/installations/non_removed/measurements/last
</code>```

where non_removed would be an alias for querying installations that weren't removed.

Hope it helps!

Body:
How should a query look like when I want to retrieve last measurements from installations that aren't removed?

Something like that?

/my-web-service/installations/measurements/last?removed=false

The thing is, I don't want to retrieve last measurements that weren't removed from installations. I want to retrieve last measurements from installations that weren't removed.

Body:
According to this best practices article, you could use "aliases for common queries":

To make the API experience more pleasant for the average consumer,
  consider packaging up sets of conditions into easily accessible
  RESTful paths. For example, the recently closed tickets query above
  could be packaged up as GET /tickets/recently_closed

So, in your case, it could be:

/my-web-service/installations/non_removed/measurements/last

where non_removed would be an alias for querying installations that weren't removed.

Hope it helps!