JPA findByAttributeName method not working - spring

When i am searching as findById(). It is working fine but when i am trying as findByUsername(String username) I am getting exception as
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]
The Table code for Mysql is
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;
The Entity class for UserRegistration is
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;
}
}
THE SERVICE CLASS FOR UserRegistration is
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);
}
}
THE REPOSITORY FOR UserRegistration is
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);
}
MY pom.xml is
http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.1.4.RELEASE
com
JSPTest
0.0.1-SNAPSHOT
JSPTest
Demo project for 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>

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>

Related

Flyway with spring boot 3.xxx problems when execute script

I'm trying to create a test project using flyway and spring 3.0.1.
Whenever I try to run the project when the flyway tries to run the script, an error appears stating that the tables have already been created previously.
I'm working with the h2 database, this type of error shouldn't happen...
I have a suspicion that spring jpa's hibernate is generating the tables even though I parameterize it so as not to create table by jpa.
application.yml
spring:
datasource:
url: jdbc:h2:mem:clientdb
driver-class-name: org.h2.Driver
username: sa
password: password
jpa:
show-sql: true
database-platform: org.hibernate.dialect.H2Dialect
hibernate:
ddl-auto: none
h2:
console:
enabled: true
flyway:
enabled: true
url: jdbc:h2:mem:clientdb
user: sa
password: password
#group: true
baseline-on-migrate: true
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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.br.smart</groupId>
<artifactId>smart-cliente</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>smart-cliente</name>
<description>Serviço responsável por armazenar os cliente</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
<!--<version>5.0.3</version>-->
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<!--<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.0.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
sql
CREATE SEQUENCE "SEQ_CLIENTE_TELEFONE";
CREATE SEQUENCE "SEQ_ENDERECO_CLIENTE";
CREATE SEQUENCE "SEQ_CLIENTE";
CREATE TABLE CLIENTE_EMAIL (
COD_CLIENTE INTEGER NOT NULL,
EMAIL VARCHAR(200) NOT NULL
);
CREATE TABLE CLIENTE_TELEFONE (
COD_TELEFONE_CLIENTE INTEGER NOT NULL,
DDI VARCHAR(4) NOT NULL,
DDD VARCHAR(3) NOT NULL,
NUMERO VARCHAR(12) NOT NULL,
TIPO_TELEFONE VARCHAR(20) NOT NULL
);
CREATE TABLE CLIENTE_TELEFONE (
COD_ENDERECO_CLIENTE INTEGER NOT NULL,
LOGRADOURO VARCHAR(150) NOT NULL,
NUMERO VARCHAR(6) NOT NULL,
COMPLEMENTO VARCHAR(20),
BAIRRO VARCHAR(50),
CIDADE VARCHAR(50),
ESTADO VARCHAR(50),
PAIS VARCHAR(50),
CEP VARCHAR(20),
TIPO_ENDERECO VARCHAR(15)
);
CREATE TABLE CLIENTE (
COD_USUARIO INTEGER NOT NULL,
NOME VARCHAR(100) NOT NULL,
CPF_CNPJ VARCHAR(14) NOT NULL
);
entity
#Entity
#AllArgsConstructor
#Getter
#Builder
#Table(name = "CLIENTE")
public class ClientEntity {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_CLIENTE")
#Column(name = "COD_USUARIO")
private Integer id;
#Column(name = "NOME")
private String name;
#Column(name = "CPF_CNPJ")
private String cpfCnpj;
#OneToMany(mappedBy = "clientEntity")
private List<PhoneEntity> phoneList;
#OneToMany(mappedBy = "clientEntity")
private List<AddressEntity> addressList;
#ElementCollection(fetch = FetchType.LAZY)
#CollectionTable(name = "CLIENTE_EMAIL", joinColumns = #JoinColumn(name = "COD_USUARIO"))
#Column(name = "EMAIL")
private Set<String> emailSet
#Entity
#Builder
#AllArgsConstructor
#Getter
#Table(name = "ENDERECO_CLIENTE")
public class AddressEntity {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_ENDERECO_CLIENTE")
#Column(name = "COD_ENDERECO_CLIENTE")
private Integer id;
#Column(name = "LOGRADOURO")
private String location;
#Column(name = "NUMERO")
private String number;
#Column(name = "COMPLEMENTO")
private String complement;
#Column(name = "BAIRRO")
private String district;
#Column(name = "CIDADE")
private String city;
#Column(name = "ESTADO")
private String state;
#Column(name = "PAIS")
private String country;
#Column(name = "CEP")
private String zipCode;
#Column(name = "TIPO_ENDERECO")
private String addressType;
#ManyToOne(fetch = FetchType.EAGER)
private ClientEntity clientEntity;
#Entity
#AllArgsConstructor
#Builder
#Getter
#Table(name = "CLIENTE_TELEFONE")
public class PhoneEntity {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_CLIENTE_TELEFONE")
#Column(name = "COD_TELEFONE_CLIENTE")
private Integer id;
#Column(name = "DDI")
private String ddi;
#Column(name = "DDD")
private String ddd;
#Column(name = "NUMERO")
private String number;
#Column(name = "TIPO_TELEFONE")
private String phoneType;
#ManyToOne(fetch = FetchType.EAGER)
private ClientEntity clientEntity;
I tried to create a flyway configuration file as described in some stackoverflow links and I was unsuccessful.

JPA in query does not seem to return any result

I am trying to run an in query (springboot+jpa+mysql). I have enabled the debug logs, the query seem to be fine, however spring jpa does not return any result.
Here are the configs:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<!-- Spring dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
<scope>runtime</scope>
</dependency>
</dependencies>
Here is my repository:
#Query(value = "select * from targeting_locations where targeting_location_master_id in (:targetingLocationMasterIds)", nativeQuery = true)
List<TargetingLocations> findAllByTargetingLocationMasterIdIn(#Param("targetingLocationMasterIds") List<Long> targetingLocationMasterIds);
// Or
#Query("SELECT t FROM TargetingLocations t WHERE t.targetingLocationMasterId IN :targetingLocationMasterIds")
List<TargetingLocations> findAllByTargetingLocationMasterIdIn(#Param("targetingLocationMasterIds") List<Long> targetingLocationMasterIds);
Point to be noted here is that, the column in 'in' query is not the primary key.
#Entity
#Table(name = "targeting_locations")
public class TargetingLocations {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
public Long id;
#Column(name = "geohash")
public String geoHash;
#Column(name = "site_name")
public String siteName;
#Column(name = "city")
public String city;
#Column(name = "country")
public String country;
#Column(name = "state")
public String state;
#Column(name = "latitude")
public Double latitude;
#Column(name = "longitude")
public Double longitude;
#Column(name = "targeting_type")
public String targetingType;
#Column(name = "targeting_data")
public String targetingData;
#Column(name = "targeting_location_master_id")
public Long targetingLocationMasterId; // ----> in query in this column
Query generated:
Hibernate:
select
targetingl0_.id as id1_1_,
targetingl0_.city as city2_1_,
targetingl0_.country as country3_1_,
targetingl0_.geohash as geohash4_1_,
targetingl0_.latitude as latitude5_1_,
targetingl0_.longitude as longitud6_1_,
targetingl0_.site_name as site_nam7_1_,
targetingl0_.state as state8_1_,
targetingl0_.targeting_data as targetin9_1_,
targetingl0_.targeting_location_master_id as targeti10_1_,
targetingl0_.targeting_type as targeti11_1_
from
targeting_locations targetingl0_
where
targetingl0_.targeting_location_master_id in (
?
)
2021-02-23 16:22:46.199 TRACE 28282 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [BIGINT] - [13063]
Just define that in your repository as a method.
List<TargetingLocations> findByTargetingLocationMasterIdIn(List<Long> targetingLocationMasterIds);
Remove #Query and also the name should start with findBy... not findAll...
What you want to achieve will be implemented and come automatically from spring-jpa

com.mongodb.MongoSocketOpenException: Exception opening socket with spring boot and mongodb cloud

Please suggest any solution for the below exception which is occuring while running my rest api while executing springboot application with mongodb cloud db. I have created collection in mongodb as well and configured below properties.
com.mongodb.MongoSocketOpenException: Exception opening socket
at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:70) ~[mongodb-driver-core-4.1.1.jar:na]
at com.mongodb.internal.connection.InternalStreamConnection.open(InternalStreamConnection.java:143) ~[mongodb-driver-core-4.1.1.jar:na]
at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.lookupServerDescription(DefaultServerMonitor.java:188) ~[mongodb-driver-core-4.1.1.jar:na]
at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:144) ~[mongodb-driver-core-4.1.1.jar:na]
at java.base/java.lang.Thread.run(Thread.java:832) ~[na:na]
Caused by: java.net.ConnectException: Connection refused: no further information
at java.base/sun.nio.ch.Net.pollConnect(Native Method) ~[na:na]
at java.base/sun.nio.ch.Net.pollConnectNow(Net.java:589) ~[na:na]
at java.base/sun.nio.ch.NioSocketImpl.timedFinishConnect(NioSocketImpl.java:549) ~[na:na]
at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:597) ~[na:na]
at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:333) ~[na:na]
at java.base/java.net.Socket.connect(Socket.java:648) ~[na:na]
at com.mongodb.internal.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:78) ~[mongodb-driver-core-4.1.1.jar:na]
at com.mongodb.internal.connection.SocketStream.initializeSocket(SocketStream.java:79) ~[mongodb-driver-core-4.1.1.jar:na]
at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:65) ~[mongodb-driver-core-4.1.1.jar:na]
... 4 common frames omitted
Model class
------------
package com.praveen.entity;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import lombok.Data;
#Document
public class Products {
#Id
private String id;
private Integer p_id;
private String p_name;
private Integer p_cost;
private Integer countInStock;
private Integer numReviews;
private String image;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Integer getP_id() {
return p_id;
}
public void setP_id(Integer p_id) {
this.p_id = p_id;
}
public String getP_name() {
return p_name;
}
public void setP_name(String p_name) {
this.p_name = p_name;
}
public Integer getP_cost() {
return p_cost;
}
public void setP_cost(Integer p_cost) {
this.p_cost = p_cost;
}
public Integer getCountInStock() {
return countInStock;
}
public void setCountInStock(Integer countInStock) {
this.countInStock = countInStock;
}
public Integer getNumReviews() {
return numReviews;
}
public void setNumReviews(Integer numReviews) {
this.numReviews = numReviews;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
#Override
public String toString() {
return "Products [id=" + id + ", p_id=" + p_id + ", p_name=" + p_name + ", p_cost=" + p_cost + ", countInStock="
+ countInStock + ", numReviews=" + numReviews + ", image=" + image + "]";
}
}
RestController class
---------------------
package com.praveen.rest;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RestController;
import com.praveen.entity.Products;
import com.praveen.service.ProductsService;
#RestController
public class ProductsRestController {
#Autowired
private ProductsService service;
#GetMapping("/products")
public ResponseEntity<List<Products>> getProducts(){
List<Products> allProducts = service.getAllProducts();
if(allProducts != null) {
return new ResponseEntity<List<Products>>(allProducts, HttpStatus.OK);
}else {
return new ResponseEntity<List<Products>>(HttpStatus.BAD_REQUEST);
}
}
}
Service class
--------------
package com.praveen.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.praveen.entity.Products;
import com.praveen.repository.ProductsRepository;
#Service
public class ProductsServiceImpl implements ProductsService {
#Autowired
private ProductsRepository prodRepo;
#Override
public List<Products> getAllProducts() {
List<Products> productsList = prodRepo.findAll();
if(productsList != null) {
System.out.println(productsList);
return productsList;
}
return null;
}
}
Repository
-----------
package com.praveen.repository;
import java.io.Serializable;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import com.praveen.entity.Products;
#Repository
public interface ProductsRepository extends MongoRepository<Products, Serializable> {
}
application.properties
-----------------------
spring.data.mongodb.url = mongodb+srv://praveen:praveen#cluster0.qrvkm.mongodb.net/miniproject?retryWrites=true&w=majority
spring.data.mongodb.database = products
spring.data.mongodb.port = 27017
spring.data.mongodb.repositories.enabled=true
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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.praveen</groupId>
<artifactId>NgRx-Products</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>05-MiniProject-NgRx-Products</name>
<description>NgRx package with Products data using springboot</description>
<properties>
<java.version>15</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
Please suggest any solution for the above exception, I have given all my files in the above.
Try adding this annotation to your main class file
#EnableAutoConfiguration(exclude={MongoAutoConfiguration.class})
Search services in start.
open it.
search for mongodb there.
start/restart mongodb services from there.
It should work properly.
this exception occurs due to mongodb incorrect port in application properties. So only changing spring.data.mongodb.port=27017 in application.properties file made it work. Also make sure you started mongodb server locally.
Check the connect to MongoDB sever locally with url:portNumber mentioned in the application.properties from where your code is getting executed.

JpaRepsitory giving error while using method existsByUserName(String userName);

I have created a JpaRepository interface where i define a method named existsByUserName(String userName). But because of this method, i am getting error.
UserRepository interface
package org.avijit.DAO; import org.avijit.Domain.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface UserRepository extends JpaRepository<User, Integer> {
boolean existsByUserName(String userName);
}
My Controller class is
package org.avijit.Controller;
import org.avijit.DAO.UserRepository;
import org.avijit.Domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.validation.Valid;
import java.util.List;
#Controller
public class baseController {
#Autowired
UserRepository userRepository;
#RequestMapping("/")
public String homePage() {
System.out.println(userRepository.findAll());
return "HomePage";
}
#RequestMapping("/register")
public String register(Model model) {
model.addAttribute(new User());
return "RegistrationPage";
}
#RequestMapping(value = "/doRegistration", method = RequestMethod.POST)
public String doRegistration(#Valid #ModelAttribute("user") User user, BindingResult result) {
if (result.hasErrors()) {
return "RegistrationPage";
} else {
if (user.getId() < 0) {
userRepository.save(user);
return "redirect:/memberList";
} else {
User tempUser = userRepository.findOne(user.getId());
if (!tempUser.getUserName().equals(user.getUserName()) && userRepository.existsByUserName(user.getUserName())) {
result.rejectValue("userName", "DuplicateKey.user.userName", "This username already exist! Try again !");
return "RegistrationPage";
} else {
tempUser.setFirstName(user.getFirstName());
tempUser.setLastName(user.getLastName());
tempUser.setUserName(user.getUserName());
tempUser.setMobile(user.getMobile());
tempUser.setAddress(user.getAddress());
tempUser.setPassword(user.getPassword());
userRepository.save(tempUser);
return "redirect:/memberList";
}
}
}
}
#RequestMapping(value = "/memberList")
public String memberList(Model model) {
List<User> list = userRepository.findAll();
model.addAttribute("list", list);
return "UserList";
}
}
My Entity class is
package org.avijit.Domain;
import org.hibernate.validator.constraints.NotBlank;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class User {
#Id
#GeneratedValue
private Integer id;
#NotBlank
private String firstName;
#NotBlank
private String lastName;
#NotBlank
private String userName;
#NotBlank
private String mobile;
#NotBlank
private String address;
#NotBlank
private String password;
public User() {
}
public User(String firstName, String lastName, String userName, String mobile, String address, String password) {
this.firstName = firstName;
this.lastName = lastName;
this.userName = userName;
this.mobile = mobile;
this.address = address;
this.password = password;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public String toString() {
return "User{" +
"id=" + id +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", userName='" + userName + '\'' +
", mobile='" + mobile + '\'' +
", address='" + address + '\'' +
", password='" + password + '\'' +
'}';
}
}
My pom.xml is
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
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>org.avijit.jpaproject</groupId>
<artifactId>jpaproject</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.9.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.11.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.11.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.3.4.Final</version>
</dependency>
<!--Extra Dependency -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.41</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
</dependencies>
And error stack trace is below
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'baseController': Unsatisfied dependency expressed through field 'userRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property existsByUserName found for type User!
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:592)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:370)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1219)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:551)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:754)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:444)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:326)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4727)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5189)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:752)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:728)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734)
at org.apache.catalina.startup.HostConfig.manageApp(HostConfig.java:1702)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:300)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:482)
at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:431)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:300)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
at javax.management.remote.rmi.RMIConnectionImpl.doOperation(RMIConnectionImpl.java:1468)
at javax.management.remote.rmi.RMIConnectionImpl.access$300(RMIConnectionImpl.java:76)
at javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(RMIConnectionImpl.java:1309)
at javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(RMIConnectionImpl.java:1401)
at javax.management.remote.rmi.RMIConnectionImpl.invoke(RMIConnectionImpl.java:829)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:361)
at sun.rmi.transport.Transport$1.run(Transport.java:200)
at sun.rmi.transport.Transport$1.run(Transport.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:683)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property existsByUserName found for type User!
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1583)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:207)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1131)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1059)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:589)
... 60 more
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property existsByUserName found for type User!
at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:75)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:327)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:307)
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:270)
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:241)
at org.springframework.data.repository.query.parser.Part.<init>(Part.java:76)
at org.springframework.data.repository.query.parser.PartTree$OrPart.<init>(PartTree.java:235)
at org.springframework.data.repository.query.parser.PartTree$Predicate.buildTree(PartTree.java:373)
at org.springframework.data.repository.query.parser.PartTree$Predicate.<init>(PartTree.java:353)
at org.springframework.data.repository.query.parser.PartTree.<init>(PartTree.java:84)
at org.springframework.data.jpa.repository.query.PartTreeJpaQuery.<init>(PartTreeJpaQuery.java:61)
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:95)
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateIfNotFoundQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:206)
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$AbstractQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:73)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.<init>(RepositoryFactorySupport.java:367)
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:190)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:239)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:225)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:92)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1642)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1579)
Try Updating below line
#Repository public interface UserRepository extends JpaRepository {
with
#Repository public interface UserRepository extends JpaRepository<User,<data_type_primary_key>> {
replace "< data_type_primary_key>" with the actual data type of primary Key in your entity.
Just changed my jpa-version
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.11.9.RELEASE</version>
</dependency>
Now everything working fine !!!
As stated in this link
Currently to implements exists with predicate (e.g. existsByUsername)
we have to use #Query manually, e.g.
http://stackoverflow.com/a/27156094/122441
Please support this convenience method directly in Spring Data JPA.
So you have to write it manually with #Query
Please see the solution here
#Query("SELECT CASE WHEN COUNT(u) > 0 THEN 'true' ELSE 'false' END FROM ENTITY e WHERE e.username = :userName")
EDIT:
I got it working without query with dependency org.springframework.data:spring-data-jpa:jar:2.0.6.RELEASE

