I have just started a Spring tutorial. I do everything the same as the lecturer, but if I make a getRequest nothing changes. I also do not have any grey globe icons next to the #RequestMapping and #GetMapping annotations ss of grey globe icon. Would be happy to have any suggestions. Here is the erorr I get when I call the controller endpoint error page
package Controller;
import model.Il;
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.RestController;
import java.util.Arrays;
import java.util.List;
#RestController
#RequestMapping("/iller")
public class ILController {
#GetMapping
public ResponseEntity<List<Il>> getIller(){
Il il1 = new Il("34", "Istanbul");
Il il2 = new Il("06", "Ankara");
List<Il> iller = Arrays.asList(il1, il2);
return new ResponseEntity<>(iller, HttpStatus.OK);
}
}
Il class:
package model;
import lombok.Data;
#Data
public class Il {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Il(){
this.id = "defaultId";
this.name = "defaultName";
}
public Il(String id, String name){
this.id = id;
this.name = name;
}
}
I built your example from scratch with Intellij. Could you try re-editing your code as in the screenshot? If you need help with Spring, please write.
you need to fill the annotation #GetMapping with a path that defines your GET method.
For example, try something like this:
#GetMapping(value = "/GetIller")
public ResponseEntity<List<Il>> getIller(){
Il il1 = new Il("34", "Istanbul");
Il il2 = new Il("06", "Ankara");
List<Il> iller = Arrays.asList(il1, il2);
return new ResponseEntity<>(iller, HttpStatus.OK);
}
Same for other HTTP methods (POST, PUT, PATCH, DELETE ...)
Please check the pom also:
<?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.7.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.yml
server:
port: 9090
Application.java
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Regarding the Glob Icon feature, I think that feature is only available in the IntelliJ Enterprise version.
By clicking that grey globe icon it gives 3 options -
Go to declaration or usage
Generate request in HTTP Client
Show all endpoints of module
Related
Attempting to write a Java RESTful API When I run mvn clean install I build no problem. When I run mvn spring-boot run I get the following runtime error. I have included the pom.xml and classes that I think are relevant. I also have a service layer and entity class not listed, though I don't think they are the issue. I can add if maybe someone would like to see them as well. Any help would be greatly appreciated.Thank you in advance.
org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.context.ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean.
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:161) ~[spring-boot-2.3.3.RELEASE.jar:2.3.3.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:545) ~[spring-context-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:143) ~[spring-boot-2.3.3.RELEASE.jar:2.3.3.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:758) ~[spring-boot-2.3.3.RELEASE.jar:2.3.3.RELEASE]
below is code that I think could potentially be causing the problem:
pom.xml
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.example.myproject</groupId>
<artifactId>Java_API</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.3.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<version>2.3.3.RELEASE</version>
<scope>provided</scope>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>3.0.2</version>
</plugin>
</plugins>
</build>
</project>
Main.java
package com.example.myproject;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Main {
public static void main(String[] args)
{
SpringApplication.run(myController.class,args);
}
}
myController.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class myController {
#Autowired
private EmployeeService employeeService;
#GetMapping("/employee/{id}")
public Employee getEmployee(#PathVariable int id) {
return employeeService.getEmployee(id);
}
#PostMapping("/employee")
public void createEmployee(#RequestBody Employee employee) {
EmployeeService.createEmployee(employee);
}
}
I have tried only having starter-web instead of both starter-web and starter-tomcat, but it yields the same result. The versioning seems right.
tried adding <scope>provided</scope>, granted I'm not entirely sure what it does.
A number of other things that may come to me, blanking on everything I have tried. Really stumped on what it does not like.
Change Main.java
change SpringApplication.run(myController.class,args);
to
SpringApplication.run(Main.class, args);
public static void main(String[] args)
{
//SpringApplication.run(myController.class,args);
SpringApplication.run(Main.class, args);
}
pom.xml
you can remove spring-boot-starter-tomcat
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.example.myproject</groupId>
<artifactId>Java_API</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.3.3.RELEASE</version>
</dependency>
<!--
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<version>2.3.3.RELEASE</version>
<scope>provided</scope>
</dependency>
-->
</dependencies>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>3.0.2</version>
</plugin>
</plugins>
</build>
</project>
package and run
mvn clean package spring-boot:run
test
curl http://localhost:8080/employee/22
I can't get enough information from your question. I change my test code:
myController.java
package com.example.myproject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class myController {
//#Autowired
//private EmployeeService employeeService;
#GetMapping("/employee/{id}")
public Employee getEmployee(#PathVariable int id) {
Employee e1=new Employee();
e1.setId(id);
e1.setName("Hello World");
return e1;
//return employeeService.getEmployee(id);
}
#PostMapping("/employee")
public void createEmployee(#RequestBody Employee employee) {
System.out.println("DEBUG-"+ employee.getId()+"\t"+employee.getName());
//EmployeeService.createEmployee(employee);
}
}
Employee.java
package com.example.myproject;
public class Employee {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
I use the following code to test on my machine and it can be executed. At the same time, when you change SpringApplication.run(Main.class, args); back to SpringApplication.run(myController.class, args) ;, when executed it throws the same error message as in the question, Unable to start web server; nested exception is org.springframework.context.ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean.
If there are other error messages generated, it should be part of your EmployeeService. You did not provide enough information.
My sample spring boot REST web service gives 404 error, and I am not sure what went wrong
package com.in28minutes.springboot.studentservices;
#SpringBootApplication
public class StudentServicesApplication {
public static void main(String[] args) {
SpringApplication.run(StudentServicesApplication.class, args);
}
}
package com.in28minutes.springboot.controller;
#RestController
public class StudentController {
#Autowired
private StudentService studentService;
#GetMapping("/students/{studentId}/courses")
public List<Course> retrieveCoursesForStudent(#PathVariable String
studentId) {
return studentService.retrieveCourses(studentId);
}
#GetMapping("/students/{studentId}/courses/{courseId}")
public Course retrieveDetailsForCourse(#PathVariable String studentId,
#PathVariable String courseId) {
return studentService.retrieveCourse(studentId, courseId);
}
}
My Request from POSTMan REST request sender:
http://localhost:8080/students/stu1/courses/course1
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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.in28minutes.springboot</groupId>
<artifactId>student-services</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>student-services</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-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>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>
Response:
{
"timestamp": "2018-12-28T02:48:00.185+0000",
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/students/stu1/courses/course1"
}
As assumed, you have Controller classes in different package com.in28minutes.springboot.controller; and Spring boot main class in different package com.in28minutes.springboot.studentservices;
#SpringBootApplication
By default #SpringBootApplication will only scan from the package of the class that declares this annotation.
This is a convenience annotation that is equivalent to declaring #Configuration, #EnableAutoConfiguration and #ComponentScan.
If specific packages are not defined, scanning will occur from the package of the class that declares this annotation.
use #ComponentScan to scan controller package
#ComponentScan(basePackages = {"com.in28minutes.springboot.controller"})
#SpringBootApplication
public class StudentServicesApplication {
public static void main(String[] args) {
SpringApplication.run(StudentServicesApplication.class, args);
}
}
More Info : ref
The issue is resolved, #Component needed to be added to Service class, along with #ComponentScan in the main application class:
package com.in28minutes.springboot.service;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.stereotype.Component;
import com.in28minutes.springboot.model.Course;
import com.in28minutes.springboot.model.Student;
#Component
public class StudentService {
public List<Course> retrieveCourses(String studentId) {
Map<String, Course> courses = Student.getStudentObj(studentId).getCourses();
List<Course> courseList =
courses.values().parallelStream().collect(Collectors.toList());
return courseList;
}
public Course retrieveCourse(String studentId, String courseId) {
return Student.getStudentObj(studentId).getCourses().get(courseId);
}
}
package com.in28minutes.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
#ComponentScan("com.in28minutes.springboot")
public class StudentServicesApplication {
public static void main(String[] args) {
SpringApplication.run(StudentServicesApplication.class, args);
}
}
I'm creating a simple rest controller with Spring Boot and the Web dependency. I'm trying to deserialize a JSON body to a test POJO with only 3 fields, but when I attempt to make a POST request, the server responds with a 500 error and the error I get in the console is:
.w.s.m.s.DefaultHandlerExceptionResolver : Failed to write HTTP message: org.springframework.http.converter.HttpMessageNotWritableException: No converter found for return value of type: class java.util.LinkedHashMap
All of the code I have written is as follows:
EmailApplication.java:
package com.test.email.app;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
#ComponentScan(basePackages = { "com.test.email" })
public class EmailApplication {
public static void main(String[] args) {
SpringApplication.run(EmailApplication.class, args);
}
#Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
return args -> {
System.out.println("----- You're up and running with test-email-app! -----");
};
}
}
EmailController.java:
package com.test.email.controller;
import com.test.email.entity.TestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import java.net.URI;
#RestController
public class EmailController {
#RequestMapping(value = "/", method = RequestMethod.GET)
public String index() {
TestEntity entity = new TestEntity();
return "test-email-app index";
}
#RequestMapping(value = "/poster", method = RequestMethod.POST)
public ResponseEntity<String> poster(#RequestBody TestEntity testEntity) {
URI location = URI.create("/poster");
return ResponseEntity.created(location).body(testEntity.getUrl());
}
}
TestEntity.java
package com.test.email.entity;
/**
* An entity for serialization/deserialization testing
*/
public class TestEntity {
public String url;
public int count;
public double height;
public TestEntity() {}
public TestEntity(String url, int count, double height) {
this.url = url;
this.count = count;
this.height = height;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
}
I'm making a POST request with Postman using only the header Content-Type: application/json and with the body:
{ "url": "http://google.com", "count": 3, "height": 2.4 }
I don't know why Spring can't convert from a LinkedHashMap to my POJO. Any help would be appreciated.
Edit:
My pom.xml is as follows:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.test.email</groupId>
<artifactId>test-email-app</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>test-email-app</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
After Analyzing your problem, I found some cases where this issue can arise.
Those are given bellow:
Inner Class:
If your class TestEntity is Inner class of your endpoint.
Just transfer your TestEntity from Inner class to a separate class and run your code, it will work.
Support Inner Class:
If you want to support inner class a RequestBody then make TestEntity class as static, this will solve your problem.
Spring dependency configuration:
If still not solved your problem, check your dependency on pom.xml. May be you are not adding dependency on proper way. For this you can view this answer . Or you can add jackson explicitly in your pom.xml file.
Dependencies are:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.4.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.3</version>
</dependency>
Hope this will solve your problem :)
If still not solved your problem, check some youtube video or some blog site or download some open-source project from github.
Thanks :)
Related links:
Spring #Requestbody not mapping to inner class
Try to specify that your method consumes JSON. Change your annotation:
#RequestMapping(value = "/poster", method = RequestMethod.POST)
to
#PostMapping(value = "/poster",
consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,
produces = MediaType.TEXT_HTML)
The main part here that you specify that you accept your input to be JSON. Not sure what type you return but you can specify the appropriate type or remove the "produces" part. The main part is to specify what your input is
Ideally this code should work but give a try by adding below dependency in pom.xml
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.0</version>
</dependency>
I have following field declaration:
#Entity
public class TransactionStateHistory {
...
#Column(nullable = false)
private LocalDateTime dateTime;
...
}
and following dependency:
compile group: 'org.hibernate', name: 'hibernate-java8', version: '5.2.10.Final'
but in database I see <binary data>:
Where do I wrong?
From question I see that you are trying to use Hibernate-java8 module instead use Hibernate-core 5.2.10.Final as Hibernate-java8 is merged in Hibernate-core which takes care of converting values to LocalDateTime
Here is the working sample
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class LocalDateTimeDemoApplication {
public static void main(String[] args) {
SpringApplication.run(LocalDateTimeDemoApplication.class, args);
}
}
My entity class
import java.time.LocalDateTime;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class DateTimeEntity
{
#Id
#GeneratedValue
private Integer id;
private LocalDateTime localDate;
public Integer getId()
{
return id;
}
public void setId(Integer id)
{
this.id = id;
}
public LocalDateTime getLocalDate()
{
return localDate;
}
public void setLocalDate(LocalDateTime localDate)
{
this.localDate = localDate;
}
}
My repository
import org.springframework.data.jpa.repository.JpaRepository;
public interface LocalDateTimeRep extends JpaRepository<DateTimeEntity, Integer>
{
}
Now testing time.
import java.time.LocalDateTime;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.example.entity.DateTimeEntity;
import com.example.entity.LocalDateTimeRep;
#RunWith(SpringRunner.class)
#SpringBootTest
public class LocalDateTimeDemoApplicationTests {
#Autowired LocalDateTimeRep repo;
#Test
public void contextLoads() {
DateTimeEntity dateTimeEntity = new DateTimeEntity();
dateTimeEntity.setLocalDate(LocalDateTime.now());
DateTimeEntity persistedEntry = repo.save(dateTimeEntity);
System.out.println(persistedEntry.getLocalDate());
}
}
you can persist and retrieve the values of type LocalDateTime without any converts using Hibernate 5.2.10.Final.
Key is the POM.XML, you need to exclude hibernate-entitymanager from jpa module and in properties set hibernate.version to 5.2.10.Final
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>LocalDateTimeDemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>LocalDateTimeDemo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.3.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<hibernate.version>5.2.10.Final</hibernate.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
**<exclusions>
<exclusion>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</exclusion>
</exclusions>**
</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>
This way you can use LocalDateTime in springboot and Hibernate.
In your main application class (for example MainApplication) could you try to add the following?
#EnableJpaRepositories
#EntityScan(basePackageClasses = {MainApplication.class, Jsr310JpaConverters.class})
Jsr310 is from
org.springframework.data.jpa.convert.threeten.Jsr310JpaConverters
Please notice that jpa #Temporal do not support java.time class like LocalDateTime here.
You need to write a converter and set it to automatic bind like this code:
import java.sql.Date;
import java.time.LocalDate;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
/**
* Converter for java.time persistence.
*
* #author m.elbehi
*/
#Converter(autoApply = true)
public class LocalDateConverter implements AttributeConverter<LocalDate, Date> {
#Override
public Date convertToDatabaseColumn(LocalDate date) {
return date != null ? Date.valueOf(date) : null;
}
#Override
public LocalDate convertToEntityAttribute(Date value) {
return value != null ? value.toLocalDate() : null;
}
}
I am trying to create a basing spring app using mongoDB, but I don't know how to connect to the database. I tried something like this:
application.properties:
spring.data.mongodb.host=127.0.0.1
spring.data.mongodb.database=mongulet
spring.datasource.driver-class-name=mongodb.jdbc.MongoDriver
spring.data.mongodb.port=27017
Main Application:
package com.example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class RestSuperAdvancedApplication implements CommandLineRunner{
#Autowired
private CustomerRepository repository;
public static void main(String[] args) {
SpringApplication.run(RestSuperAdvancedApplication.class, args);
}
#Override
public void run(String... strings) throws Exception {
repository.deleteAll();
repository.save(new Customer("Crisan", "Raoul"));
repository.save(new Customer("Smith", "Martha"));
repository.save(new Customer("Erie", "Jayne"));
repository.save(new Customer("Robinson", "Crusoe"));
System.out.println("Customers found : ");
repository.findAll().forEach(System.out::println);
System.out.println();
System.out.println("Customer found by first name: (Erie)");
System.out.println("----------------");
System.out.println(repository.findOneByFirstName("Erie"));
}
}
Customer class:
package com.example;
import javax.persistence.Id;
/**
* Created by rcrisan on 7/19/2016.
*/
public class Customer {
#Id
private String id;
private String firstName;
private String lastName;
public Customer() {
}
public Customer(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
#Override
public String toString() {
return "Customer{" +
"id='" + id + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
'}';
}
}
Repository:
package com.example;
import org.springframework.data.mongodb.repository.MongoRepository;
import java.util.List;
/**
* Created by rcrisan on 7/19/2016.
*/
public interface CustomerRepository extends MongoRepository<Customer, String> {
Customer findOneByFirstName(String fistName);
List<Customer> findByLastName(String lastName);
}
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>com.example</groupId>
<artifactId>restsuperadvanced</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>restSuperAdvanced</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-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>
After I run the program I get this exception:
Caused by: java.lang.IllegalStateException: Cannot load driver class: mongodb.jdbc.MongoDriver
Is there another way to connect to a mongoDB without using driver class ?
You seem to be trying to mix JPA, which is primarily intended for relational datastores, with MongoDB, which is an "unrelated" document store. Drop the dependency on spring-boot-starter-data-jpa (you simply don't need it) and the spring.datasource.driver-class-name (you should use MongoDB natively, not via a JDBC bridge).