JPA repository .save in Netty server channelInitializer handler not working - java

I have initialized the socket channel in the Netty server but I have faced an issue with the handler, when I want to save the received data from the client to MySQL through JPA it can not be saved.
package com.servernetty.server;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class ServerApplication {
public static void main(String[] args) throws InterruptedException {
SpringApplication.run(ServerApplication.class, args);
}
}
#Service
public class ServerService {
private static final Logger logger = LoggerFactory.getLogger(ServerService.class);
private final TestRepo testRepo;
#Autowired
public ServerService(#Value("${hs.host}") String host, #Value("${hs.port}") int port, TestRepo testRepo) throws Exception {
this.testRepo = testRepo;
EventLoopGroup booGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap().
group(booGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.DEBUG))
.handler(new LoggingHandler(LogLevel.INFO))
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true)
.localAddress("127.0.0.1", port).childHandler(new ChannelInitializer<SocketChannel>() {
#Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new NettyServerHandler());
}
});
logger.info("You are here in message server port no: " + port);
ChannelFuture channel = bootstrap.bind(port).sync().channel().closeFuture().sync();
} finally {
logger.info("finallllllll: " + port);
booGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
private final TestRepo testrepo;
public NettyServerHandler(TestRepo testrepo) {
this.testrepo = testrepo;
}
/**
* The message sent by the client will trigger
*/
#Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
TestModel trans = new TestModel();
trans.setId(11);
trans.setTestf("d11");
trans.setTransactionType("test");
log.info("before save");
try {
testrepo.save(trans);
} catch (Exception e) {
log.info("tttttttttttttt" + e.toString());
e.printStackTrace();
}
log.info("after save");
}
}
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
#Entity
#Table(name = "test", uniqueConstraints = #UniqueConstraint(columnNames = { "id" }, name = "TEST_UNIQUE_ID"))
public class TestModel {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", columnDefinition = "bigint unsigned")
private Integer id;
String testf;
#Column(name = "transaction_type")
String transactionType;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTestf() {
return testf;
}
public void setTestf(String testf) {
this.testf = testf;
}
public String getTransactionType() {
return transactionType;
}
public void setTransactionType(String transactionType) {
this.transactionType = transactionType;
}
}
import javax.transaction.Transactional;
import com.servernetty.server.model.TestModel;
import org.springframework.data.jpa.repository.JpaRepository;
public interface TestRepo extends JpaRepository<TestModel, Integer> {
}
The folder structure
The exception that I receive
java.lang.NullPointerException
at com.servernetty.server.handlers.NettyServerHandler.channelRead(NettyServerHandler.java:105)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357)
at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1410)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)
at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:919)
at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:166)
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:719)
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:655)
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:581)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:493)
at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:986)
at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
at java.base/java.lang.Thread.run(Thread.java:829)
In logger I receive the "before save" but nothing after that, the application stacks.
Appreciate your help

