spring-boot-starter-data-mongodb doesn't seem to include persistence-api to use #PrePersist #PreUpdate - spring-boot

What is the correct way to include and use JPA Entity Lifecycle Events when using spring-boot-starter-data-mongodb?
my pom.xml dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
My classpath doesn't see to have any of the following JPA annotations:
#PrePersist
#PostPersist
#PreRemove
#PostRemove
#PreUpdate
#PostUpdate
#PostLoad

Mongo has its own events documented # #Entity Callbacks.
Example:
class DefaultingEntityCallback implements BeforeSaveCallback<Person>, Ordered {
#Override
public Object onBeforeSave(Person entity, String collection) {
if(collection == "user") {
return // ...
}
return // ...
}
#Override
public int getOrder() {
return 100;
}
}
Following Functional interfaces available:
org.springframework.data.mongodb.core.mapping.event.AfterConvertCallback
org.springframework.data.mongodb.core.mapping.event.AfterSaveCallback
org.springframework.data.mongodb.core.mapping.event.BeforeConvertCallback
org.springframework.data.mongodb.core.mapping.event.BeforeSaveCallback
org.springframework.data.mongodb.core.mapping.event.ReactiveAfterConvertCallback
org.springframework.data.mongodb.core.mapping.event.ReactiveAfterSaveCallback
org.springframework.data.mongodb.core.mapping.event.ReactiveBeforeConvertCallback
org.springframework.data.mongodb.core.mapping.event.ReactiveBeforeSaveCallback

Related

UnknownHostException in Spring Boot with Consul

I am using spring-boot-starter-parent version 2.2.2.RELEASE with spring-cloud.version Hoxton.SR1 to create 2 services : ordercreate(Supplier) and orderconsume(Consumer).
In Consul, the 2 services are up as below
I get the exception
java.net.UnknownHostException: ordercreate
when invoking the orderconsumer service as below:
http://localhost:8282/consumeOrder
Please find the code details below.Thanks for suggestions.
ordercreate
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
application.properties
spring.application.name=ordercreate
server.port=8181
OrderCreateController
#RestController
public class OrderCreateController {
#GetMapping("/createOrder")
public String createOrder() {
System.out.println("In Supplier...");
return "Hello consul";
}
}
For Consumer,
orderconsume
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
application.properties
spring.application.name=orderconsume
server.port=8282
OrderConsumeApplication
#SpringBootApplication
#EnableDiscoveryClient
public class OrderConsumeApplication {
public static void main(String[] args) {
SpringApplication.run(OrderConsumeApplication.class, args);
}
}
OrderConsumeController
#RestController
public class OrderConsumeController {
#Autowired
private RestTemplate restTemplate;
//http://localhost:8282/consumeOrder
#GetMapping(value="/consumeOrder")
public String receiveOrder() {
String uri = "http://ordercreate/createOrder";
return restTemplate.getForObject(uri, String.class);
}
#Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}

Error creating bean with name 'dietaController'

So, I have a problem like this:
2020-01-30 22:54:20.059 ERROR 8040 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'dietaController': Unsatisfied dependency expressed through field 'dietaRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dietaRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.diet4you.LapkoEkaterina.Entity.Dieta
My pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.diet4you</groupId>
<artifactId>LapkoEkaterina</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.3.2.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.2.3.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.16.Final</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
My Entity:
#Entity
#Table(name = "diety")
public class Dieta {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
#Column(name="DIETA_ID") private int dietaId;
#NotEmpty
#Column(unique=true, name ="DIETA_NAZWA")
private String nazwa;
#NotEmpty
#Column(name="OPIS") private String opis;
public Dieta(){ }
public Dieta (int dietaId,String nazwa, String opis )
{ this.dietaId = dietaId;
this.nazwa = nazwa;
this.opis = opis; }
public int getDietaId() {
return dietaId; }
public void setDietaId(int dietaId) {
this.dietaId = dietaId; }
public String getNazwa() {
return nazwa; }
public void setNazwa(String nazwa) {
this.nazwa = nazwa; }
public String getOpis() {
return opis; }
public void setOpis(String opis) {
this.opis = opis; }
}
My repository:
#Repository
public interface DietaRepository extends JpaRepository<Dieta, String> {
Dieta findByName (String name);
}
And my Controller:
#RestController
public class DietaController {
#Autowired
private DietaRepository dietaRepository;
#GetMapping("/dieta")
public List<Dieta> getAllNotes() {
return dietaRepository.findAll();
}
}
Application java class:
#Configuration
#SpringBootApplication
#EnableJpaRepositories
#EntityScan ( basePackages = { " com.diet4you.LapkoEkaterina" })
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
remove space here #EntityScan ( basePackages = { " com.diet4you.LapkoEkaterina" }) between " and com.diet4you...
change extends JpaRepository<Dieta, String> to extends JpaRepository<Dieta, Integer>
remove or fix Dieta findByName (String name) at repository interface, it's mistake

Injecting Specific DataSource in Spring Boot 2.0.2 Release

When trying to autowire DataSource by using Spring Boot 2.0.2 RELEASE, it gives the following error and cannot manage to inject it:
'Could not autowire. There is more than one bean of 'DataSource' type.'
The beans are created in DataSourceConfiguration class for HikariDataSource, BasicDataSource and for Tomcat.
Is there a way of qualifying one of them and avoid creation of the remaining ones?
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
public SecurityConfig() {
this.usersByUsernameQuery = // definitions here
this.authoritiesByUsernameQuery = //
this.allowedAuthorities = //
}
#Autowired
public void configureGlobal(final AuthenticationManagerBuilder auth, final DataSource dataSource) throws Exception {
auth.jdbcAuthentication()
.dataSource(dataSource)
.usersByUsernameQuery(usersByUsernameQuery)
.authoritiesByUsernameQuery(authoritiesByUsernameQuery);
}
}
pom.xml:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
</dependencies>
application.properties:
spring.datasource.url=jdbc:mysql://localhost:9400/test
spring.datasource.username=root
spring.datasource.password=test
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

