JPA метод findByAttributeName не работает - PullRequest
0 голосов
/ 29 апреля 2019

Когда я ищу как findById (). Это работает нормально, но когда я пытаюсь как findByUsername (String username), я получаю исключение как

java.lang.ClassNotFoundException: antlr.RecognitionException
            at java.net.URLClassLoader.findClass(Unknown Source) ~[na:1.8.0_45]
            at java.lang.ClassLoader.loadClass(Unknown Source) ~[na:1.8.0_45]
            at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) ~[na:1.8.0_45]
            at java.lang.ClassLoader.loadClass(Unknown Source) ~[na:1.8.0_45]
            at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:188) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
            at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:143) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
            at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:119) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
            at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:80) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
            at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:153) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
            at org.hibernate.internal.AbstractSharedSessionContract.getQueryPlan(AbstractSharedSessionContract.java:605) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
            at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:714) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
            at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:3399) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
            at org.hibernate.query.criteria.internal.CriteriaQueryImpl$1.buildCompiledQuery(CriteriaQueryImpl.java:318) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
            at org.hibernate.query.criteria.internal.compile.CriteriaCompiler.compile(CriteriaCompiler.java:149) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
            at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:3699) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
            at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:207) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
            at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_45]
            at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_45]
            at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_45]
        at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:350) ~[spring-orm-5.1.6.RELEASE.jar:5.1.6.RELEASE]
            at com.sun.proxy.$Proxy94.createQuery(Unknown Source) ~[na:na]
            at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_45]
            at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_45]
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_45]