I took your code and removed all (new) and all (Constructors). It is best to let Springboot Autowire everything for you:
Pay attention to how ServerService and NettyServerHandler are implemented.
package com.example.socketchannel;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class SocketchannelApplication {
public static void main(String[] args) {
SpringApplication.run(SocketchannelApplication.class, args);
}
}
package com.example.socketchannel.controller;
import com.example.socketchannel.service.NettyServerHandler;
import com.example.socketchannel.service.ServerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class ServerController {
private static final Logger logger = LoggerFactory.getLogger(NettyServerHandler.class);
#Autowired
private ServerService serverService;
}
package com.example.socketchannel.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.*;
import io.netty.channel.socket.*;
import io.netty.channel.socket.nio.*;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
#Service
public class ServerService {
private static final Logger logger = LoggerFactory.getLogger(ServerService.class);
//You need to add hs.host to your properties
#Value("${hs.host:127:0.0.1}")
private String host;
//You need to add hs.port to your properties.
#Value("${hs.port:9090}")
private Integer port;
#Autowired
private NettyServerHandler nettyServerHandler;
#PostConstruct
private void init() {
EventLoopGroup booGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap().
group(booGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.DEBUG))
.handler(new LoggingHandler(LogLevel.INFO))
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true)
.localAddress("127.0.0.1", port).childHandler(new ChannelInitializer<SocketChannel>() {
#Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(nettyServerHandler);
}
});
logger.info("You are here in message server port no {}", port);
ChannelFuture channel = bootstrap.bind(port).sync().channel().closeFuture().sync();
} catch (InterruptedException e) {
logger.error("Encounterd Exception", e);
} finally {
logger.info("finallllllll: {} ", port);
booGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
package com.example.socketchannel.service;
import com.example.socketchannel.model.TestModel;
import com.example.socketchannel.repository.TestRepo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
#Service
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
private static final Logger logger = LoggerFactory.getLogger(NettyServerHandler.class);
#Autowired
private TestRepo testRepo;
/**
* The message sent by the client will trigger
*/
#Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
TestModel trans = new TestModel();
trans.setId(11);
trans.setTestf("d11");
trans.setTransactionType("test");
logger.info("before save");
try {
testRepo.save(trans);
} catch (Exception e) {
logger.info("tttttttttttttt" + e.toString());
e.printStackTrace();
}
logger.info("after save");
}
}
package com.example.socketchannel.repository;
import com.example.socketchannel.model.TestModel;
import org.springframework.data.jpa.repository.JpaRepository;
public interface TestRepo extends JpaRepository<TestModel, Integer> {
}
package com.example.socketchannel.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
#Entity
#Table(name = "test", uniqueConstraints = #UniqueConstraint(columnNames = { "id" }, name = "TEST_UNIQUE_ID"))
public class TestModel {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", columnDefinition = "bigint unsigned")
private Integer id;
String testf;
#Column(name = "transaction_type")
String transactionType;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTestf() {
return testf;
}
public void setTestf(String testf) {
this.testf = testf;
}
public String getTransactionType() {
return transactionType;
}
public void setTransactionType(String transactionType) {
this.transactionType = transactionType;
}
}
<?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.5.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>socketchannel</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>socketchannel</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</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>io.grpc</groupId>
<artifactId>grpc-netty</artifactId>
<version>1.41.0</version>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>5.0.0.Alpha2</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</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>
</plugin>
</plugins>
</build>
</project>
Validating that the springboot context runs, if you do mvn clean install
package com.example.socketchannel;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
#SpringBootTest
class SocketchannelApplicationTests {
#Test
void contextLoads() {
}
}
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building socketchannel 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
Downloading: https://arm.lmera.ericsson.se/artifactory/proj-cv-dev-local/io/grpc/grpc-core/maven-metadata.xml
Downloading: https://arm.lmera.ericsson.se/artifactory/proj-cv-dev/io/grpc/grpc-core/maven-metadata.xml
Downloaded: https://arm.lmera.ericsson.se/artifactory/proj-cv-dev/io/grpc/grpc-core/maven-metadata.xml (0 B at 0.0 KB/sec)
Downloading: https://arm.lmera.ericsson.se/artifactory/proj-cv-dev-local/io/grpc/grpc-api/maven-metadata.xml
Downloading: https://arm.lmera.ericsson.se/artifactory/proj-cv-dev/io/grpc/grpc-api/maven-metadata.xml
Downloaded: https://arm.lmera.ericsson.se/artifactory/proj-cv-dev/io/grpc/grpc-api/maven-metadata.xml (2 KB at 10.5 KB/sec)
[INFO]
[INFO] --- maven-resources-plugin:3.2.0:resources (default-resources) # socketchannel ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Using 'UTF-8' encoding to copy filtered properties files.
[INFO] Copying 1 resource
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) # socketchannel ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 6 source files to C:\UCA-Development\cvc-clones\services\socketchannel\target\classes
[INFO]
[INFO] --- maven-resources-plugin:3.2.0:testResources (default-testResources) # socketchannel ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Using 'UTF-8' encoding to copy filtered properties files.
[INFO] skip non existing resourceDirectory C:\UCA-Development\cvc-clones\services\socketchannel\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) # socketchannel ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to C:\UCA-Development\cvc-clones\services\socketchannel\target\test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.22.2:test (default-test) # socketchannel ---
[INFO]
[INFO] -------------------------------------------------------
[INFO] T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.example.socketchannel.SocketchannelApplicationTests
14:01:36.120 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
14:01:36.140 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]
14:01:36.228 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [com.example.socketchannel.SocketchannelApplicationTests] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper]
14:01:36.251 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither #ContextConfiguration nor #ContextHierarchy found for test class [com.example.socketchannel.SocketchannelApplicationTests], using SpringBootContextLoader
14:01:36.260 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.example.socketchannel.SocketchannelApplicationTests]: class path resource [com/example/socketchannel/SocketchannelApplicationTests-context.xml] does not exist
14:01:36.261 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.example.socketchannel.SocketchannelApplicationTests]: class path resource [com/example/socketchannel/SocketchannelApplicationTestsContext.groovy] does not exist
14:01:36.261 [main] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [com.example.socketchannel.SocketchannelApplicationTests]: no resource found for suffixes {-context.xml, Context.groovy}.
14:01:36.262 [main] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils - Could not detect default configuration classes for test class [com.example.socketchannel.SocketchannelApplicationTests]: SocketchannelApplicationTests does not declare any static, non-private, non-final, nested classes annotated with #Configuration.
14:01:36.351 [main] DEBUG org.springframework.test.context.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [com.example.socketchannel.SocketchannelApplicationTests]
14:01:36.542 [main] DEBUG org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider - Identified candidate component class: file [C:\UCA-Development\cvc-clones\services\socketchannel\target\classes\com\example\socketchannel\SocketchannelApplication.class]
14:01:36.544 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Found #SpringBootConfiguration com.example.socketchannel.SocketchannelApplication for test class com.example.socketchannel.SocketchannelApplicationTests
14:01:36.788 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - #TestExecutionListeners is not present for class [com.example.socketchannel.SocketchannelApplicationTests]: using defaults.
14:01:36.788 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.boot.test.autoconfigure.webservices.client.MockWebServiceServerTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.event.ApplicationEventsTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener, org.springframework.test.context.event.EventPublishingTestExecutionListener]
14:01:36.823 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener#38f116f6, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener#5286c33a, org.springframework.test.context.event.ApplicationEventsTestExecutionListener#6e6d5d29, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener#5c530d1e, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener#6c25e6c4, org.springframework.test.context.support.DirtiesContextTestExecutionListener#85e6769, org.springframework.test.context.transaction.TransactionalTestExecutionListener#c5ee75e, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener#48a12036, org.springframework.test.context.event.EventPublishingTestExecutionListener#bf1ec20, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener#70efb718, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener#b70da4c, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener#4a11eb84, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener#4e858e0a, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener#435fb7b5, org.springframework.boot.test.autoconfigure.webservices.client.MockWebServiceServerTestExecutionListener#4e70a728]
14:01:36.829 [main] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - Before test class: context [DefaultTestContext#3f07b12c testClass = SocketchannelApplicationTests, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration#4bd1f8dd testClass = SocketchannelApplicationTests, locations = '{}', classes = '{class com.example.socketchannel.SocketchannelApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer#4bbf6d0e, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer#2415fc55, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer#0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer#5e21e98f, org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer#7b993c65, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer#0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer#6692b6c6, org.springframework.boot.test.context.SpringBootTestArgs#1, org.springframework.boot.test.context.SpringBootTestWebEnvironment#192d43ce], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> true]], class annotated with #DirtiesContext [false] with mode [null].
14:01:36.903 [main] DEBUG org.springframework.test.context.support.TestPropertySourceUtils - Adding inlined properties to environment: {spring.jmx.enabled=false, org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.5.6)
2021-10-31 14:01:38.142 INFO 6128 --- [ main] c.e.s.SocketchannelApplicationTests : Starting SocketchannelApplicationTests using Java 11.0.7 on SE-00018098 with PID 6128 (started by ezsusmu in C:\UCA-Development\cvc-clones\services\socketchannel)
2021-10-31 14:01:38.150 INFO 6128 --- [ main] c.e.s.SocketchannelApplicationTests : No active profile set, falling back to default profiles: default
2021-10-31 14:01:41.285 INFO 6128 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2021-10-31 14:01:41.439 INFO 6128 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 135 ms. Found 1 JPA repository interfaces.
2021-10-31 14:01:46.495 INFO 6128 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2021-10-31 14:01:47.188 INFO 6128 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2021-10-31 14:01:47.567 INFO 6128 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2021-10-31 14:01:47.852 INFO 6128 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.32.Final
2021-10-31 14:01:48.528 INFO 6128 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2021-10-31 14:01:49.292 INFO 6128 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2021-10-31 14:01:51.596 INFO 6128 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2021-10-31 14:01:51.617 INFO 6128 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2021-10-31 14:01:53.868 INFO 6128 --- [ main] c.e.socketchannel.service.ServerService : You are here in message server port no 9090
2021-10-31 14:01:57.647 INFO 6128 --- [ntLoopGroup-2-1] io.netty.handler.logging.LoggingHandler : [id: 0x23fb4903] REGISTERED
2021-10-31 14:01:57.651 INFO 6128 --- [ntLoopGroup-2-1] io.netty.handler.logging.LoggingHandler : [id: 0x23fb4903] BIND: 0.0.0.0/0.0.0.0:9090
2021-10-31 14:01:57.655 INFO 6128 --- [ntLoopGroup-2-1] io.netty.handler.logging.LoggingHandler : [id: 0x23fb4903, L:/0:0:0:0:0:0:0:0:9090] ACTIVE

try to use spring-boot-starter-jdbc, you will not face the issue.

Related

Controller Method is not getting triggered

I have recently started exploring Spring boot. I am following https://www.bezkoder.com/spring-boot-jdbctemplate-postgresql-example/ documentation.
I have created all files as instructed in the documentation.
Here goes my code:
******AppApplication.java
`package com.triveni.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
public class AppApplication {
public static void main(String[] args) {
SpringApplication.run(AppApplication.class, args);
}
}`
***** IProductRepository *****
`package com.triveni.repository;
import com.triveni.models.ProductModel;
import java.util.List;
public interface IProductRepository {
int create(ProductModel productModel);
int update (ProductModel productModel);
ProductModel findById(int id);
List<ProductModel> findAll();
List<ProductModel> findByActive(boolean active);
}`
***** ProductModel.java *****
package com.triveni.models;
public class ProductModel {
private int productId;
private String productName;
private int cost;
private Boolean active;
private int descriptionId;
public ProductModel(int productId, String productName, int cost, Boolean active, int descriptionId){
this.productId = productId;
this.productName = productName;
this.cost = cost;
this.active = active;
this.descriptionId = descriptionId;
}
public void setProductId(int productId){
this.productId = productId;
}
public long getProductId(){
return productId;
}
public void setProductName(String productName){
this.productName = productName;
}
public String getProductName(){
return productName;
}
public void setCost(int cost) {
this.cost = cost;
}
public int getCost() {
return cost;
}
public void setActive(Boolean active) {
this.active = active;
}
public Boolean getActive() {
return active;
}
public void setDescriptionId(int descriptionId) {
this.descriptionId = descriptionId;
}
public int getDescriptionId() {
return descriptionId;
}
}
*** Product Repository *****
package com.triveni.data;
import com.triveni.models.ProductModel;
import com.triveni.repository.IProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
public class ProductRepository implements IProductRepository {
#Autowired
private JdbcTemplate jdbcTemplate;
#Override
public int create(ProductModel productModel) {
return jdbcTemplate.update("INSERT INTO public.product(\n" +
"\t\"productId\", \"productName\", cost, \"DescriptionId\", active)\n" +
"\tVALUES (?, ?, ?, ?, ?);",new Object[]{productModel.getProductId(),productModel.getProductName(),
productModel.getCost(), productModel.getDescriptionId(),productModel.getActive()});
}
#Override
public int update(ProductModel productModel) {
return 0;
}
#Override
public ProductModel findById(int id) {
return null;
}
#Override
public List<ProductModel> findAll() {
return jdbcTemplate.query("SELECT \"productId\", \"productName\", cost, \"DescriptionId\", active\n" +
"\tFROM public.product",BeanPropertyRowMapper.newInstance(ProductModel.class));
}
#Override
public List<ProductModel> findByActive(boolean active) {
return null;
}
}
***** ProductController.java *****
package com.triveni.controllers;
import java.util.ArrayList;
import java.util.List;
import com.triveni.data.ProductRepository;
import com.triveni.models.ProductModel;
import com.triveni.repository.IProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
#RestController
#RequestMapping("/api/v1")
public class ProductController {
#Autowired
ProductRepository productRepository;
#GetMapping("/product")
public ResponseEntity<List<ProductModel>> getAllProducts(){
try{
List<ProductModel> products = new ArrayList<ProductModel>();
productRepository.findAll().forEach(products::add);;
return new ResponseEntity<>(products, HttpStatus.OK);
}catch (Exception e){
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
My Project Folder Structure
I am getting following error
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Tue Dec 27 13:51:39 IST 2022
There was an unexpected error (type=Not Found, status=404).
Any help will be highly appreciated.
*Output
/Users/chhayatiwari/Library/Java/JavaVirtualMachines/openjdk-19.0.1/Contents/Home/bin/java -javaagent:/Applications/IntelliJ IDEA CE.app/Contents/lib/idea_rt.jar=51857:/Applications/IntelliJ IDEA CE.app/Contents/bin -Dfile.encoding=UTF-8 -Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8 -classpath /Users/chhayatiwari/Desktop/Work/TriveniApp-Service/app/target/classes:/Users/chhayatiwari/.m2/repository/org/springframework/boot/spring-boot-starter-web/3.0.1/spring-boot-starter-web-3.0.1.jar:/Users/chhayatiwari/.m2/repository/org/springframework/boot/spring-boot-starter/3.0.1/spring-boot-starter-3.0.1.jar:/Users/chhayatiwari/.m2/repository/org/springframework/boot/spring-boot/3.0.1/spring-boot-3.0.1.jar:/Users/chhayatiwari/.m2/repository/org/springframework/boot/spring-boot-autoconfigure/3.0.1/spring-boot-autoconfigure-3.0.1.jar:/Users/chhayatiwari/.m2/repository/org/springframework/boot/spring-boot-starter-logging/3.0.1/spring-boot-starter-logging-3.0.1.jar:/Users/chhayatiwari/.m2/repository/ch/qos/logback/logback-classic/1.4.5/logback-classic-1.4.5.jar:/Users/chhayatiwari/.m2/repository/ch/qos/logback/logback-core/1.4.5/logback-core-1.4.5.jar:/Users/chhayatiwari/.m2/repository/org/apache/logging/log4j/log4j-to-slf4j/2.19.0/log4j-to-slf4j-2.19.0.jar:/Users/chhayatiwari/.m2/repository/org/apache/logging/log4j/log4j-api/2.19.0/log4j-api-2.19.0.jar:/Users/chhayatiwari/.m2/repository/org/slf4j/jul-to-slf4j/2.0.6/jul-to-slf4j-2.0.6.jar:/Users/chhayatiwari/.m2/repository/jakarta/annotation/jakarta.annotation-api/2.1.1/jakarta.annotation-api-2.1.1.jar:/Users/chhayatiwari/.m2/repository/org/yaml/snakeyaml/1.33/snakeyaml-1.33.jar:/Users/chhayatiwari/.m2/repository/org/springframework/boot/spring-boot-starter-json/3.0.1/spring-boot-starter-json-3.0.1.jar:/Users/chhayatiwari/.m2/repository/com/fasterxml/jackson/core/jackson-databind/2.14.1/jackson-databind-2.14.1.jar:/Users/chhayatiwari/.m2/repository/com/fasterxml/jackson/core/jackson-annotations/2.14.1/jackson-annotations-2.14.1.jar:/Users/chhayatiwari/.m2/repository/com/fasterxml/jackson/core/jackson-core/2.14.1/jackson-core-2.14.1.jar:/Users/chhayatiwari/.m2/repository/com/fasterxml/jackson/datatype/jackson-datatype-jdk8/2.14.1/jackson-datatype-jdk8-2.14.1.jar:/Users/chhayatiwari/.m2/repository/com/fasterxml/jackson/datatype/jackson-datatype-jsr310/2.14.1/jackson-datatype-jsr310-2.14.1.jar:/Users/chhayatiwari/.m2/repository/com/fasterxml/jackson/module/jackson-module-parameter-names/2.14.1/jackson-module-parameter-names-2.14.1.jar:/Users/chhayatiwari/.m2/repository/org/springframework/boot/spring-boot-starter-tomcat/3.0.1/spring-boot-starter-tomcat-3.0.1.jar:/Users/chhayatiwari/.m2/repository/org/apache/tomcat/embed/tomcat-embed-core/10.1.4/tomcat-embed-core-10.1.4.jar:/Users/chhayatiwari/.m2/repository/org/apache/tomcat/embed/tomcat-embed-el/10.1.4/tomcat-embed-el-10.1.4.jar:/Users/chhayatiwari/.m2/repository/org/apache/tomcat/embed/tomcat-embed-websocket/10.1.4/tomcat-embed-websocket-10.1.4.jar:/Users/chhayatiwari/.m2/repository/org/springframework/spring-web/6.0.3/spring-web-6.0.3.jar:/Users/chhayatiwari/.m2/repository/io/micrometer/micrometer-observation/1.10.2/micrometer-observation-1.10.2.jar:/Users/chhayatiwari/.m2/repository/io/micrometer/micrometer-commons/1.10.2/micrometer-commons-1.10.2.jar:/Users/chhayatiwari/.m2/repository/org/springframework/spring-webmvc/6.0.3/spring-webmvc-6.0.3.jar:/Users/chhayatiwari/.m2/repository/org/springframework/spring-aop/6.0.3/spring-aop-6.0.3.jar:/Users/chhayatiwari/.m2/repository/org/springframework/spring-context/6.0.3/spring-context-6.0.3.jar:/Users/chhayatiwari/.m2/repository/org/springframework/spring-expression/6.0.3/spring-expression-6.0.3.jar:/Users/chhayatiwari/.m2/repository/org/slf4j/slf4j-api/2.0.6/slf4j-api-2.0.6.jar:/Users/chhayatiwari/.m2/repository/org/springframework/spring-core/6.0.3/spring-core-6.0.3.jar:/Users/chhayatiwari/.m2/repository/org/springframework/spring-jcl/6.0.3/spring-jcl-6.0.3.jar:/Users/chhayatiwari/.m2/repository/org/springframework/boot/spring-boot-starter-data-jdbc/3.0.1/spring-boot-starter-data-jdbc-3.0.1.jar:/Users/chhayatiwari/.m2/repository/org/springframework/boot/spring-boot-starter-jdbc/3.0.1/spring-boot-starter-jdbc-3.0.1.jar:/Users/chhayatiwari/.m2/repository/com/zaxxer/HikariCP/5.0.1/HikariCP-5.0.1.jar:/Users/chhayatiwari/.m2/repository/org/springframework/data/spring-data-jdbc/3.0.0/spring-data-jdbc-3.0.0.jar:/Users/chhayatiwari/.m2/repository/org/springframework/data/spring-data-relational/3.0.0/spring-data-relational-3.0.0.jar:/Users/chhayatiwari/.m2/repository/org/springframework/data/spring-data-commons/3.0.0/spring-data-commons-3.0.0.jar:/Users/chhayatiwari/.m2/repository/org/postgresql/postgresql/42.5.1/postgresql-42.5.1.jar:/Users/chhayatiwari/.m2/repository/org/checkerframework/checker-qual/3.5.0/checker-qual-3.5.0.jar:/Users/chhayatiwari/.m2/repository/org/springframework/spring-jdbc/5.3.22/spring-jdbc-5.3.22.jar:/Users/chhayatiwari/.m2/repository/org/springframework/spring-beans/6.0.3/spring-beans-6.0.3.jar:/Users/chhayatiwari/.m2/repository/org/springframework/spring-tx/6.0.3/spring-tx-6.0.3.jar com.triveni.app.AppApplication
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v3.0.1)
2022-12-27T20:17:11.351+05:30 INFO 3695 --- [ main] com.triveni.app.AppApplication : Starting AppApplication using Java 19.0.1 with PID 3695 (/Users/chhayatiwari/Desktop/Work/TriveniApp-Service/app/target/classes started by chhayatiwari in /Users/chhayatiwari/Desktop/Work/TriveniApp-Service/app)
2022-12-27T20:17:11.353+05:30 INFO 3695 --- [ main] com.triveni.app.AppApplication : No active profile set, falling back to 1 default profile: "default"
2022-12-27T20:17:11.664+05:30 INFO 3695 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JDBC repositories in DEFAULT mode.
2022-12-27T20:17:11.671+05:30 INFO 3695 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 4 ms. Found 0 JDBC repository interfaces.
2022-12-27T20:17:11.919+05:30 INFO 3695 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2022-12-27T20:17:11.924+05:30 INFO 3695 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-12-27T20:17:11.925+05:30 INFO 3695 --- [ main] o.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/10.1.4]
2022-12-27T20:17:11.972+05:30 INFO 3695 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-12-27T20:17:11.973+05:30 INFO 3695 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 589 ms
2022-12-27T20:17:12.162+05:30 INFO 3695 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2022-12-27T20:17:12.282+05:30 INFO 3695 --- [ main] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Added connection org.postgresql.jdbc.PgConnection#6680f714
2022-12-27T20:17:12.283+05:30 INFO 3695 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2022-12-27T20:17:12.343+05:30 INFO 3695 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2022-12-27T20:17:12.348+05:30 INFO 3695 --- [ main] com.triveni.app.AppApplication : Started AppApplication in 1.206 seconds (process running for 1.435)
2022-12-27T20:19:18.599+05:30 INFO 3695 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-12-27T20:19:18.599+05:30 INFO 3695 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2022-12-27T20:19:18.604+05:30 INFO 3695 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 5 ms
try to add this to annotation #CrossOrigin("*") after #RestController.
I believe you are just launching the spring application and on launch, this error shows up. In order to test your URL you can type
<YOUR-URL>/app/v1/product
This should return you the Response you are looking for.
Remove ResponseEntity<List> from method and instead return a simple String and check if the method invoked or not. If it works properly then go to the next step and invoke the repository.

Whitelabel error when i try make to make a get from database

I am trying to make a small rest-api in springboot but i always get this errorerror 404
It is connected to a database but when I try to exceute a GET from Post I also have 404 error
This is my structure
project structure
My pom
<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.6.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>Clientix</groupId>
<artifactId>Ruben_DeNicolas</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Clientix</name>
<description>TFG</description>
<properties>
<java.version>1.8</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>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</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>
</plugin>
</plugins>
</build>
</project>
Repository
package repositories;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import models.ClientesModel;
#Repository
public interface ClientesRepository extends CrudRepository<ClientesModel, Integer>{
}
Service
package services;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import models.ClientesModel;
import repositories.ClientesRepository;
#Service
public class ClientesService {
#Autowired
ClientesRepository clientesRepository;
public ArrayList<ClientesModel>getClientes()
{
return(ArrayList<ClientesModel>)clientesRepository.findAll();
}
public ClientesModel insert(ClientesModel c)
{
return clientesRepository.save(c);
}
}
Model
package models;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "clientes")
public class ClientesModel {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(unique = true, nullable = false)
private Integer idCliente;
private String NombreCliente;
private String CIFNIF;
private String DireccionFacturacion;
public ClientesModel(String NombreCliente) {
this.NombreCliente = NombreCliente;
}
public ClientesModel(int idCliente, String NombreCliente, String CIFNIF, String DireccionFacturacion) {
this.idCliente = idCliente;
this.NombreCliente = NombreCliente;
this.CIFNIF = CIFNIF;
this.DireccionFacturacion = DireccionFacturacion;
}
public Integer getIdCliente() {
return idCliente;
}
public void setIdCliente(Integer idCliente) {
this.idCliente = idCliente;
}
public String getNombreCliente() {
return NombreCliente;
}
public void setNombreCliente(String nombreCliente) {
NombreCliente = nombreCliente;
}
public String getCIFNIF() {
return CIFNIF;
}
public void setCIFNIF(String cIFNIF) {
CIFNIF = cIFNIF;
}
public String getDireccionFacturacion() {
return DireccionFacturacion;
}
public void setDireccionFacturacion(String direccionFacturacion) {
DireccionFacturacion = direccionFacturacion;
}
}
Controller
package controllers;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import models.ClientesModel;
import services.ClientesService;
#RestController
#RequestMapping(value = "/clientes",produces="application/json")
public class ClientesController {
#Autowired
ClientesService clientesService;
//OBTENER TODOS LOS CLIENTES
//#RequestMapping(value = "/",method = RequestMethod.GET)
#GetMapping()
public ArrayList<ClientesModel> getClientes()
{
return clientesService.getClientes();
}
//INSTERTAR CLIENTE
#PostMapping
public ClientesModel insert(#RequestBody ClientesModel c)
{
return this.clientesService.insert(c);
}
}
```
Clientix application
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
#ComponentScan()
public class ClientixApplication {
public static void main(String[] args) {
SpringApplication.run(ClientixApplication.class, args);
}
}
This is the SpringBoot log
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.6.6)
2022-04-06 16:05:32.098 INFO 15728 --- [ main] C.Ruben_DeNicolas.ClientixApplication : Starting ClientixApplication using Java 17.0.2 on DESKTOP-0EJNGE1 with PID 15728 (C:\Users\Rubén\Desktop\TestSpringBoot\Ruben_DeNicolas (1)\Ruben_DeNicolas\target\classes started by Rubén in C:\Users\Rubén\Desktop\TestSpringBoot\Ruben_DeNicolas (1)\Ruben_DeNicolas)
2022-04-06 16:05:32.101 INFO 15728 --- [ main] C.Ruben_DeNicolas.ClientixApplication : No active profile set, falling back to 1 default profile: "default"
2022-04-06 16:05:32.373 INFO 15728 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2022-04-06 16:05:32.381 INFO 15728 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 2 ms. Found 0 JPA repository interfaces.
2022-04-06 16:05:32.627 INFO 15728 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2022-04-06 16:05:32.632 INFO 15728 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-04-06 16:05:32.632 INFO 15728 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.60]
2022-04-06 16:05:32.692 INFO 15728 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-04-06 16:05:32.692 INFO 15728 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 569 ms
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
2022-04-06 16:05:32.784 INFO 15728 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2022-04-06 16:05:32.810 INFO 15728 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.6.7.Final
2022-04-06 16:05:32.893 INFO 15728 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2022-04-06 16:05:32.945 INFO 15728 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2022-04-06 16:05:32.948 WARN 15728 --- [ main] com.zaxxer.hikari.util.DriverDataSource : Registered driver with driverClassName=com.mysql.jdbc.Driver was not found, trying direct instantiation.
2022-04-06 16:05:33.018 INFO 15728 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2022-04-06 16:05:33.034 INFO 15728 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL55Dialect
2022-04-06 16:05:33.132 INFO 15728 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2022-04-06 16:05:33.138 INFO 15728 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2022-04-06 16:05:33.156 WARN 15728 --- [ main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2022-04-06 16:05:33.313 INFO 15728 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2022-04-06 16:05:33.319 INFO 15728 --- [ main] C.Ruben_DeNicolas.ClientixApplication : Started ClientixApplication in 1.398 seconds (JVM running for 1.705)
2022-04-06 16:05:36.286 INFO 15728 --- [nio-8080-exec-2] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-04-06 16:05:36.287 INFO 15728 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2022-04-06 16:05:36.287 INFO 15728 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Completed initialization in 0 ms
what is the url your hitting on your browser, make sure not hitting with https...
Code looks okay, try hitting
http://localhost:8080/clientes

Facing issue with JPA Hikari Transaction Mangaement

I am using JPA , HikariPool to add entries in DB .
I am facing issue while saving the transaction .
Here is my main class
package com.vish.jpa_demo;
import com.vish.jpa_demo.config.AppConfig;
import com.vish.jpa_demo.model.Laptop;
import com.vish.jpa_demo.model.Student;
import com.vish.jpa_demo.service.DBService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
#Slf4j
#SpringBootApplication
public class JpaDemoApplication
{
public static void main(String[] args)
{
log.info("Starting Main");
SpringApplication.run(JpaDemoApplication.class, args);
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(JpaDemoApplication.class);
Student s = new Student("Vish");
Laptop laptop = new Laptop("HP");
s.setLaptop(laptop);
DBService dbService =applicationContext.getBean(DBService.class);
try
{
dbService.addLaptop(laptop);
dbService.addStudent(s);
laptop.setBrand("Apple");
dbService.addLaptop(laptop);
}
catch (Exception e)
{
e.printStackTrace();
}
log.info("Exiting Main");
}
}
Here is my AppConfig
package com.vish.jpa_demo.config;
import com.vish.jpa_demo.service.DBService;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
import java.util.Properties;
#EnableTransactionManagement
#Configuration
public class AppConfig
{
#Autowired
private Environment env;
#Bean
public JpaVendorAdapter getJpaVendorAdapter()
{
HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
jpaVendorAdapter.setDatabase(Database.MYSQL);
jpaVendorAdapter.setShowSql(true);
jpaVendorAdapter.setGenerateDdl(false);
jpaVendorAdapter.setDatabasePlatform("org.hibernate.dialect.HSQLDialect");
return jpaVendorAdapter;
}
#Bean
public DataSource getHikariDataSource()
{
final HikariDataSource dataSource = new HikariDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
dataSource.setUsername("XXXXX");
dataSource.setPassword("XXXX");
dataSource.setAutoCommit(false);
//dataSource.setMinEvictableIdleTimeMillis(1000);
//dataSource.setCacheState(false);s
dataSource.setConnectionTimeout(31000);
dataSource.setIdleTimeout(30000);
dataSource.setMaximumPoolSize(2);
dataSource.setMinimumIdle(0);
dataSource.setConnectionTimeout(60000);
return dataSource;
}
#Bean
public LocalContainerEntityManagerFactoryBean getEntityMangerFactory()
{
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(getHikariDataSource());
entityManagerFactoryBean.setJpaVendorAdapter(getJpaVendorAdapter());
entityManagerFactoryBean.setJpaProperties(DBProperties());
entityManagerFactoryBean.setPersistenceUnitName("com.vish.jpa_demo");
entityManagerFactoryBean.setPackagesToScan("com.vish.jpa_demo.model");
return entityManagerFactoryBean;
}
#Bean
public PlatformTransactionManager hibernateTransactionManager()
{
final JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(getEntityMangerFactory().getNativeEntityManagerFactory());
transactionManager.setDataSource(getHikariDataSource());
return transactionManager;
}
private final Properties DBProperties()
{
final Properties hibernateProperties = new Properties();
hibernateProperties.put("javax.persistence.transactionType", "RESOURCE_LOCAL");
hibernateProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
hibernateProperties.setProperty("hibernate.show_sql", "true");
//hibernateProperties.setProperty("hibernate.current_session_context_class","org.springframework.orm.hibernate5.SpringSessionContext");
hibernateProperties.setProperty("hibernate.current_session_context_class","org.hibernate.context.internal.ThreadLocalSessionContext");
return hibernateProperties;
}
}
Here is my DaoImpl Class .
Here I am trying to add one object .
Transaction is already started in Service class and I am using the same in Dao
package com.vish.jpa_demo.dao;
import com.vish.jpa_demo.model.Laptop;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.ScrollMode;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
#Slf4j
#Repository
#Data
public class LaptopDaoImpl implements ILaptopDao
{
private Session session = null;
#Autowired
private EntityManagerFactory entityManagerFactory;
private EntityManager entityManager ;
private void setEntityMangerFactoryCurrentSession()
{
if ( this.session == null )
{
//this.session = this.entityManagerFactory.createEntityManager().unwrap(Session.class).getSessionFactory().openSession();
this.session = this.entityManagerFactory.createEntityManager().unwrap(Session.class).getSessionFactory().getCurrentSession();
}
}
#Override
public void addLaptop(Laptop laptop)
{
log.info("Adding Laptop " + laptop.getBrand());
setEntityMangerFactoryCurrentSession();
this.session.save(laptop);
}
#Override
public Laptop getLaptopDetailsByName(String name)
{
Laptop invalidlaptop = null ;
try
{
setEntityMangerFactoryCurrentSession();
String myQry = "from Laptop where brand = :bname";
Query query = session.createQuery(myQry,Laptop.class);
query.setParameter("bname",name);
query.setFetchSize(1);
ScrollableResults scrollableResults = query.setReadOnly(true).scroll(ScrollMode.FORWARD_ONLY);
while(true)
{
for (;scrollableResults.next(); )
{
List<Object> objectList = Arrays.asList(scrollableResults.get());
Optional<Laptop> laptop = objectList
.stream()
.map(e -> (Laptop) e )
.filter(e2 -> e2.getBrand().equalsIgnoreCase(name))
.findFirst();
return laptop.orElse(invalidlaptop);
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
return invalidlaptop;
}
}
Here is my Service Class
package com.vish.jpa_demo.service;
import com.vish.jpa_demo.dao.ILaptopDao;
import com.vish.jpa_demo.dao.IStudentDao;
import com.vish.jpa_demo.model.Laptop;
import com.vish.jpa_demo.model.Student;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.ScrollMode;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
#Data
#Slf4j
#Component
public class DBService
{
private Session session = null;
#Autowired(required = false )
private SessionFactory sessionFactory;
#Autowired
private IStudentDao studentDao;
#Autowired
private ILaptopDao laptopDao;
#Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
public void addStudent(Student student) throws Exception
{
try
{
studentDao.addStudent(student);
}
catch (Exception e)
{
e.printStackTrace();
}
}
#Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
public void addLaptop(Laptop laptop) throws Exception
{
try
{
laptopDao.addLaptop(laptop);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Actual Error
"C:\Program Files\Java\jdk1.8.0_231\bin\java.exe" -agentlib:jdwp=transport=dt_socket,address=127.0.0.1:57158,suspend=y,server=n -javaagent:C:\Users\VISHBA~1\AppData\Local\Temp\captureAgent251jars\debugger-agent.jar -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.8.0_231\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\rt.jar;F:\Java\VD_program\java_prog\SpringBoot_JPA_Hikari\jpa_demo\target\classes;C:\Users\VIsh bade\.m2\repository\org\springframework\boot\spring-boot-starter-data-jpa\2.4.1\spring-boot-starter-data-jpa-2.4.1.jar;C:\Users\VIsh bade\.m2\repository\org\springframework\boot\spring-boot-starter-aop\2.4.1\spring-boot-starter-aop-2.4.1.jar;C:\Users\VIsh bade\.m2\repository\org\springframework\spring-aop\5.3.2\spring-aop-5.3.2.jar;C:\Users\VIsh bade\.m2\repository\org\aspectj\aspectjweaver\1.9.6\aspectjweaver-1.9.6.jar;C:\Users\VIsh bade\.m2\repository\org\springframework\boot\spring-boot-starter-jdbc\2.4.1\spring-boot-starter-jdbc-2.4.1.jar;C:\Users\VIsh bade\.m2\repository\org\springframework\spring-jdbc\5.3.2\spring-jdbc-5.3.2.jar;C:\Users\VIsh bade\.m2\repository\jakarta\transaction\jakarta.transaction-api\1.3.3\jakarta.transaction-api-1.3.3.jar;C:\Users\VIsh bade\.m2\repository\jakarta\persistence\jakarta.persistence-api\2.2.3\jakarta.persistence-api-2.2.3.jar;C:\Users\VIsh bade\.m2\repository\org\hibernate\hibernate-core\5.4.25.Final\hibernate-core-5.4.25.Final.jar;C:\Users\VIsh bade\.m2\repository\org\jboss\logging\jboss-logging\3.4.1.Final\jboss-logging-3.4.1.Final.jar;C:\Users\VIsh bade\.m2\repository\net\bytebuddy\byte-buddy\1.10.18\byte-buddy-1.10.18.jar;C:\Users\VIsh bade\.m2\repository\antlr\antlr\2.7.7\antlr-2.7.7.jar;C:\Users\VIsh bade\.m2\repository\org\jboss\jandex\2.1.3.Final\jandex-2.1.3.Final.jar;C:\Users\VIsh bade\.m2\repository\com\fasterxml\classmate\1.5.1\classmate-1.5.1.jar;C:\Users\VIsh bade\.m2\repository\org\dom4j\dom4j\2.1.3\dom4j-2.1.3.jar;C:\Users\VIsh bade\.m2\repository\org\hibernate\common\hibernate-commons-annotations\5.1.2.Final\hibernate-commons-annotations-5.1.2.Final.jar;C:\Users\VIsh bade\.m2\repository\org\glassfish\jaxb\jaxb-runtime\2.3.3\jaxb-runtime-2.3.3.jar;C:\Users\VIsh bade\.m2\repository\org\glassfish\jaxb\txw2\2.3.3\txw2-2.3.3.jar;C:\Users\VIsh bade\.m2\repository\com\sun\istack\istack-commons-runtime\3.0.11\istack-commons-runtime-3.0.11.jar;C:\Users\VIsh bade\.m2\repository\com\sun\activation\jakarta.activation\1.2.2\jakarta.activation-1.2.2.jar;C:\Users\VIsh bade\.m2\repository\org\springframework\data\spring-data-jpa\2.4.2\spring-data-jpa-2.4.2.jar;C:\Users\VIsh bade\.m2\repository\org\springframework\data\spring-data-commons\2.4.2\spring-data-commons-2.4.2.jar;C:\Users\VIsh bade\.m2\repository\org\springframework\spring-orm\5.3.2\spring-orm-5.3.2.jar;C:\Users\VIsh bade\.m2\repository\org\springframework\spring-context\5.3.2\spring-context-5.3.2.jar;C:\Users\VIsh bade\.m2\repository\org\springframework\spring-expression\5.3.2\spring-expression-5.3.2.jar;C:\Users\VIsh bade\.m2\repository\org\springframework\spring-tx\5.3.2\spring-tx-5.3.2.jar;C:\Users\VIsh bade\.m2\repository\org\springframework\spring-beans\5.3.2\spring-beans-5.3.2.jar;C:\Users\VIsh bade\.m2\repository\org\springframework\spring-aspects\5.3.2\spring-aspects-5.3.2.jar;C:\Users\VIsh bade\.m2\repository\org\projectlombok\lombok\1.18.16\lombok-1.18.16.jar;C:\Users\VIsh bade\.m2\repository\org\springframework\boot\spring-boot-starter\2.4.1\spring-boot-starter-2.4.1.jar;C:\Users\VIsh bade\.m2\repository\org\springframework\boot\spring-boot\2.4.1\spring-boot-2.4.1.jar;C:\Users\VIsh bade\.m2\repository\org\springframework\boot\spring-boot-autoconfigure\2.4.1\spring-boot-autoconfigure-2.4.1.jar;C:\Users\VIsh bade\.m2\repository\org\springframework\boot\spring-boot-starter-logging\2.4.1\spring-boot-starter-logging-2.4.1.jar;C:\Users\VIsh bade\.m2\repository\ch\qos\logback\logback-classic\1.2.3\logback-classic-1.2.3.jar;C:\Users\VIsh bade\.m2\repository\ch\qos\logback\logback-core\1.2.3\logback-core-1.2.3.jar;C:\Users\VIsh bade\.m2\repository\org\apache\logging\log4j\log4j-to-slf4j\2.13.3\log4j-to-slf4j-2.13.3.jar;C:\Users\VIsh bade\.m2\repository\org\apache\logging\log4j\log4j-api\2.13.3\log4j-api-2.13.3.jar;C:\Users\VIsh bade\.m2\repository\org\slf4j\jul-to-slf4j\1.7.30\jul-to-slf4j-1.7.30.jar;C:\Users\VIsh bade\.m2\repository\jakarta\annotation\jakarta.annotation-api\1.3.5\jakarta.annotation-api-1.3.5.jar;C:\Users\VIsh bade\.m2\repository\org\yaml\snakeyaml\1.27\snakeyaml-1.27.jar;C:\Users\VIsh bade\.m2\repository\jakarta\xml\bind\jakarta.xml.bind-api\2.3.3\jakarta.xml.bind-api-2.3.3.jar;C:\Users\VIsh bade\.m2\repository\jakarta\activation\jakarta.activation-api\1.2.2\jakarta.activation-api-1.2.2.jar;C:\Users\VIsh bade\.m2\repository\org\springframework\spring-core\5.3.2\spring-core-5.3.2.jar;C:\Users\VIsh bade\.m2\repository\org\springframework\spring-jcl\5.3.2\spring-jcl-5.3.2.jar;C:\Users\VIsh bade\.m2\repository\com\zaxxer\HikariCP\2.2.5\HikariCP-2.2.5.jar;C:\Users\VIsh bade\.m2\repository\org\slf4j\slf4j-api\1.7.30\slf4j-api-1.7.30.jar;C:\Users\VIsh bade\.m2\repository\org\javassist\javassist\3.18.1-GA\javassist-3.18.1-GA.jar;C:\Users\VIsh bade\.m2\repository\mysql\mysql-connector-java\8.0.13\mysql-connector-java-8.0.13.jar;C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2019.2.1\lib\idea_rt.jar" com.vish.jpa_demo.JpaDemoApplication
Connected to the target VM, address: '127.0.0.1:57158', transport: 'socket'
08:48:32.958 [main] INFO com.vish.jpa_demo.JpaDemoApplication - Starting Main
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.4.1)
2020-12-17 08:48:33.751 INFO 5184 --- [ main] com.vish.jpa_demo.JpaDemoApplication : Starting JpaDemoApplication using Java 1.8.0_231 on LAPTOP-SDUPSP61 with PID 5184 (F:\Java\VD_program\java_prog\SpringBoot_JPA_Hikari\jpa_demo\target\classes started by VIsh bade in F:\Java\VD_program\java_prog\SpringBoot_JPA_Hikari\jpa_demo)
2020-12-17 08:48:33.753 INFO 5184 --- [ main] com.vish.jpa_demo.JpaDemoApplication : No active profile set, falling back to default profiles: default
2020-12-17 08:48:33.910 INFO 5184 --- [ main] com.vish.jpa_demo.JpaDemoApplication : Started JpaDemoApplication in 0.736 seconds (JVM running for 1.33)
2020-12-17 08:48:34.718 INFO 5184 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: com.vish.jpa_demo]
2020-12-17 08:48:34.826 INFO 5184 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.25.Final
2020-12-17 08:48:35.019 INFO 5184 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2020-12-17 08:48:35.370 INFO 5184 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariCP pool HikariPool-0 is starting.
2020-12-17 08:48:36.133 INFO 5184 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2020-12-17 08:48:36.610 INFO 5184 --- [ main] org.hibernate.tuple.PojoInstantiator : HHH000182: No default (no-argument) constructor for class: com.vish.jpa_demo.model.Laptop (class must be instantiated by Interceptor)
2020-12-17 08:48:36.864 INFO 5184 --- [ main] org.hibernate.tuple.PojoInstantiator : HHH000182: No default (no-argument) constructor for class: com.vish.jpa_demo.model.Student (class must be instantiated by Interceptor)
2020-12-17 08:48:36.992 INFO 5184 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'com.vish.jpa_demo'
2020-12-17 08:48:50.258 INFO 5184 --- [ main] com.vish.jpa_demo.dao.LaptopDaoImpl : Adding Laptop HP
org.hibernate.HibernateException: Calling method 'save' is not valid without an active transaction (Current status: NOT_ACTIVE)
at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:347)
at com.sun.proxy.$Proxy38.save(Unknown Source)
at com.vish.jpa_demo.dao.LaptopDaoImpl.addLaptop(LaptopDaoImpl.java:51)
at com.vish.jpa_demo.service.DBService.addLaptop(DBService.java:61)
at com.vish.jpa_demo.service.DBService$$FastClassBySpringCGLIB$$ffafa2f0.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:771)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:123)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:388)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:691)
at com.vish.jpa_demo.service.DBService$$EnhancerBySpringCGLIB$$5cfb11dd.addLaptop(<generated>)
at com.vish.jpa_demo.JpaDemoApplication.main(JpaDemoApplication.java:37)
Disconnected from the target VM, address: '127.0.0.1:57158', transport: 'socket'
2020-12-17 08:51:03.970 INFO 5184 --- [ main] com.vish.jpa_demo.dao.StudentDaoImpl : Adding Student Vish
org.hibernate.HibernateException: Calling method 'save' is not valid without an active transaction (Current status: NOT_ACTIVE)
at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:347)
at com.sun.proxy.$Proxy38.save(Unknown Source)
at com.vish.jpa_demo.dao.StudentDaoImpl.addStudent(StudentDaoImpl.java:44)
at com.vish.jpa_demo.service.DBService.addStudent(DBService.java:46)
at com.vish.jpa_demo.service.DBService$$FastClassBySpringCGLIB$$ffafa2f0.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:771)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:123)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:388)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:691)
at com.vish.jpa_demo.service.DBService$$EnhancerBySpringCGLIB$$5cfb11dd.addStudent(<generated>)
at com.vish.jpa_demo.JpaDemoApplication.main(JpaDemoApplication.java:38)
2020-12-17 08:51:03.975 INFO 5184 --- [ main] com.vish.jpa_demo.dao.LaptopDaoImpl : Adding Laptop Apple
org.hibernate.HibernateException: Calling method 'save' is not valid without an active transaction (Current status: NOT_ACTIVE)
at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:347)
at com.sun.proxy.$Proxy38.save(Unknown Source)
at com.vish.jpa_demo.dao.LaptopDaoImpl.addLaptop(LaptopDaoImpl.java:51)
at com.vish.jpa_demo.service.DBService.addLaptop(DBService.java:61)
at com.vish.jpa_demo.service.DBService$$FastClassBySpringCGLIB$$ffafa2f0.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:771)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:123)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:388)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:691)
at com.vish.jpa_demo.service.DBService$$EnhancerBySpringCGLIB$$5cfb11dd.addLaptop(<generated>)
at com.vish.jpa_demo.JpaDemoApplication.main(JpaDemoApplication.java:40)
2020-12-17 08:51:03.980 INFO 5184 --- [ main] com.vish.jpa_demo.JpaDemoApplication : Exiting Main
Process finished with exit code 0
Entire code is available at https://github.com/vishy-wisy/Java/tree/main/jpa_demo
Thanks in advance !

Thymeleaf won't recognize variable in HomeController and Java error in creating bean "homeController"

I've been debugging this web app for 2 hours now and I can't figure this out.
After placing the version variable in the application, removing the temp H2 DB and the data.sql file, then adding the driver to the pom.xml file to use the Postgres DB, it stopped working.
I attached all the necessary files but if you need something please comment.
In the application.properties I gave the variable version then used that in the HomeController (line 24) and the corresponding console error says, "could not resolve placeholder 'version'."
In the browser usually, there are error messages that I can dig through, but this time the browser on the localhost simply fails to load, This site can’t be reached, localhost refused to connect.
There are only two "Caused by" errors in the console logs below so I'm sure it is not that difficult to point out the bug.
After lots of research on StackOverflow, looking at other questions, and trial and error, I have run out of possible solutions to try that are applicable to my case. Would really appreciate it if someone would take a look at the attached code and let me know about any solutions. Any help is appreciated! Thank you very much in advance and I will check back.
Here's the file structure if that helps at all
Here's the 2nd part:
The spring.datasource.username=postgres is underlined in yellow in eclipse as well as the version=3.0.0 at the bottom, when I hover over the yellow line it says, "unknown property" on both.
Here is my application.properties file and the screenshot:
spring.datasource.url=jdbc:postgresql://localhost:5432/pma-database
spring.datasource.username=postgres
spring.datasource.password=password321
spring.datasource.initialization-mode=never
spring.jpa.hibernate.ddl-auto=none
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
spring.jpa.show-sql=true
spring.thymeleaf.cache=false
version=3.0.0
Here's the HomeController.java you'll see the #Value("${version}") is here on line 24 or so and the model.addAttribute("versionNumber", ver) is on line 36.
package com.project1.controllers;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.project1.dao.EmployeeRepository;
import com.project1.dao.ProjectRepository;
import com.project1.dto.ChartData;
import com.project1.dto.EmployeeProject;
import com.project1.entities.Project;
#Controller
public class HomeController {
#Value("${version}")
private String ver;
#Autowired
ProjectRepository proRepo;
#Autowired
EmployeeRepository empRepo;
#GetMapping("/")
public String displayHome(Model model) throws JsonProcessingException {
model.addAttribute("versionNumber", ver);
Map<String, Object> map = new HashMap<>();
//we are querying the DB for projects
List<Project> projects = proRepo.findAll();
model.addAttribute("projectsList", projects);
List<ChartData> projectData = proRepo.getProjectStatus();
ObjectMapper objectMapper = new ObjectMapper();
String jsonString = objectMapper.writeValueAsString(projectData);
//[ ["NOTSTARTED, 1], ["INPROGRESS", 2], ["COMPLETED", 1] ]
model.addAttribute("projectStatusCnt", jsonString);
//we are querying the DB for employees
List<EmployeeProject> employeesProjectCnt = empRepo.employeeProjects();
model.addAttribute("employeesListProjectsCnt", employeesProjectCnt);
return "main/home";
}
}
Here's the home.html file which has the versionNumber variable in the tag, which is related to the issue at hand.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<!-- this is the code for the header-->
<head th:replace="layouts::header"></head>
<!-- this is the code for the navbar-->
<nav th:replace="layouts::navbar"></nav>
<body>
<div class="container">
<h3>Main Dashboard</h3>
<a th:text="${versionNumber}"></a>
<hr>
<h4> Current Projects </h4>
<div class="row">
<div class="col-md-6">
<table class="table table-bordered table-striped">
<thead class="thead-dark">
<tr>
<th> Project Name </th>
<th> Project Stage </th>
</tr>
</thead>
<tbody>
<tr th:each="aProject : ${projectsList}">
<td th:text="${aProject.name}"></td>
<td th:text="${aProject.stage}"></td>
</tr>
</tbody>
</table>
</div>
<div class="col-md-4">
<canvas id="myPieChart" height="50" width="50"></canvas>
<script>
var chartData = "[[${projectStatusCnt}]]"
</script>
</div>
</div>
</div>
<div class="container">
<h4> Current Employees </h4>
<div class="row">
<div class="col-md-6">
<table class="table table-bordered table-striped">
<thead class="thead-dark">
<tr>
<th> First Name </th>
<th> Last Name </th>
<th> Project Count</th>
</tr>
</thead>
<tbody>
<tr th:each="aEmployeeProjectCnt : ${employeesListProjectsCnt}">
<td th:text="${aEmployeeProjectCnt.firstName}"></td>
<td th:text="${aEmployeeProjectCnt.lastName}"></td>
<td th:text="${aEmployeeProjectCnt.projectCount}"></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<script type="text/javascript" th:src="#{js/myChart.js}"></script>
</body>
</html>
Here's the Employee class which has the GenerationStrategy. I tried
both GenerationTypes listed but they give the same exact error in the console logs.
#Id annotation
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="employee_seq")
Again the code snippet below was also tried but that gave me the same exact error as the code that I have attached below and these were recommendations from stackoverflow, but the application still won't work.
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="employee_seq")
#SequenceGenerator(allocationSize=1, name = "employee_generator")
Here's the Employee class
package com.project1.entities;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.SequenceGenerator;
#Entity
public class Employee {
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="employee_seq")
#SequenceGenerator(allocationSize=1, name = "employee_generator")
private long employeeId;
private String firstName;
private String lastName;
private String email;
#ManyToMany(cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.PERSIST},
fetch = FetchType.LAZY)
#JoinTable(name="project_employee",
joinColumns=#JoinColumn(name="employee_id"),
inverseJoinColumns=#JoinColumn(name="project_id")
)
private List<Project> projects;
public Employee() {
}
public Employee(String firstName, String lastName, String email) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
public List<Project> getProjects() {
return projects;
}
public void setProjects(List<Project> projects) {
this.projects = projects;
}
public long getEmployeeId() {
return employeeId;
}
public void setEmployeeId(long employeeId) {
this.employeeId = employeeId;
}
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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Also the same thing with the Project class
package com.project1.entities;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.SequenceGenerator;
#Entity
public class Project {
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="project_seq")
#SequenceGenerator(allocationSize=1, name = "project_generator")
private long projectId;
private String name;
private String stage; // NOTSTARTED, COMPLETED, INPROGRESS
private String description;
#ManyToMany(cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.PERSIST},
fetch = FetchType.LAZY)
#JoinTable(name="project_employee",
joinColumns=#JoinColumn(name="project_id"),
inverseJoinColumns=#JoinColumn(name="employee_id")
)
private List<Employee> employees;
public Project() {
}
public Project(String name, String stage, String description) {
super();
this.name = name;
this.stage = stage;
this.description = description;
}
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
public long getProjectId() {
return projectId;
}
public void setProjectId(long projectId) {
this.projectId = projectId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStage() {
return stage;
}
public void setStage(String stage) {
this.stage = stage;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
//convenience method
public void addEmployee(Employee emp) {
if(employees == null) {
employees = new ArrayList<>();
}
employees.add(emp);
}
}
Here's the error message:
Java HotSpot(TM) 64-Bit Server VM warning: Options -Xverify:none and -noverify were deprecated in JDK 13 and will likely be removed in a future release.
{spring.web.resources.chain.cache=false, spring.web.resources.cache.period=0}
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.4.0)
2020-12-06 19:57:50.893 INFO 8560 --- [ restartedMain] com.project1.PmaApplication : Starting PmaApplication using Java 14.0.2 on DESKTOP-C26F0I7 with PID 8560 (C:\Users\kashi\git\PMA-Application\PMA-Application\target\classes started by kashi in C:\Users\kashi\git\PMA-Application\PMA-Application)
2020-12-06 19:57:50.897 INFO 8560 --- [ restartedMain] com.project1.PmaApplication : No active profile set, falling back to default profiles: default
2020-12-06 19:57:50.975 INFO 8560 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2020-12-06 19:57:50.975 INFO 8560 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2020-12-06 19:57:51.832 INFO 8560 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFERRED mode.
2020-12-06 19:57:51.902 INFO 8560 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 59 ms. Found 2 JPA repository interfaces.
2020-12-06 19:57:52.673 INFO 8560 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2020-12-06 19:57:52.682 INFO 8560 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-12-06 19:57:52.683 INFO 8560 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.39]
2020-12-06 19:57:52.779 INFO 8560 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-12-06 19:57:52.779 INFO 8560 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1803 ms
2020-12-06 19:57:52.843 INFO 8560 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2020-12-06 19:57:52.977 INFO 8560 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2020-12-06 19:57:53.025 INFO 8560 --- [ restartedMain] o.s.b.a.h2.H2ConsoleAutoConfiguration : H2 console available at '/h2-console'. Database available at 'jdbc:h2:mem:c7335b0f-bd3a-43dd-9628-9ea69397c416'
2020-12-06 19:57:53.116 INFO 8560 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2020-12-06 19:57:53.268 INFO 8560 --- [ restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-12-06 19:57:53.381 INFO 8560 --- [ task-1] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-12-06 19:57:53.397 WARN 8560 --- [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'homeController': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'version' in value "${version}"
2020-12-06 19:57:53.397 INFO 8560 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2020-12-06 19:57:53.460 INFO 8560 --- [ task-1] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.23.Final
2020-12-06 19:57:53.619 INFO 8560 --- [ task-1] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2020-12-06 19:57:53.752 INFO 8560 --- [ task-1] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2020-12-06 19:57:54.169 WARN 8560 --- [ restartedMain] o.s.b.f.support.DisposableBeanAdapter : Invocation of destroy method failed on bean with name 'entityManagerFactory': javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Could not instantiate id generator [entity-name=com.project1.entities.Project]
2020-12-06 19:57:54.169 INFO 8560 --- [ restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
2020-12-06 19:57:54.389 WARN 8560 --- [ restartedMain] o.s.b.f.support.DisposableBeanAdapter : Invocation of destroy method failed on bean with name 'inMemoryDatabaseShutdownExecutor': org.h2.jdbc.JdbcSQLNonTransientConnectionException: Database is already closed (to disable automatic closing at VM shutdown, add ";DB_CLOSE_ON_EXIT=FALSE" to the db URL) [90121-200]
2020-12-06 19:57:54.392 INFO 8560 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2020-12-06 19:57:54.400 INFO 8560 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
2020-12-06 19:57:54.405 INFO 8560 --- [ restartedMain] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2020-12-06 19:57:54.439 INFO 8560 --- [ restartedMain] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-12-06 19:57:54.489 ERROR 8560 --- [ restartedMain] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'homeController': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'version' in value "${version}"
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:405) ~[spring-beans-5.3.1.jar:5.3.1]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1415) ~[spring-beans-5.3.1.jar:5.3.1]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:608) ~[spring-beans-5.3.1.jar:5.3.1]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:531) ~[spring-beans-5.3.1.jar:5.3.1]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.1.jar:5.3.1]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.1.jar:5.3.1]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.1.jar:5.3.1]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.1.jar:5.3.1]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:944) ~[spring-beans-5.3.1.jar:5.3.1]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:925) ~[spring-context-5.3.1.jar:5.3.1]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:588) ~[spring-context-5.3.1.jar:5.3.1]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:144) ~[spring-boot-2.4.0.jar:2.4.0]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:767) ~[spring-boot-2.4.0.jar:2.4.0]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759) ~[spring-boot-2.4.0.jar:2.4.0]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:426) ~[spring-boot-2.4.0.jar:2.4.0]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:326) ~[spring-boot-2.4.0.jar:2.4.0]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1309) ~[spring-boot-2.4.0.jar:2.4.0]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1298) ~[spring-boot-2.4.0.jar:2.4.0]
at com.project1.PmaApplication.main(PmaApplication.java:12) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:564) ~[na:na]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) ~[spring-boot-devtools-2.4.0.jar:2.4.0]
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'version' in value "${version}"
at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:178) ~[spring-core-5.3.1.jar:5.3.1]
at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:124) ~[spring-core-5.3.1.jar:5.3.1]
at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:239) ~[spring-core-5.3.1.jar:5.3.1]
at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:210) ~[spring-core-5.3.1.jar:5.3.1]
at org.springframework.context.support.PropertySourcesPlaceholderConfigurer.lambda$processProperties$0(PropertySourcesPlaceholderConfigurer.java:175) ~[spring-context-5.3.1.jar:5.3.1]
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveEmbeddedValue(AbstractBeanFactory.java:931) ~[spring-beans-5.3.1.jar:5.3.1]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1308) ~[spring-beans-5.3.1.jar:5.3.1]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1287) ~[spring-beans-5.3.1.jar:5.3.1]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640) ~[spring-beans-5.3.1.jar:5.3.1]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:119) ~[spring-beans-5.3.1.jar:5.3.1]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399) ~[spring-beans-5.3.1.jar:5.3.1]
... 23 common frames omitted
The parent tag right underneath the model version in the pom.xml file is underlined in red and when I hover over it it shows this.
Execution default-resources of goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources failed: newPosition < 0: (-1 < 0) (org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources:default-resources:process-resources)
org.apache.maven.plugin.PluginExecutionException: Execution default-resources of goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources failed: newPosition < 0: (-1 < 0)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:148)
at org.eclipse.m2e.core.internal.embedder.MavenImpl.execute(MavenImpl.java:332)
at org.eclipse.m2e.core.internal.embedder.MavenImpl.lambda$8(MavenImpl.java:1379)
at org.eclipse.m2e.core.internal.embedder.MavenExecutionContext.executeBare(MavenExecutionContext.java:179)
at org.eclipse.m2e.core.internal.embedder.MavenExecutionContext.execute(MavenExecutionContext.java:114)
at org.eclipse.m2e.core.internal.embedder.MavenImpl.execute(MavenImpl.java:1378)
at org.eclipse.m2e.core.project.configurator.MojoExecutionBuildParticipant.build(MojoExecutionBuildParticipant.java:54)
at org.eclipse.m2e.core.internal.builder.MavenBuilderImpl.build(MavenBuilderImpl.java:135)
at org.eclipse.m2e.core.internal.builder.MavenBuilder$1.method(MavenBuilder.java:169)
at org.eclipse.m2e.core.internal.builder.MavenBuilder$1.method(MavenBuilder.java:1)
at org.eclipse.m2e.core.internal.builder.MavenBuilder$BuildMethod.lambda$1(MavenBuilder.java:114)
at org.eclipse.m2e.core.internal.embedder.MavenExecutionContext.executeBare(MavenExecutionContext.java:179)
at org.eclipse.m2e.core.internal.embedder.MavenExecutionContext.execute(MavenExecutionContext.java:114)
at org.eclipse.m2e.core.internal.builder.MavenBuilder$BuildMethod.lambda$0(MavenBuilder.java:105)
at org.eclipse.m2e.core.internal.embedder.MavenExecutionContext.executeBare(MavenExecutionContext.java:179)
at org.eclipse.m2e.core.internal.embedder.MavenExecutionContext.execute(MavenExecutionContext.java:153)
at org.eclipse.m2e.core.internal.embedder.MavenExecutionContext.execute(MavenExecutionContext.java:101)
at org.eclipse.m2e.core.internal.builder.MavenBuilder$BuildMethod.execute(MavenBuilder.java:88)
at org.eclipse.m2e.core.internal.builder.MavenBuilder.build(MavenBuilder.java:197)
at org.eclipse.core.internal.events.BuildManager$2.run(BuildManager.java:832)
at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:45)
at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:220)
at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:263)
at org.eclipse.core.internal.events.BuildManager$1.run(BuildManager.java:316)
at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:45)
at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:319)
at org.eclipse.core.internal.events.BuildManager.basicBuildLoop(BuildManager.java:371)
at org.eclipse.core.internal.events.BuildManager.build(BuildManager.java:392)
at org.eclipse.core.internal.events.AutoBuildJob.doBuild(AutoBuildJob.java:154)
at org.eclipse.core.internal.events.AutoBuildJob.run(AutoBuildJob.java:244)
at org.eclipse.core.internal.jobs.Worker.run(Worker.java:63)
Caused by: java.lang.IllegalArgumentException: newPosition < 0: (-1 < 0)
at java.base/java.nio.Buffer.createPositionException(Buffer.java:334)
at java.base/java.nio.Buffer.position(Buffer.java:309)
at java.base/java.nio.ByteBuffer.position(ByteBuffer.java:1309)
at java.base/java.nio.ByteBuffer.position(ByteBuffer.java:266)
at org.apache.maven.shared.utils.io.FileUtils.copyFile(FileUtils.java:1946)
at org.apache.maven.shared.filtering.DefaultMavenFileFilter.copyFile(DefaultMavenFileFilter.java:98)
at org.apache.maven.shared.filtering.DefaultMavenResourcesFiltering.filterResources(DefaultMavenResourcesFiltering.java:262)
at org.apache.maven.plugins.resources.ResourcesMojo.execute(ResourcesMojo.java:356)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:137)
... 30 more
Here's the pom.xml file and the tag right underneath the model version
<?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.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.project1</groupId>
<artifactId>PMA-Application</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>PMA-Application</name>
<description>The PMA Web App</description>
<properties>
<java.version>1.8</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-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>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</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</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
I had the same exact problem, hope I can still help somebody with this.
If you're using eclipse go to
File > Properties > Java Build Path > Source
and now under src/main/resources at "Excluded" it said for me "**", make sure to delete this entry so that it sais "(None)". Fixed it for me.
add #PropertySource({"classpath:resource.properties"}) on your controller

cant connect to mysql databse using spring boot

When I am hitting url(http://localhost:8080/pjt/samples) in Postman for json data,it shows the following error.
{
"timestamp": "2020-05-17T10:54:26.705+0000",
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/pjt/samples"
}
1)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.2.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>samplepjt</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>samplepjt</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-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</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>
</plugins>
</build>
</project>
2)model:
package model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "samples")
public class Sample {
private Long id ;
private String name;
private String city;
public Sample(String name, String city) {
this.name = name;
this.city = city;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Column(name = "name", nullable = false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Column(name = "city", nullable = false)
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
#Override
public String toString() {
return "Sample [id=" + id + ",name=" + name + ", city=" + city + "]";
}
}
3)repository
package repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import model.Sample;
#Repository
public interface SampleRepository extends JpaRepository<Sample,Long>{
}
4)controller
package controller;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import model.Sample;
import repository.SampleRepository;
#RestController
#RequestMapping("/pjt")
public class SampleController {
#Autowired
private SampleRepository sampleRepository;
#PostMapping("/samples")
public Sample createSample(#Valid #RequestBody Sample sample) {
return sampleRepository.save(sample);
}
#GetMapping("/samples")
public List<Sample> getAllSample() {
return sampleRepository.findAll();
}
}
5)main function
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class SamplepjtApplication {
public static void main(String[] args) {
SpringApplication.run(SamplepjtApplication.class, args);
}
}
6)application.properties
spring.datasource.url = jdbc:mysql://localhost:3306/sampledb?useSSL=false
spring.datasource.username = root
spring.datasource.password = dali
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.hibernate.ddl-auto = update
. ____ _ __ _ _
/\ / ' __ _ ()_ __ __ _ \ \ \ \
( ( )_ | '_ | '| | ' / ` | \ \ \ \
\/ )| |)| | | | | || (| | ) ) ) )
' |____| .|| ||| |__, | / / / /
=========|_|==============|___/=///_/
:: Spring Boot :: (v2.2.7.RELEASE)
2020-05-17 16:47:56.159 INFO 3688 --- [ main] com.example.demo.SamplepjtApplication : No active profile set, falling back to default profiles: default
2020-05-17 16:47:58.395 INFO 3688 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2020-05-17 16:47:58.476 INFO 3688 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 49ms. Found 0 JPA repository interfaces.
2020-05-17 16:48:00.119 INFO 3688 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8081 (http)
2020-05-17 16:48:00.142 INFO 3688 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-05-17 16:48:00.143 INFO 3688 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.34]
2020-05-17 16:48:00.496 INFO 3688 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-05-17 16:48:00.497 INFO 3688 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 4199 ms
2020-05-17 16:48:00.980 INFO 3688 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-05-17 16:48:01.156 INFO 3688 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.15.Final
2020-05-17 16:48:01.579 INFO 3688 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
2020-05-17 16:48:01.898 INFO 3688 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2020-05-17 16:48:02.714 INFO 3688 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2020-05-17 16:48:02.771 INFO 3688 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5InnoDBDialect
2020-05-17 16:48:03.635 INFO 3688 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation:[org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-05-17 16:48:03.660 INFO 3688 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-05-17 16:48:04.042 WARN 3688 --- [ main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2020-05-17 16:48:04.388 INFO 3688 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-05-17 16:48:04.845 INFO 3688 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8081 (http) with context path ''
2020-05-17 16:48:04.849 INFO 3688 --- [ main] com.example.demo.SamplepjtApplication : Started SamplepjtApplication in 9.906 seconds (JVM running for 12.757)
2020-05-17 16:48:13.367 INFO 3688 --- [nio-8081-exec-2] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-05-17 16:48:13.369 INFO 3688 --- [nio-8081-exec-2] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2020-05-17 16:48:13.395 INFO 3688 --- [nio-8081-exec-2] o.s.web.servlet.DispatcherServlet : Completed initialization in 25 ms
Can anyone help me to fix this issue?
You have to place the SampleController.java in com.example.demo.controller & SampleRepository.java in com.example.demo.repository. Or all the files should be in com.example.demo folder.
Because #SpringBootApplication has to scan all the components. Go through this doc for better understanding https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/html/using-boot-structuring-your-code.html.

Categories

Resources