Pushing Spring boot app to heroku not completed - java

when I'm deploying my simple project to Heroku I'm getting a maven-plugin error
Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin
my code is very simple it's one entity class and restController class, when I run my project on my pc it working but the deployment failed.
my class
package com.hosting.hostingTest;
public class BucketList {
private long id;
private String name;
public BucketList(long id, String name) {
this.id = id;
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;
}
}
my rest controller
package com.hosting.hostingTest;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class BucketListController {
private List<BucketList> myBucketList = new ArrayList<>();
private final AtomicLong counter = new AtomicLong();
public BucketListController(){
myBucketList.add(new BucketList(counter.incrementAndGet(), "Visit Colosseum in Rome"));
}
#GetMapping(value = "/")
public ResponseEntity index() {
return ResponseEntity.ok(myBucketList);
}
#GetMapping(value = "/bucket")
public ResponseEntity getBucket(#RequestParam(value="id") Long id) {
BucketList itemToReturn = null;
for(BucketList bucket : myBucketList){
if(bucket.getId() == id)
itemToReturn = bucket;
}
if(itemToReturn == null){
return ResponseEntity.ok("No bucket found with id " + id);
}else {
return ResponseEntity.ok(itemToReturn);
}
}
#PostMapping(value = "/")
public ResponseEntity addToBucketList(#RequestParam(value="name") String name) {
myBucketList.add(new BucketList(counter.incrementAndGet(), name));
return ResponseEntity.ok(myBucketList);
}
#PutMapping(value = "/")
public ResponseEntity updateBucketList(#RequestParam(value="name") String name, #RequestParam(value="id") Long id) {
myBucketList.forEach(bucketList -> {
if(bucketList.getId() == id){
bucketList.setName(name);
}
});
return ResponseEntity.ok(myBucketList);
}
#DeleteMapping(value = "/")
public ResponseEntity removeBucketList(#RequestParam(value="id") Long id) {
BucketList itemToRemove = null;
for(BucketList bucket : myBucketList){
if(bucket.getId() == id)
itemToRemove = bucket;
}
myBucketList.remove(itemToRemove);
return ResponseEntity.ok(myBucketList);
}
}
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.3.2.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.hosting</groupId>
<artifactId>hostingTest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>hostingTest</name>
<description>Demo project for Spring Boot</description>
<packaging>jar</packaging>
<properties>
<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
the error :
[INFO] Compiling 3 source files to /tmp/build_a3c8365b/target/classes
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 10.228 s
[INFO] Finished at: 2020-08-12T12:41:17Z
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project hostingTest: Compilation failure -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
! ERROR: Failed to build app with Maven
We're sorry this build is failing! If you can't find the issue in application code,
please submit a ticket so we can help: https://help.heroku.com/
! Push rejected, failed to compile Java app.
! Push failed

Related

Connect with MSSQL with Spring Reactive (R2DBC)