#DeleteMapping not recognized

I am new with spring boot, is very simple my question but I canĀ“t find where is the problem.
I have a basic #GetMapping and #DeleteMapping
#RestController
public class MyController
{
private MyServiceImpl myService;
#Autowired
public MyController(MyServiceImpl myService)
{
this.myService = myService;
}
#GetMapping("/test")
public List<Scan> getTestData(#RequestParam(value = "test_id", required = true) String test_id) {
return myService.findByTestId( test_id );
}
#DeleteMapping("/test")
public int deleteData(#RequestParam(value = "test_id", required = true) String test_id){
return myService.deleteTest( test_id );
}
#DeleteMapping("/test2")
public String deleteArticle() {
return "Test";
}
}
I am testing with Postman, the Get request is working, but the delete request is not. Even when I debug the spring boot application. The GetMapping is called, whereas the delete is not "reacting" /called
Maybe is not enough information, but I even tested #DeleteMapping("/test2") is not doing anything, I mean, I get no response, and in Postman it stays "loading..."
Any suggestions?
My complete POM
http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
<parent>
<groupId>com.ttt.pdt</groupId>
<artifactId>pdt-base</artifactId>
<version>2.0-SNAPSHOT</version>
</parent>
<artifactId>pdt-service</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.4.0</version>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
The parent (pdt-base) has
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
</parent>
MyServiceImpl
#Service
public class MyServiceImpl
{
private ScnDao scnDao;
#Autowired
public ScanServiceImpl(ScnDao scnDao){
this.scnDao = scnDao;
}
public int deleteTest( String test_id )
{
return scnDao.deleteTest( test_id );
}
}
public interface ScanDao
{
int deleteTest( String test_id )
}
#Repository
public class ScnPostgres implements ScnDao
{
private JdbcTemplate jdbcTemplate;
#Autowired
public ScnPostgres( JdbcTemplate jdbcTemplate )
{
this.jdbcTemplate = jdbcTemplate;
}
public int deleteTest( String test_id )
{
String SQL = "DELETE FROM scn WHERE test_id = ?";
return jdbcTemplate.update( SQL, new String[] { test_id } );
}
}
As in SPR comments described SPR-16874:
it does not support DELETE currently. It would be a trivial change to
make. There is suggested a workaround:
#DeleteMapping(value = "/greeting")
public Greeting handle(#RequestBody MultiValueMap<String, String> params) {
return new Greeting(counter.incrementAndGet(),
String.format(template, params));
}
As you can see the issue has been opened in the spring boot tracker.

Spring Boot/Spring Integration Servlet Context/DelegatingWebMvcConfiguration issue

I'm not sure the best way to word this issue, because I have no idea why this happens.
When I start up my Spring Boot application without the spring-integration-core jar, my app starts up fine. The second I add the spring-boot-starter-integration or any spring-integration-core library to my Maven pom file the servlet context is always null on my DelegatingWebMvcConfiguration class and I get the following error:
java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
After doing some debugging, I see the DelegatingWebMvcConfiguration class initialized before the EmbeddedWebApplicationContext sets the servlet context for my application, which makes sense why the servlet context is null for my DelegatingWebMvcConfiguration and set for all the other classes initialized with postProcessBeforeInitialization in ServletContextAwareProcessor. Simply removing the Spring Integration dependency fixes the issue, but I'd like to use Spring Integration in my Boot application.
My question is what would cause the DelegatingWebMvcConfiguration to be created before the EmbeddedWebApplicationContext can call prepareEmbeddedWebApplicationContext method.
Spring dependencies using Spring Boot 1.1.8.RELEASE:
org.springframework.boot
spring-boot-starter-web
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-solr</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-integration</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.hateoas</groupId>
<artifactId>spring-hateoas</artifactId>
<version>0.16.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-core</artifactId>
<version>2.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-cassandra</artifactId>
<version>1.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.ldap</groupId>
<artifactId>spring-ldap-core</artifactId>
<version>2.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>4.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-messaging</artifactId>
<version>4.1.2.RELEASE</version>
</dependency>
My root configuration file:
#Configuration
#EnableAutoConfiguration
#EnableAsync
#EnableEntityLinks
#EnableSpringDataWebSupport
#ComponentScan
#PropertySource(value = "file:../application.properties",
ignoreResourceNotFound = true)
public class ApplicationInitializer extends SpringBootServletInitializer
implements EmbeddedServletContainerCustomizer {
public static void main(String[] args) throws Exception {
SpringApplication.run(ApplicationInitializer.class, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application){
return application.sources(ApplicationInitializer.class);
}
#Override
public void customize(ConfigurableEmbeddedServletContainer container) {
container.setContextPath(APPLICATION_ROOT_PATH);
}
// Global beans defined here
}
Update: After trying many different things, I found out after disabling my SchedulingConfigurer my app now starts. Here is my SchedulingConfigurer
#Configuration
#EnableScheduling
#EnableConfigurationProperties(SchedulingProperties.class)
public class SchedulingConfig implements SchedulingConfigurer {
//Inject Runnables and properties
#Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setScheduler(taskScheduler());
// call taskRegistrar.addFixedRateTask with runnable and property rate value
}
#Bean(destroyMethod = "shutdown")
public Executor taskScheduler() {
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.setPoolSize(Runtime.getRuntime().availableProcessors());
return taskScheduler;
}
}

Resources