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).
Related
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
Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception; nested exception is java.lang.IllegalStateException: Cannot load driver class: oracle.jdbc.driver.OracleDriver
pom.xml file
https://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>
</parent>
<groupId>com.Projectdashboardtool</groupId>
<artifactId>Project</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Project</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-web</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-jersey</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-services</artifactId>
</dependency> -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc8</artifactId>
<version>12.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
Controller class
#RestController
#RequestMapping("/project")
public class ProjectController {
#Autowired
private ProjectRepository projectRepository;
#GetMapping
public List<Project> list(){
//List<Project> project=new ArrayList<>();
return projectRepository.findAll();
}
#PostMapping
#ResponseStatus(HttpStatus.OK)
public void create(#RequestBody Project project) {
projectRepository.save(project);
}
#GetMapping("/{id}")
public Project get(#PathVariable("id") long id) {
return projectRepository.getOne(id);
}
}
Model class
package com.Projectdashboardtool.Project.Model;
import java.sql.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#Entity
#JsonIgnoreProperties({"hiberanateLazyInitializer", "handler"})
public class Project {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String dg_number;
private String project;
private String release_level;
private String release_area;
private String release_number;
#JsonFormat(shape=JsonFormat.Shape.STRING, pattern="dd-MM-yyyy")
private Date planned_release_date;
private Date release_date;
public String getDg_number() {
return dg_number;
}
public void setDg_number(String dg_number) {
this.dg_number = dg_number;
}
public String getProject() {
return project;
}
public void setProject(String project) {
this.project = project;
}
public String getRelease_level() {
return release_level;
}
public void setRelease_level(String release_level) {
this.release_level = release_level;
}
public String getRelease_area() {
return release_area;
}
public void setRelease_area(String release_area) {
this.release_area = release_area;
}
public String getRelease_number() {
return release_number;
}
public void setRelease_number(String release_number) {
this.release_number = release_number;
}
public Date getPlanned_release_date() {
return planned_release_date;
}
public void setPlanned_release_date(Date planned_release_date) {
this.planned_release_date = planned_release_date;
}
public Date getRelease_date() {
return release_date;
}
public void setRelease_date(Date release_date) {
this.release_date = release_date;
}
public String getRelease_type() {
return release_type;
}
public void setRelease_type(String release_type) {
this.release_type = release_type;
}
private String release_type;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Override
public String toString() {
return "Project [id=" + id + ", dg_number=" + dg_number + ", project=" + project + ", release_level="
+ release_level + ", release_area=" + release_area + ", release_number=" + release_number
+ ", planned_release_date=" + planned_release_date + ", release_date=" + release_date
+ ", release_type=" + release_type + "]";
}
}
application.properties file
spring.jpa.hibernate.ddl-auto=update
spring.jpa.database-platform=org.hibernate.dialect.SQLServer2012Dialect
spring.datasource.url=jdbc:oracle:thin:#//hostname/servicename
spring.datasource.username=username
spring.datasource.password=password
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
Adding dependency :
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc8</artifactId>
<version>12.1.0</version>
</dependency>
And correct hibernate dialect - org.hibernate.dialect.OracleDialect should work.
I think you are using property file for DB oracle. From your exception i can able to see spring boot failed to load oracle driver. So download ojdbc6.jar from Oracle website or if you install oracle11g in your local system you can find ojdbc in jdbc/lib folder.
add this to your project, On eclipse right click on project --> build path --> add this jar.
So suppose you are using spring boot add this dependency to your pom.xml
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0</version>//add letest version
</dependency>
Suppose if your dependency not detected by maven follow the below steps:-
Run this command
mvn install:install-file - Dfile=C:\Users\user\.m2\repository\com\oracle\ojdbc6\11.2.0\ojdbc6.jar -DgroupId=com.oracle -DartifactId=ojdbc6 -Dversion=11.2.0 -Dpackaging=jar
Then You can Use this.
Oracle JDBC drivers are available on Central Maven. Check out this blog. You can add this GAV for 18.3 JDBC driver.
<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc8</artifactId>
<version>18.3.0.0</version>
I'm trying to implement custom method in Spring Data repository using Spring Boot 1.5.9.RELEASE.
I created the repository:
package com.example.springdatademo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
interface MyEntityRepository extends JpaRepository<MyEntity, String>, CustomMyEntityRepository {
}
Provided the custom repository:
package com.example.springdatademo;
interface CustomMyEntityRepository {
MyEntity myCustomFindQuery();
}
And the implementation:
package com.example.springdatademo;
import org.springframework.stereotype.Component;
#Component
class CustomMyEntityRepositoryImpl implements CustomMyEntityRepository {
#Override
public MyEntity myCustomFindQuery() {
System.out.println("hello from custom query implementation");
return null;
}
}
Plus, I provided an invocation:
package com.example.springdatademo;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#EntityScan
#EnableJpaRepositories
#SpringBootApplication
public class SpringDataDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringDataDemoApplication.class, args);
}
#Bean
public CommandLineRunner run(MyEntityRepository repository) {
return (args) -> {
final MyEntity myEntity1 = repository.myCustomFindQuery();
repository.save(new MyEntity(1, "fieldTwo"));
for (MyEntity myEntity : repository.findAll()) {
System.out.println(myEntity);
}
};
}
}
pom.xml is just plain one generated from spring initializer:
<?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>1.5.9.RELEASE</version>
<!-- <version>2.1.9.RELEASE</version>-->
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>spring-data-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-data-demo</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>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>
When running the project on Spring Boot 1.5.9.RELEASE I'm getting a problem on container creation:
Caused by: java.lang.IllegalArgumentException: Failed to create query method public abstract com.example.springdatademo.MyEntity com.example.springdatademo.CustomMyEntityRepository.myCustomFindQuery()! No property myCustomFindQuery found for type MyEntity!
Changing the Spring Boot version to 2.1.9.RELEASE works fine and gives me the expected result.
I can't find any tips in spring-data-jpa-1.11.9.RELEASE documentation
I just checked out your code and was able to fix it. This is what I did
Rename MyEntityRepositoryCustomImpl to MyEntityRepositoryImpl and
As I told you in my comment, cutom repository should be named MyEntityRepositoryCustom(I guess you already did this)
Naming convention is the key here. Impl class should be named <BaseRepository>Impl. And not <CustomRepository>Impl
If you want your current code to run then you need a #NamedQuery if you want to run hql
or if you want to run native query #NamedNativeQuery with a name MyEntity.myCustomFindQuery in your Entity class
#NamedQuery(name="MyEntity.myCustomFindQuery",
query="SELECT 1 as a, 'a' as b from MyEntity")
or
#NamedNativeQuery(name="MyEntity.myCustomFindQuery",
query="SELECT 1 as a, 'a' as b", resultSetMapping="mapmyCustomFindQuery")
#SqlResultSetMapping(name = "mapmyCustomFindQuery", classes = {
#ConstructorResult(targetClass = MyEntity.class, columns = {
#ColumnResult(name = "a"), #ColumnResult(name = "b")
})
})
Alternatively you can keep both repository separate (means MyEntityRepository shouldn't extend MyEntityRepositoryCustom
in that case your Application class will look like below
#Autowired
MyEntityRepository repository;
#Autowired
MyEntityRepositoryCustom entityRepositoryCustom;
public static void main(String[] args) {
SpringApplication.run(SpringDataDemoApplication.class, args);
}
#Bean
public CommandLineRunner run() {
return (args) -> {
final MyEntity myEntity1 = entityRepositoryCustom.myCustomFindQuery();
repository.save(new MyEntity(1, "fieldTwo"));
for (MyEntity myEntity : repository.findAll()) {
System.out.println(myEntity);
}
};
}
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 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;
}
}