I am currently trying to establish a database connection with a Microsoft SQL Server.
Unfortunately I can not understand why it does not work. And the error message can unfortunately not give me precise information.
It looks like my code isn't even trying to connect to the database.
My Starterclaas:
#SpringBootApplication
public class R2Dbc3Application {
public static void main(String[] args) {
SpringApplication.run(R2Dbc3Application.class, args);
}
}
DatabaseConfiguration:
package com.example.config;
import io.r2dbc.mssql.MssqlConnectionConfiguration;
import io.r2dbc.mssql.MssqlConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.r2dbc.config.AbstractR2dbcConfiguration;
import org.springframework.data.r2dbc.repository.config.EnableR2dbcRepositories;
#Configuration
#EnableR2dbcRepositories("com.example.repository")
public class DatabaseConfiguration extends AbstractR2dbcConfiguration {
private final Logger log = LoggerFactory.getLogger(DatabaseConfiguration.class);
#Value("${spring.data.mssql.host}")
private String host;
#Value("${spring.data.mssql.database}")
private String database;
#Value("${spring.data.mssql.username}")
private String username;
#Value("${spring.data.mssql.password}")
private String password;
#Bean
#Override
public MssqlConnectionFactory connectionFactory() {
System.out.println("Connecting to database" + host);
return new MssqlConnectionFactory(MssqlConnectionConfiguration.builder()
.host(host)
.port(1453)
.database(database)
.username(username)
.password(password)
.build());
}
}
my DatabaseInitializer:
package com.example.config;
import com.example.domain.Person;
import com.example.repository.PersonRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
#Component
public class DatabaseInitializer {
private final Logger log = LoggerFactory.getLogger(DatabaseInitializer.class);
#Autowired
PersonRepository personRepository;
public DatabaseInitializer(PersonRepository personRepository) {
this.personRepository = personRepository;
}
#PostConstruct
public void init() {
log.info("Initializing database if necessary");
personRepository.findAll().count().subscribe(count -> {
if (count == 0) {
log.info("Database is empty, inserting sample data");
createPerson("Josh", "Long", "Pivotal");
createPerson("Julien", "Dubois", "Microsoft");
} else {
log.info("Database is already initialized");
}
});
}
private void createPerson(String firstName, String lastName, String company) {
Person person = new Person();
person.setFirstName(firstName);
person.setLastName(lastName);
person.setCompany(company);
personRepository.save(person).log().subscribe();
}
}
Person.Java:
package com.example.domain;
import org.springframework.data.annotation.Id;
import org.springframework.data.relational.core.mapping.Table;
#Table("person")
public class Person {
#Id
private Long id;
private String firstName;
private String lastName;
private String company;
and getter/setter
My PersonRepository
package com.example.repository;
import com.example.domain.Person;
import org.springframework.data.repository.reactive.ReactiveCrudRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface PersonRepository extends ReactiveCrudRepository<Person, Long> {
}
And my Controller:
package com.example.web;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.domain.Person;
import com.example.repository.PersonRepository;
import reactor.core.publisher.Flux;
#RestController
#RequestMapping("/")
public class PersonController {
private final PersonRepository personRepository;
public PersonController(PersonRepository personRepository) {
this.personRepository = personRepository;
}
#GetMapping("/persons")
public Flux<Person> list() {
return personRepository.findAll();
}
}
My Pom:
<?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.2.6.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>R2DBC2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>R2DBC2</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<!-- see https://github.com/r2dbc/r2dbc-mssql/issues/77 -->
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-core</artifactId>
</dependency>
<dependency>
<groupId>io.r2dbc</groupId>
<artifactId>r2dbc-mssql</artifactId>
<version>1.0.0.M7</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-r2dbc</artifactId>
<version>1.0.0.gh-151-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-libs-snapshot</id>
<url>https://repo.spring.io/libs-snapshot</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
</pluginRepository>
</pluginRepositories>
</project>
Error Message:
This application has no configured error view, so you are seeing this as a fallback.
Tue May 19 12:23:33 CEST 2020
[58026f55-7] There was an unexpected error (type=Not Found, status=404).
org.springframework.web.server.ResponseStatusException: 404 NOT_FOUND
at org.springframework.web.reactive.resource.ResourceWebHandler.lambda$handle$0(ResourceWebHandler.java:325)
Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException:
Error has been observed at the following site(s):
|_ checkpoint ⇢ HTTP GET "/persons" [ExceptionHandlingWebHandler]
Stack trace:
at org.springframework.web.reactive.resource.ResourceWebHandler.lambda$handle$0(ResourceWebHandler.java:325)
at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:44)
at reactor.core.publisher.Mono.subscribe(Mono.java:4210)
at reactor.core.publisher.FluxSwitchIfEmpty$SwitchIfEmptySubscriber.onComplete(FluxSwitchIfEmpty.java:75)
at reactor.core.publisher.MonoFlatMap$FlatMapMain.onComplete(MonoFlatMap.java:174)
at reactor.core.publisher.MonoNext$NextSubscriber.onComplete(MonoNext.java:96)
at reactor.core.publisher.FluxConcatMap$ConcatMapImmediate.drain(FluxConcatMap.java:359)
at reactor.core.publisher.FluxConcatMap$ConcatMapImmediate.onSubscribe(FluxConcatMap.java:21
org.springframework.web.server.ResponseStatusException: 404 NOT_FOUND
It means the endpoint mapping through #GetMapping was not hit. Remember the paths are joined with defined mappings at the class level and then at the method level, the current endpoint would look like:
localhost:8080//persons
This is incorrect.
As long as the #RestController is a root with no further mapping, don't include the "/" character as long as it adds another "layer" or "subpath" in the path. The correct usage would be #RequestMapping("/endpoint-name"). In your case, you don't want an extra "subpath" so omit the annotation:
#RestController
public class PersonController { ... }
Unfortunatelly, I couldn't find any reference to support my statement.

"Exception in thread "mainHow to resolve this exception: " java.lang.NoClassDefFoundError: net/bytebuddy/NamingStrategy..."

I'm trying to connect a local database to my application using hibernate. I'm getting the following error:
Jul 02, 2019 9:20:08 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {[WORKING]}
Exception in thread "main" java.lang.NoClassDefFoundError: net/bytebuddy/NamingStrategy$SuffixingRandom$BaseNameResolver
at org.hibernate.orm.core#5.4.3.Final/org.hibernate.cfg.Environment.buildBytecodeProvider(Environment.java:345)
at org.hibernate.orm.core#5.4.3.Final/org.hibernate.cfg.Environment.buildBytecodeProvider(Environment.java:337)
at org.hibernate.orm.core#5.4.3.Final/org.hibernate.cfg.Environment.<clinit>(Environment.java:230)
at org.hibernate.orm.core#5.4.3.Final/org.hibernate.boot.registry.StandardServiceRegistryBuilder.<init>(StandardServiceRegistryBuilder.java:78)
at org.hibernate.orm.core#5.4.3.Final/org.hibernate.boot.registry.StandardServiceRegistryBuilder.<init>(StandardServiceRegistryBuilder.java:67)
at org.hibernate.orm.core#5.4.3.Final/org.hibernate.boot.registry.StandardServiceRegistryBuilder.<init>(StandardServiceRegistryBuilder.java:58)
at ProjectDBTest/ProjectDBTest2.HibernateUtil.getSessionFactory(HibernateUtil.java:28)
at ProjectDBTest/ProjectDBTest2.App.main(App.java:28)
Caused by: java.lang.ClassNotFoundException: net.bytebuddy.NamingStrategy$SuffixingRandom$BaseNameResolver
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
... 8 more
Any help on how to resolve this would be greatly appreciated.
Initially, I was getting 'java.lang.NoClassDefFoundError: java/sql/SQLException' exception and so I added 'requires java.sql' after seeing this as a suggested solution elsewhere on Stack Overflow, but now a the exception described above arises. I'm not sure where I'm gone wrong in my code or what is missing.
Here is my module-info.java file:
module ProjectDBTest {
requires java.persistence;
//requires lombok;
requires javafx.graphics;
requires org.hibernate.orm.core;
requires java.naming;
requires java.sql;
exports ProjectDBTest2.DB;
}
main class:
package ProjectDBTest2;
import ProjectDBTest2.DB.Vocabulary;
import org.hibernate.Session;
import org.hibernate.Transaction;
import java.util.List;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
Vocabulary word1 = new Vocabulary();
word1.setUnitID(1);
word1.setWord("test");
word1.setVocabClass("noun");
word1.setVocabDefinition("this is a test");
word1.setVocabID(7);
System.out.println(word1.getUnitID());
Transaction transaction = null;
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
transaction = session.beginTransaction();
session.save(word1);
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
}
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
List< Vocabulary > students = session.createQuery("from Vocabulary ", Vocabulary.class).list();
students.forEach(s -> System.out.println(s.getWord()));
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
}
}
}
Hibernate util file:
package ProjectDBTest2;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
public class HibernateUtil {
private static StandardServiceRegistry registry;
private static SessionFactory sessionFactory;
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
try {
// Create registry
registry = new StandardServiceRegistryBuilder().configure().build();
// Create MetadataSources
MetadataSources sources = new MetadataSources(registry);
// Create Metadata
Metadata metadata = sources.getMetadataBuilder().build();
// Create SessionFactory
sessionFactory = metadata.getSessionFactoryBuilder().build();
} catch (Exception e) {
e.printStackTrace();
if (registry != null) {
StandardServiceRegistryBuilder.destroy(registry);
}
}
}
return sessionFactory;
}
public static void shutdown() {
if (registry != null) {
StandardServiceRegistryBuilder.destroy(registry);
}
}
}
Persistence data class:
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
//#Data
#Entity
#Table(name = "vocabulary")
public class Vocabulary {
#Id
#Column(name = "V_ID")
private int vocabID;
#Column(name = "V_WORD")
private String word;
#Column(name = "V_CLASS")
private String vocabClass;
#Column(name = "V_DEFINITION")
private String vocabDefinition;
#Column(name = "U_ID")
private int unitID;
public int getVocabID() {
return vocabID;
}
public void setVocabID(int vocabID) {
this.vocabID = vocabID;
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public String getVocabClass() {
return vocabClass;
}
public void setVocabClass(String vocabClass) {
this.vocabClass = vocabClass;
}
public String getVocabDefinition() {
return vocabDefinition;
}
public void setVocabDefinition(String vocabDefinition) {
this.vocabDefinition = vocabDefinition;
}
public int getUnitID() {
return unitID;
}
public void setUnitID(int unitID) {
this.unitID = unitID;
}
}
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>ProjectDBTest2</groupId>
<artifactId>ProjectDBTest2.0</artifactId>
<version>1.0-SNAPSHOT</version>
<name>ProjectDBTest2.0</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/net.bytebuddy/byte-buddy -->
<dependency>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.3.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok-->
<!--
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
<scope>provided</scope>
</dependency> -->
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.3.0.Final</version>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-graphics</artifactId>
<version>13-ea+9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.openjfx/javafx -->
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx</artifactId>
<version>13-ea+9</version>
<type>pom</type>
</dependency>
<!-- https://mvnrepository.com/artifact/org.openjfx/javafx-base -->
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-base</artifactId>
<version>13-ea+9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.openjfx/javafx-controls -->
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
<version>13-ea+9</version>
</dependency>
</dependencies>
<build>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
<!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
<plugin>
<artifactId>maven-site-plugin</artifactId>
<version>3.7.1</version>
</plugin>
<plugin>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>3.0.0</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
I'm using intelliJ ultimate 2019.1 and language level is set to 11.
I finally managed to solve the issue by updating my module-info.java file to include:
module AlienDB {
requires static lombok;
requires java.persistence;
requires org.hibernate.orm.core;
requires java.naming;
requires java.sql;
requires com.sun.xml.bind;
requires net.bytebuddy;
opens Aliens to org.hibernate.orm.core;
exports Aliens;
}
Previously I was adding java.xml.bind which was causing further issues.

Spring Boot - "Error creating bean with name 'entityManagerFactory'" - Start

I have seen a lot of questions but the answers are not satisfying my problem...
I start with Spring Boot and I am completely lost.
The error is :
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: No identifier specified for entity: pack.datas.entities.Degree
/// others lines
Caused by: org.hibernate.AnnotationException: No identifier specified for entity: pack.datas.entities.Degree
The entry point :
package pack;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
#RestController
#EntityScan
public class CandidatesRecruitmentApplication {
public static void main(String[] args) {
SpringApplication.run(CandidatesRecruitmentApplication.class, args);
}
}
The classes :
package pack.datas;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.hibernate.jpa.boot.spi.EntityManagerFactoryBuilder;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.stereotype.Component;
#Component
#Configuration
#EnableJpaRepositories
public class DatasFactory {
private DataSource dataSource;
public DatasFactory() {
super();
}
#Bean
#ConfigurationProperties(prefix="spring.datasource")
public DataSource dataSource() {
if(this.dataSource == null)
return this.dataSource = DataSourceBuilder.create().build();
else
return this.dataSource;
}
package pack.datas.entities;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Table;
import org.springframework.data.annotation.Id;
#Entity
#Table(name = "degree")
public class Degree implements Serializable {
private static final long serialVersionUID = -8900492704842756948L;
#Id
#GeneratedValue
#Column(name = "pk_id")
private Integer id;
#Column(name = "degree_i")
private Integer degreeId;
#Column(name = "degree_s_en")
private String degreeEn;
#Column(name = "degree_s_fr")
private String degreeFr;
protected Degree() {
}
public Degree(Integer id, Integer degreeId, String degreeEn, String degreeFr) {
super();
this.id = id;
this.degreeId = degreeId;
this.degreeEn = degreeEn;
this.degreeFr = degreeFr;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getDegreeId() {
return degreeId;
}
public void setDegreeId(Integer degreeId) {
this.degreeId = degreeId;
}
public String getDegreeEn() {
return degreeEn;
}
public void setDegreeEn(String degreeEn) {
this.degreeEn = degreeEn;
}
public String getDegreeFr() {
return degreeFr;
}
public void setDegreeFr(String degreeFr) {
this.degreeFr = degreeFr;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((degreeEn == null) ? 0 : degreeEn.hashCode());
result = prime * result + ((degreeFr == null) ? 0 : degreeFr.hashCode());
result = prime * result + ((degreeId == null) ? 0 : degreeId.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Degree other = (Degree) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (degreeEn == null) {
if (other.degreeEn != null)
return false;
} else if (!degreeEn.equals(other.degreeEn))
return false;
if (degreeFr == null) {
if (other.degreeFr != null)
return false;
} else if (!degreeFr.equals(other.degreeFr))
return false;
if (degreeId == null) {
if (other.degreeId != null)
return false;
} else if (!degreeId.equals(other.degreeId))
return false;
return true;
}
#Override
public String toString() {
return "Degree [ " + degreeId + " - " + degreeEn + "/" + degreeFr + " ]";
}
}
package pack.datas.controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
#Controller
public class DaoController {
#GetMapping("/")
#ResponseBody
#Transactional(readOnly = true)
String home() {
return "<h1>Test Program</h1>";
}
}
The 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>pack</groupId>
<artifactId>candidates-recruitment</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>candidates-recruitment</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.2.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>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.maven.surefire/surefire-api -->
<dependency>
<groupId>org.apache.maven.surefire</groupId>
<artifactId>surefire-api</artifactId>
<version>2.19.1</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Camden.SR3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/libs-release</url>
</repository>
<repository>
<id>org.jboss.repository.releases</id>
<name>JBoss Maven Release Repository</name>
<url>https://repository.jboss.org/nexus/content/repositories/releases</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
</project>
The application.yml :
# DATASOURCE (DataSourceProperties)
spring:
datasource:
url: jdbc:postgresql://localhost:5432/recruitments_db
username: postgresql
password: postgresql
driver-class-name: org.postgresql.Driver
# HIBERNATE (HibernateProperties)
hibernate:
dialect: org.hibernate.dialect.PostgreSQLDialect
show_sql: true
hbm2ddl.auto: create
#SECURITY (SecuriyProperties)
security:
user:
name: TestU
password: Test1
Please, I need your help !
Seems like you used #Id annotation from the wrong package in your Degree class. Change your import from org.springframework.data.annotation.Id to javax.persistence.Id. That should help with the exception you're getting.
use
javax.persistence.Id
instead of
org.springframework.data.annotation.Id
will solve the problem
I encountered the same problem today.After some debugging,got to know that I annotated one of the fields in my model class with #GeneratedValue(strategy = GenerationType.AUTO) but didn't add the #Id annotation to that field.Adding one resolved it.
Hibernate jar was corrupted in local repository of maven,it was taking corrupted library every time, after deleting local maven repository issue resolved
C:\Users\user.m2\repository
This error might be related to wrong database configuration in your project.
In your application.yml or application.properties file, you would be given wrong db name in "spring.datasource.url" .
A bit late to the party but I ran into the same problem and this is what fixed it:
diff --git a/pom.xml b/pom.xml
index 3a65505..96e5640 100644
--- a/pom.xml
+++ b/pom.xml
## -19,7 +19,7 ##
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
- <version>2.0.6.RELEASE</version>
+ <version>2.3.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
Encountered the same problem after importing my project to IntelliJ IDE. Turned out it was easier than I thought I went to pom.xml and right-clicked on "+ Add as a Maven project". This solved the problem.

Connect to PostgreSQL from SpringBootApplication

I am building a simple Spring application from the scratch using Maven and PostgreSQL.
I've been following thousand of tutorials but it isn't clear for me where to store the different configurations to connect and work with a PostgreSQL database.
My pom.xml file:
<?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>org.springframework</groupId>
<artifactId>gs-rest-service</artifactId>
<version>0.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.2.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.4-1201-jdbc4</version>
</dependency>
</dependencies>
<properties>
<java.version>1.8</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
</project>
My src/main/java/quotes/Application.java file:
package quotes;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
My src/main/java/quotes/Quote.java file:
package quotes;
public class Quote {
private String content;
private String author;
public Quote(String content, String author) {
this.content = content;
this.author = author;
}
public String getContent() {
return this.content;
}
public Quote setContent(String content) {
this.content = content;
return this;
}
public String getAuthor() {
return this.author;
}
public Quote setAuthor(String author) {
this.author = author;
return this;
}
}
And my src/main/java/quotes/QuoteController.java file:
package quotes;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.CrossOrigin;
#Controller
public class QuoteController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
#CrossOrigin(origins = "*")
#RequestMapping("/random")
public #ResponseBody Quote randomQuote() {
return new Quote("¿A dónde vas? Patatas traigo", "Ortega y Pacheco");
}
}
I can build and run the application with Maven:
mvn clean package
java -jar target/*.jar
The idea now is to modify the code on QuoteController.java to connect to PostgreSQL and return a random stored quote.
Could you please give some advices / clues?
You should try this tutorial .
http://devcrumb.com/hibernate/spring-data-jpa-hibernate-maven
You need to add an application.properties file under src/main/resources
It should look like this for PostgreSQL:
spring.jpa.database=POSTGRESQL
spring.datasource.platform=postgres
spring.database.driverClassName=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/your-db-name
spring.datasource.username=username
spring.datasource.password=password
Checkout this link for more info:
enter link description here

Using Java ServiceLoader results NoSuchElementException error

My class DoFindMiddleService extends the abstract class DoFindMiddle.
Here is the DoFindMiddle class:
public abstract class DoFindMiddle<T extends Comparable<T>> {
public abstract ListItem<T> findMiddle(ListItem<T> paramListItem);
public static <D extends Comparable<D>> DoFindMiddle<D> newInstance() {
return (DoFindMiddle)ServiceLoader.load(DoFindMiddle.class).iterator().next();
}
}
Here is the first part of DoFindMiddleService class:
package com.nng.interview.homework.applicant.kovacskalman;
import com.nng.interview.homework.exercise.DoFindMiddle;
import java.util.Iterator;
import java.util.ServiceConfigurationError;
import java.util.ServiceLoader;
public class DoFindMiddleService<T extends Comparable<T>> extends DoFindMiddle<T> {
public static DoFindMiddle service;
public volatile ServiceLoader<DoFindMiddleService> loader;
public DoFindMiddleService() {
loader = ServiceLoader.load(DoFindMiddleService.class);
}
public static synchronized DoFindMiddle getInstance() {
if (service == null) {
service = new DoFindMiddleService();
}
return service;
}
public String getDefinition(String word) {
String definition = null;
try {
Iterator<DoFindMiddleService> dictionaries = loader.iterator();
while (definition == null && dictionaries.hasNext()) {
DoFindMiddleService d = dictionaries.next();
definition = d.getDefinition(word);
}
} catch (ServiceConfigurationError serviceError) {
definition = null;
serviceError.printStackTrace();
}
return definition;
}
.....
}
If I try the following in the Unit test:
final DoFindMiddle<Integer> instance = new DoFindMiddleService();
Then it is working. But when I try in the Unit test:
final DoFindMiddle<Integer> instance = DoFindMiddle.newInstance();
Then it results NoSuchElementException error.
What can be my fault?
My pom.xml is the following:
<?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.nng.interview.homework.applicant</groupId>
<name>Kovács Kálmán</name>
<artifactId>kovacskalman</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<archive>
<manifest>
<addClasspath>true</addClasspath>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.nng.interview.homework</groupId>
<artifactId>comnnginterviewhomework</artifactId>
<version>1.0.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
</project>
When I try to execute I got this error:
d:\kovacskalman>mvn exec:java -Dexec.mainClass="com.nng.interview.homework.appli
cant.kovacskalman.App"
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Kovacs Kalman 1.0
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- exec-maven-plugin:1.3.2:java (default-cli) # kovacskalman ---
[WARNING] Warning: killAfter is now deprecated. Do you need it ? Please comment
on MEXEC-6.
[WARNING]
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.
java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
sorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.codehaus.mojo.exec.ExecJavaMojo$1.run(ExecJavaMojo.java:293)
at java.lang.Thread.run(Thread.java:744)
Caused by: java.util.NoSuchElementException
at java.util.ServiceLoader$LazyIterator.next(ServiceLoader.java:357)
at java.util.ServiceLoader$1.next(ServiceLoader.java:445)
at com.nng.interview.homework.exercise.DoFindMiddle.newInstance(DoFindMi
ddle.java:52)
at com.nng.interview.homework.applicant.kovacskalman.App.<init>(App.java
:9)
at com.nng.interview.homework.applicant.kovacskalman.App.main(App.java:1
3)
... 6 more
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.076 s
[INFO] Finished at: 2014-11-01T15:19:51+01:00
[INFO] Final Memory: 9M/96M
I have to put inside the jar META-INF/services/com.nng.interview.homework.exercise.DoFindMiddle
named file, which contains only one row:
com.nng.interview.homework.applicant.kovacskalman.DoFindMiddleService # Standard service provider
Let see the Jar file specification Service Provider part:
https://docs.oracle.com/javase/7/docs/technotes/guides/jar/jar.html#Service_Provider
According to the javadoc, iterator() does that :
 Lazily loads the available providers of this loader's service.
According to your exception, the iterator is empty, that means no implementation has been found.
Is DoFindMiddleService in your classpath ?

Categories

Resources