How do I fix this Spring Boot entity relationship Error "creating bean with name 'entityManagerFactory' Unable to map collection"?

I am trying to create a secure login and I'm doing this by assigning a user to a role which will determine what kind of access they can have. My code has no errors but when I try to run the server I get the following error (my server will not even start):
"Error creating bean with name 'entityManagerFactory' Invocation of init method failed; nested exception is org.hibernate.AnnotationException: Unable to map collection com.model.User.roles"
This is my role class:
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Role {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
public Role() {
}
public Role(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return "Role{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
This is part of my User class:
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.persistence.*;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
#Entity
#EntityListeners(AuditingEntityListener.class)
#Table(uniqueConstraints = #UniqueConstraint(columnNames = "emailAddress"))
public class User implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long userId;
//#NotBlank
#OneToMany(fetch=FetchType.LAZY, cascade=CascadeType.ALL)
public List<Subject> subject;
#ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinTable(
name = "users_roles",
joinColumns = #JoinColumn(
name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(
name = "role_id", referencedColumnName = "id"))
public Collection<Role> roles;
This is my POM file (I know it is all over the place):
<?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.finalYearProject</groupId>
<artifactId>student-life</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<!-- upgrade to thymeleaf version 3 -->
<thymeleaf.version>3.0.8.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
<thymeleaf-extras-springsecurity4.version>3.0.2.RELEASE</thymeleaf-extras-springsecurity4.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.3.7</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
UPDATE
This is what I changed in the Role class to fix the problem:
#ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinTable(
name = "users_roles",
joinColumns = #JoinColumn(
name = "user_userId", referencedColumnName = "userId"),
inverseJoinColumns = #JoinColumn(
name = "role_id", referencedColumnName = "id"))
The reference Column in the User entity is wrong.
You have defined:
private Long userId;
So the user table has a PK with the name user_id and the mapping must be:
#JoinTable(
name = "users_roles",
joinColumns = #JoinColumn(
name = "user_id", referencedColumnName = "user_id"),
inverseJoinColumns = #JoinColumn(
name = "role_id", referencedColumnName = "id"))
public Collection roles;
Try to define a collection of Users in the Role class
#ManyToMany(mappedBy = "roles")
private Collection<User> users;

Resources