Код таблицы для Mysql

        CREATE TABLE `user` (
            `USER_ID` bigint(20) NOT NULL AUTO_INCREMENT,
            `REGISTER_TYPE` varchar(4) DEFAULT NULL,
            `PROFILE_TYPE` varchar(32) DEFAULT NULL,
            `REGISTRATION_TIME` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
            `LAST_SESSION` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
            `PASSWORD_EXPIRED` smallint(6) DEFAULT '-1',
            `FIELD1` smallint(5) DEFAULT NULL,
            `FIELD2` int(11) DEFAULT NULL,
            `FIELD3` bigint(20) DEFAULT NULL,
            `FIELD4` varchar(256) DEFAULT NULL,
            `FIELD5` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', 
            PRIMARY KEY(`USER_ID`)
        ) ENGINE=InnoDB AUTO_INCREMENT=1000 DEFAULT CHARSET=latin1;

        /*!40101 SET character_set_client = @saved_cs_client */;

        --
        -- Dumping data in table `user`
        --

        LOCK TABLES `user` WRITE;
        /*!40000 ALTER TABLE `user` DISABLE KEYS */;

        INSERT INTO `user` VALUES (1000, 'USER', 'USER', '2019-04-16 06:19:10', '2019-04-16 06:19:10', '-1', NULL, NULL, NULL, NULL, '2019-04-16 06:19:10');
        INSERT INTO `user` VALUES (1001, 'USER', 'USER', '2019-04-16 06:19:10', '2019-04-16 06:19:10', '-1', NULL, NULL, NULL, NULL, '2019-04-16 06:19:10');

        /*!40000 ALTER TABLE `user` ENABLE KEYS */;
        UNLOCK TABLES;

        --
        -- Table structure for `user_registration`
        --

        /*!40101 SET @saved_cs_client     = @@character_set_client */;
        /*!40101 SET character_set_client = utf8 */;

        CREATE TABLE `user_registration`(
            `USER_ID` bigint(20) NOT NULL,
            `USERNAME` varchar(128) NOT NULL,
            `PASSWORD` varchar(128) NOT NULL,
            `PASSWORD_INVALID` smallint(6) DEFAULT '-1',
            `RESET_PASSWORD_CODE` varchar(128) DEFAULT NULL,
            `TIMEOUT` smallint(6) DEFAULT '-1',
            `PASSWORD_CREATION_TIME` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, 
            `RESET_PASSWORD_TIME` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
            `FIELD1` smallint(6) DEFAULT NULL,
            `FIELD2` int(11) DEFAULT NULL,
            `FIELD3` varchar(256) DEFAULT NULL,
            `FIELD4` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
            PRIMARY KEY (`USER_ID`),
            CONSTRAINT `USERNAME` UNIQUE (`USERNAME`),
            CONSTRAINT `userreg_user_key1` FOREIGN KEY (`USER_ID`) REFERENCES `user` (`USER_ID`) ON DELETE CASCADE
        ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

        /*!40101 SET character_set_client = @saved_cs_client */;

        --
        -- Dumping data in table `user_registration`
        --

        LOCK TABLES `user_registration` WRITE;
        /*!40000 ALTER TABLE `user_registration` DISABLE KEYS */;

        INSERT INTO `user_registration` VALUES ('1000', 'abc@gmail.com',  'abc@123', '-1', 'RESETPASS', '-1', '2019-04-17 07:37:10', '2019-04-17 07:37:10', NULL, NULL, NULL, '2019-04-17 07:37:10');
        INSERT INTO `user_registration` VALUES ('1001', 'abcd@gmail.com','abcd@123', '-1', 'RESETPASS', '-1', '2019-04-17 07:37:10', '2019-04-17 07:37:10', NULL, NULL, NULL, '2019-04-17 07:37:10');

        /*!40000 ALTER TABLE `user_registration` ENABLE KEYS */;
        UNLOCK TABLES;

Класс Entity для UserRegistration -

 package com.model;
    // Generated Apr 26, 2019 8:02:54 PM by Hibernate Tools 5.1.7.Final

    import java.util.Date;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.FetchType;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.OneToOne;
    import javax.persistence.PrimaryKeyJoinColumn;
    import javax.persistence.Table;
    import javax.persistence.Temporal;
    import javax.persistence.TemporalType;
    import javax.persistence.UniqueConstraint;
    import org.hibernate.annotations.GenericGenerator;
    import org.hibernate.annotations.Parameter;

    /**
     * UserRegistration generated by hbm2java
     */
    @Entity
    @Table(name = "user_registration", catalog = "flipkart", uniqueConstraints = @UniqueConstraint(columnNames = "USERNAME"))
    public class UserRegistration implements java.io.Serializable {

        private long userId;
        private User user;
        private String username;
        private String password;
        private Short passwordInvalid;
        private String resetPasswordCode;
        private Short timeout;
        private Date passwordCreationTime;
        private Date resetPasswordTime;
        private Short field1;
        private Integer field2;
        private String field3;
        private Date field4;

        public UserRegistration() {
        }

        public UserRegistration(User user, String username, String password, Date passwordCreationTime,
                Date resetPasswordTime, Date field4) {
            this.user = user;
            this.username = username;
            this.password = password;
            this.passwordCreationTime = passwordCreationTime;
            this.resetPasswordTime = resetPasswordTime;
            this.field4 = field4;
        }

        public UserRegistration(User user, String username, String password, Short passwordInvalid,
                String resetPasswordCode, Short timeout, Date passwordCreationTime, Date resetPasswordTime, Short field1,
                Integer field2, String field3, Date field4) {
            this.user = user;
            this.username = username;
            this.password = password;
            this.passwordInvalid = passwordInvalid;
            this.resetPasswordCode = resetPasswordCode;
            this.timeout = timeout;
            this.passwordCreationTime = passwordCreationTime;
            this.resetPasswordTime = resetPasswordTime;
            this.field1 = field1;
            this.field2 = field2;
            this.field3 = field3;
            this.field4 = field4;
        }

        @GenericGenerator(name = "generator", strategy = "foreign", parameters = @Parameter(name = "property", value = "user"))
        @Id
        @GeneratedValue(generator = "generator")

        @Column(name = "USER_ID", unique = true, nullable = false)
        public long getUserId() {
            return this.userId;
        }

        public void setUserId(long userId) {
            this.userId = userId;
        }

        @OneToOne(fetch = FetchType.LAZY)
        @PrimaryKeyJoinColumn
        public User getUser() {
            return this.user;
        }

        public void setUser(User user) {
            this.user = user;
        }

        @Column(name = "USERNAME", unique = true, nullable = false, length = 128)
        public String getUsername() {
            return this.username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        @Column(name = "PASSWORD", nullable = false, length = 128)
        public String getPassword() {
            return this.password;
        }

        public void setPassword(String password) {
            this.password = password;
        }

        @Column(name = "PASSWORD_INVALID")
        public Short getPasswordInvalid() {
            return this.passwordInvalid;
        }

        public void setPasswordInvalid(Short passwordInvalid) {
            this.passwordInvalid = passwordInvalid;
        }

        @Column(name = "RESET_PASSWORD_CODE", length = 128)
        public String getResetPasswordCode() {
            return this.resetPasswordCode;
        }

        public void setResetPasswordCode(String resetPasswordCode) {
            this.resetPasswordCode = resetPasswordCode;
        }

        @Column(name = "TIMEOUT")
        public Short getTimeout() {
            return this.timeout;
        }

        public void setTimeout(Short timeout) {
            this.timeout = timeout;
        }

        @Temporal(TemporalType.TIMESTAMP)
        @Column(name = "PASSWORD_CREATION_TIME", nullable = false, length = 26)
        public Date getPasswordCreationTime() {
            return this.passwordCreationTime;
        }

        public void setPasswordCreationTime(Date passwordCreationTime) {
            this.passwordCreationTime = passwordCreationTime;
        }

        @Temporal(TemporalType.TIMESTAMP)
        @Column(name = "RESET_PASSWORD_TIME", nullable = false, length = 26)
        public Date getResetPasswordTime() {
            return this.resetPasswordTime;
        }

        public void setResetPasswordTime(Date resetPasswordTime) {
            this.resetPasswordTime = resetPasswordTime;
        }

        @Column(name = "FIELD1")
        public Short getField1() {
            return this.field1;
        }

        public void setField1(Short field1) {
            this.field1 = field1;
        }

        @Column(name = "FIELD2")
        public Integer getField2() {
            return this.field2;
        }

        public void setField2(Integer field2) {
            this.field2 = field2;
        }

        @Column(name = "FIELD3", length = 256)
        public String getField3() {
            return this.field3;
        }

        public void setField3(String field3) {
            this.field3 = field3;
        }

        @Temporal(TemporalType.TIMESTAMP)
        @Column(name = "FIELD4", nullable = false, length = 26)
        public Date getField4() {
            return this.field4;
        }

        public void setField4(Date field4) {
            this.field4 = field4;
        }

    }

СЕРВИСНЫЙ КЛАСС ДЛЯ РЕГИСТРАЦИИ ПОЛЬЗОВАТЕЛЯ

    package com.service;

    import java.util.Optional;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;

    import com.model.UserRegistration;
    import com.repository.UserRegistrationRepository;

    @Service
    public class UserRegistrationService {

        private final UserRegistrationRepository userRegistrationRepository;

        @Autowired
        public UserRegistrationService(UserRegistrationRepository userRegistrationRepository) {
            this.userRegistrationRepository= userRegistrationRepository;
        }

        /*public Optional<UserRegistration> getByUsername(String username){
            return userRegistrationRepository.retreiveByUsername(username);
            //return userRegistrationRepository.findById(username);
        }*/

        public UserRegistration getByUsername(String username){
            return userRegistrationRepository.findByUsername(username);
            //return userRegistrationRepository.findById(username);
        }
    }

РЕПОЗИТОР ДЛЯ РЕГИСТРАЦИИ Пользователей -

    package com.repository;

    import java.util.Optional;

    import org.springframework.data.jpa.repository.JpaRepository;
    import org.springframework.data.jpa.repository.Query;
    import org.springframework.data.repository.CrudRepository;
    import org.springframework.data.repository.query.Param;
    import org.springframework.stereotype.Repository;

    import com.model.UserRegistration;
    import java.lang.String;
    import java.util.List;

    @Repository
    public interface UserRegistrationRepository extends CrudRepository<UserRegistration, Long>{

        /*@Query("select u from UserRegistration u where u.username=:username")
        public UserRegistration retreiveByUsername(@Param("username")String username);*/

        /*@Query(value="select u from UserRegistration u where u.username=:username")
        public UserRegistration retreiveUsername(String username);*/

        public UserRegistration findByUsername(String username);
    }

МОЙ pom.xml

http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 org.springframework.boot весна-загрузка-стартер-родитель 2.1.4.RELEASE ком JSPTest 0.0.1-SNAPSHOT JSPTest Демонстрационный проект для Spring Boot

        <properties>
            <java.version>1.8</java.version>
            <jjwt.version>0.6.0</jjwt.version>
        </properties>

        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>

            <!-- DEPENDENCY FOR USING JSP PAGES STARTS -->

            <dependency>
                <groupId>org.apache.tomcat.embed</groupId>
                <artifactId>tomcat-embed-jasper</artifactId>
                <scope>provided</scope>
            </dependency>

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
            </dependency>

            <!-- DEPENDENCY ADDED BECAUSE OF ERROR java.lang.ClassNotFoundException: org.eclipse.jdt.internal.compiler.env.INameEnvironment -->

            <dependency>
                <groupId>org.eclipse.jdt.core.compiler</groupId>
                <artifactId>ecj</artifactId>
                <version>4.6.1</version>
                <scope>provided</scope>
            </dependency>

            <!-- DEPENDENCY FOR USING JSP PAGES ENDS -->

            <!-- DEPENDENCY FOR JPA STARTS -->

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-jpa</artifactId>
            </dependency>

            <!-- DEPENDENCY FOR JPA ENDS -->

            <!-- DEPENDENCY FOR MYSQL STARTS -->

            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <scope>runtime</scope>
            </dependency>

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-jdbc</artifactId>
            </dependency>

            <!-- DEPENDENCY FOR MYSQL ENDS -->

            <!-- DEPENDENCY FOR SECURITY STARTS -->

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-security</artifactId>
            </dependency>

            <!-- DEPENDENCY FOR SECURITY ENDS -->

            <!-- DEPENDENCY FOR JWT STARTS -->

            <dependency>
                <groupId>io.jsonwebtoken</groupId>
                <artifactId>jjwt</artifactId>
                <version>${jjwt.version}</version>
            </dependency>

            <!-- DEPENDENCY FOR JWT ENDS -->

            <!-- DEPENDENCY FOR org.apache.common.lang3 STARTS -->

            <dependency>
              <groupId>org.apache.commons</groupId>
              <artifactId>commons-lang3</artifactId>
            </dependency>

            <!-- DEPENDENCY FOR org.apache.common.lang3 ENDS -->

            <!-- DEPENDENCY FOR HIBERNATE NOT REQUIRED YET STARTS -->

            <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-core</artifactId>
            </dependency>

            <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-entitymanager</artifactId>
            </dependency>

            <!-- <dependency>
                <groupId>org.hibernate.common</groupId>
                <artifactId>hibernate-commons-annotations</artifactId>
                <version>4.0.4.Final</version>
            </dependency> -->
            <dependency>
                <groupId>org.hibernate.common</groupId>
                <artifactId>hibernate-commons-annotations</artifactId>
                <version>5.1.0.Final</version>
            </dependency>




            <dependency>
                <groupId>antlr</groupId>
                <artifactId>antlr</artifactId>
            </dependency>

            <!--
            <dependency>
                    <groupId>javax.xml.bind</groupId>
                    <artifactId>jaxb-api</artifactId>
            </dependency> -->

            <!-- DEPENDENCY FOR HIBERNATE NOT REQUIRED YET ENDS -->

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>

            <!-- DEPENDENCY FOR USING @ConfigurationProperties Annotation STARTS -->

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-configuration-processor</artifactId>
                <optional>true</optional>
            </dependency>
        </dependencies>

        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>

    </project>

1 Ответ

0 голосов
/ 30 апреля 2019
This resolved my issue:

    <dependency>
        <groupId>org.antlr</groupId>
        <artifactId>antlr-complete</artifactId>
        <version>3.5.2</version>
    </dependency>

previously i was using this which was unable to create HQL queries

<dependency>
     <groupId>antlr</groupId>
     <artifactId>antlr</artifactId>
</dependency>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...