How I "solved" it:
The initial problem was that I forgot to change the package name in the main class that launches the application:
#EnableJpaRepositories(basePackages = {"com.sda.VictorLiviu.ecommerce.jparepository"})
After that I just instanced itemMapper as a normal class in ItemService like this:
ItemMapper itemMapper = new ItemMapper();
and than used its toEntity method as:
itemMapper.toEntity();
. . . . . . . . . . . .
My Spring Boot app says it doesn't have a Bean class which it clearly has. I will post the Pom, service and repository. I want to point out that I have exactly the same class and repository for UserService and OrderService and they don't give any error, the only difference is the #Transactional and I removed it and got the same error.Any suggestions are welcomed!
The Error:
Description:
Field repository in com.sda.VictorLiviu.ecommerce.service.ItemService required a bean of type 'com.sda.VictorLiviu.ecommerce.JpaRepository.ItemRepository' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.sda.VictorLiviu.ecommerce.JpaRepository.ItemRepository' in your configuration.
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.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.sda.VictorLiviu</groupId>
<artifactId>e-commerce</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>e-commerce</name>
<description>E-commerce website Final Project sda</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>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</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>
ItemService class
package com.sda.VictorLiviu.ecommerce.service;
import com.sda.VictorLiviu.ecommerce.DtoMapper.ItemMapper;
import com.sda.VictorLiviu.ecommerce.JpaRepository.ItemRepository;
import com.sda.VictorLiviu.ecommerce.exceptions.ItemNotFoundException;
import com.sda.VictorLiviu.ecommerce.model.Item;
import com.sda.VictorLiviu.ecommerce.dto.ItemDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;
#Transactional
#Service
public class ItemService {
#Autowired
ItemRepository repository;
#Autowired
ItemMapper itemMapper;
public void add(ItemDto dto) {
repository.save(itemMapper.toEntity(dto));
}
public Item delete(Long id) {
repository.deleteById(id);
return null;
}
public List<Item> getItems() {
return repository.findAll();
}
public Item getItemById(Long id) {
Optional<Item> optionalItem = repository.findById(id);
return optionalItem.orElseThrow( () -> new ItemNotFoundException("Couldn't find the specific item!"));
}
}
Repository
package com.sda.VictorLiviu.ecommerce.JpaRepository;
import com.sda.VictorLiviu.ecommerce.model.Item;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface ItemRepository extends JpaRepository<Item, Long> {
}
Item Class
package com.sda.VictorLiviu.ecommerce.model;
import javax.persistence.*;
#Entity
#Table(name="item")
public class Item {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "item_seq_gen")
#SequenceGenerator(name = "item_seq_gen", sequenceName = "item_seq", allocationSize = 1)
#Column(name = "id")
private Long id;
#Column(name = "price")
private double price;
#Column(name = "name")
private String name;
#Column(name = "category")
private String category;
#Column(name = "quantity")
private int quantity;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
ItemDto Class
package com.sda.VictorLiviu.ecommerce.dto;
public class ItemDto {
private Long id;
private double price;
private String name;
private String category;
private int quantity;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
Application.properties
logging.level.org.springframework=info
jwt.signing.key.secret=mySecret
jwt.get.token.uri=/authenticate
jwt.refresh.token.uri=/refresh
jwt.http.request.header=Authorization
jwt.token.expiration.in.seconds=604800
spring.jpa..show-sql=true
spring.h2.console.enabled=true
!!!!!!
Image with my packages
You need to turn on jpa repositories processing.
To do this, annotate your application with #EnableJpaRepositories
Related
I'm fairly new at maven spring boot.
I'm running mvn clean install then mvn spring-boot:run
I'm then able to go an http post and insert data into the database. I can do an http get and see the data. I can view the data in mysql.
When I re-compile and run mvn clean install again, I'm not sure what's making it delete all the data in my product table in the database.
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.7.0</version>
<relativePath/>
<!-- lookup parent from repository -->
</parent>
<groupId>sample.info</groupId>
<artifactId>mainapp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mainapp</name>
<description>Spring Boot Project</description>
<properties>
<java.version>18</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</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-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<forkCount>0</forkCount>
<reuseForks>true</reuseForks>
<argLine>-Xmx1024m -XX:MaxPermSize=256m</argLine>
</configuration>
</plugin>
</plugins>
</build>
</project>
application.properties
spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost:3306/appdb
spring.datasource.username=root
spring.datasource.password=
server.port = 9095
MainappApplication.java
package sample.info.mainapp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
#EnableJpaAuditing
#SpringBootApplication
public class MainappApplication {
public static void main(String[] args) {
SpringApplication.run(MainappApplication.class, args);
}
}
controllers/ProductController.java
package sample.info.mainapp.controllers;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sample.info.mainapp.model.Product;
import sample.info.mainapp.repository.ProductRepository;
#RestController
#RequestMapping("/api")
public class ProductController {
#Autowired
ProductRepository productRepository;
#GetMapping("/products")
public List<Product> getAllProducts() {
final List<Product> productList = new ArrayList<Product>();
Iterable<Product> iterable = productRepository.findAll();
iterable.forEach(productList::add);
return productList;
}
#GetMapping("/products/{id}")
public ResponseEntity<Product> getProductById(#PathVariable(value = "id") Long id) {
Optional<Product> product = productRepository.findById(id);
return product.isPresent() ? new ResponseEntity<Product>(product.get(), HttpStatus.OK)
: new ResponseEntity("No data found", HttpStatus.NOT_FOUND);
}
#PostMapping("/products")
public Product createProduct(#RequestBody Product product) {
return productRepository.save(product);
}
#PutMapping("/products/{id}")
public ResponseEntity<Product> updateProduct(#PathVariable(value = "id") Long id, #RequestBody Product newProduct) {
Optional<Product> product = productRepository.findById(id);
if (product.isPresent()) {
Product prod = product.get();
prod.setDescription(newProduct.getDescription());
prod.setPrice(newProduct.getPrice());
prod.setTitle(newProduct.getTitle());
prod = productRepository.save(prod);
return ResponseEntity.ok().body(prod);
} else {
return ResponseEntity.notFound().build();
}
}
#DeleteMapping("/products/{id}")
public ResponseEntity<Product> deleteProduct(#PathVariable(value = "id") Long id) {
Optional<Product> product = productRepository.findById(id);
if (product.isPresent()) {
productRepository.delete(product.get());
return new ResponseEntity("Product has been deleted successfully.", HttpStatus.OK);
} else {
return ResponseEntity.notFound().build();
}
}
}
model/Product.java
package sample.info.mainapp.model;
import javax.persistence.*;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.Date;
#Entity
#Table(name = "products")
#EntityListeners(AuditingEntityListener.class)
#JsonIgnoreProperties(value = { "created_at", "updated_at" }, allowGetters = true)
public class Product {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "title")
private String title;
#Column(name = "description")
private String description;
#Column(name = "price")
private float price;
#Column(nullable = false, updatable = false)
#Temporal(TemporalType.TIMESTAMP)
#CreatedDate
private Date created_at;
#Column(nullable = false)
#Temporal(TemporalType.TIMESTAMP)
#LastModifiedDate
private Date updated_at;
public Product() {
}
public Product(Long id, String title, String description, float price) {
this.id = id;
this.title = title;
this.description = description;
this.price = price;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public Date getCreated_at() {
return created_at;
}
public Date getUpdated_at() {
return updated_at;
}
}
repository/ProductRepository.java
package sample.info.mainapp.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import sample.info.mainapp.model.Product;
#Repository
public interface ProductRepository extends CrudRepository <Product, Long> {
}
spring.jpa.hibernate.ddl-auto = create -– Hibernate first drops existing tables, then creates new tables. Click here for more details.
Remove / comment this property from application.properties and try.
I am in the process of learning Java spring Boot from the tutorial found here
I keep getting the "Field topicRepository in api.dataBase.basic.apiDatabase.Models.TopicService required a bean of type 'api.dataBase.basic.apiDatabase.Interface.TopicRepository' that could not be found."
I read that this error can occur because of componentScan is failing for poor annotation of the class or poor package layout.
Layout of my java packages
lay out of my project
My classes are the following;
package api.dataBase.basic.apiDatabase;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication ()
public class ApiDatabaseApplication {
public static void main(String[] args) {
SpringApplication.run(ApiDatabaseApplication.class, args);
}
}
Topic.java
package api.dataBase.basic.apiDatabase.Models;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class Topic {
#Id
private String id;
private String name;
private String description;
//private Address address;
public Topic(final String id, final String name, final String description) {
this.id = id;
this.name = name;
this.description = description;
}
public Topic() {
}
#Id
public String getId() {
return id;
}
public void setId(final String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(final String description) {
this.description = description;
}
}
TopicRepository.java
package api.dataBase.basic.apiDatabase.Interface;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import api.dataBase.basic.apiDatabase.Models.Topic;
#Repository
public interface TopicRepository extends CrudRepository <Topic, String>{
}
TopicService.java
package api.dataBase.basic.apiDatabase.Models;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import api.dataBase.basic.apiDatabase.Interface.TopicRepository;
#Service
public class TopicService {
#Autowired
private TopicRepository topicRepository;
private List<Topic> Oldtopics = new ArrayList<>(Arrays.asList(
new Topic("1001", "test", "hello 1"),
new Topic("1002", "hello", "hello 2")
));
public List<Topic> getTopics() {
List<Topic> topics = new ArrayList<>();
topicRepository.findAll().forEach(topics::add);
return topics;
}
public Topic getTopic(String id) {
return Oldtopics.stream().filter(t -> t.getId().equals(id)).findFirst().get();
}
public void addTopic(final Topic topic) {
topicRepository.save(topic);
}
public void updateTopic(final Topic topic, final String id) {
for (int i = 0; i < Oldtopics.size(); i++) {
if (Oldtopics.get(i).getId().equals(id)) {
Oldtopics.set(i, topic);
return;
}
}
}
public void deleteTopic(String id) {
Oldtopics.removeIf(t -> t.getId().equals(id));
}
public void deleteTopic(final String[] id) {
for (int i = 0; i < Oldtopics.size(); i++) {
for (String ids : id) {
if (Oldtopics.get(i).getId().equals(ids)) {
Oldtopics.remove(i);
}
}
}
}
}
Any help will be appreciated.
Full Stack Trace.
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-11-21 19:18:05.350 ERROR 4192 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Field topicRepository in api.dataBase.basic.apiDatabase.Models.TopicService required a bean of type 'api.dataBase.basic.apiDatabase.Interface.TopicRepository' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'api.dataBase.basic.apiDatabase.Interface.TopicRepository' in your configuration.
POM:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>api.dataBase.basic</groupId>
<artifactId>apiDatabase</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>apiDatabase</name>
<description>API project with JPA database</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>org.apache.derby</groupId>
<artifactId>derby</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
This can be the case for missed configuration and thus messed component scan.
I'd suggest that you should add 'Config.java' with following content to your source root (src/main/java)
#Configuration
#EnableJpaRepositories
class Config {
}
I have a Spring/Boot REST controller which I inject a repository into like so:
package com.example.schooltimetable.controllers;
import com.example.schooltimetable.models.entities.StudentEntity;
import com.example.schooltimetable.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
#RestController
#CrossOrigin
#RequestMapping("student")
public class StudentController {
private final StudentRepository studentRepository;
#Autowired
public StudentController(StudentRepository studentRepository) {
this.studentRepository = studentRepository;
}
#RequestMapping(value = "/getAll", method = RequestMethod.GET)
public Iterable<StudentEntity> getAllStudents() {
return this.studentRepository.findAll();
}
}
The problem I'm facing is that whenever i start my application it throws the following error:
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in com.example.schooltimetable.controllers.StudentController required a bean of type 'com.example.schooltimetable.repository.StudentsRepository' that could not be found.
Action:
Consider defining a bean of type 'com.example.schooltimetable.repository.StudentsRepository' in your configuration.
Process finished with exit code 1
I faced this issue before when trying to find an Entity in another class, I fixed this by using the #ComponentScan() annotation in Application.java, however, it doesn't work to fix this issue.
My main application file looks like this:
SchoolTimetableApplication
package com.example.schooltimetable;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
#ComponentScan({
"com.example.schooltimetable.controllers",
"org.springframework.stereotype",
"com.example.schooltimetable.repository",
})
public class SchoolTimetableApplication {
public static void main(String[] args) {
SpringApplication.run(SchoolTimetableApplication.class, args);
}
}
And my repository looks like this:
StudentRepository
package com.example.schooltimetable.repository;
import com.example.schooltimetable.models.entities.StudentEntity;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
#Repository
#Component
public interface StudentRepository extends CrudRepository<StudentEntity, Long> { }
The StudentEntity referenced in the repository:
package com.example.schooltimetable.models.entities;
import com.example.schooltimetable.models.constants.StudentEntityConstants;
import com.example.schooltimetable.models.constants.TimetableEntityConstants;
import org.springframework.lang.NonNull;
import javax.persistence.*;
import java.util.UUID;
#Entity
#Table(name = StudentEntityConstants.TABLE_NAME)
public class StudentEntity {
#Id
#Column(name = StudentEntityConstants.ID)
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(name = StudentEntityConstants.FIRST_NAME)
#NonNull
private String firstName;
#Column(name = StudentEntityConstants.LAST_NAME)
#NonNull
private String lastName;
#Column(name = StudentEntityConstants.REFERENCE)
#NonNull
#GeneratedValue(strategy = GenerationType.AUTO)
private UUID reference;
#OneToOne(targetEntity = TimeTableEntity.class)
#JoinColumn(name = TimetableEntityConstants.REFERENCE)
private TimeTableEntity timeTable;
public long getId() {
return this.id;
}
public void setId(long id) {
this.id = id;
}
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public UUID getReference() {
return this.reference;
}
public void setReference(UUID reference) {
this.reference = reference;
}
public TimeTableEntity getTimeTable() {
return this.timeTable;
}
}
And my POM file:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>school-timetable</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>school-timetable</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-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</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.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>2.3.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Is there something I've done wrong? I'm very new to Spring/Boot. An interesting note with this issue is that if I remove
#ComponentScan({
"com.example.schooltimetable.controllers", <---- This
"org.springframework.stereotype",
"com.example.schooltimetable.repository",
})
Then the application loads but the controller will throw a 404 when trying to hit: http://localhost:8080/student/getAll
EDIT!!!
There was a few things wrong with the application at this point.
Firstly, the POM file needed updating
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>school-timetable</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>school-timetable</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-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</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.data</groupId>
<artifactId>spring-data-commons</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>commons-configuration</groupId>
<artifactId>commons-configuration</artifactId>
<version>1.9</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</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>
Secondly, the MAIN CLASS
package com.example.schooltimetable;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#SpringBootApplication
#PropertySource("classpath:application.properties")
#EntityScan("com.example.schooltimetable.models.entities")
#EnableJpaRepositories("com.example.schooltimetable.repository")
public class SchoolTimetableApplication {
public static void main(String[] args) {
SpringApplication.run(SchoolTimetableApplication.class, args);
}
}
There were also things wrong with the entities when joining columns: They should be set to read and write: false
package com.example.schooltimetable.models.entities;
import com.example.schooltimetable.models.constants.StudentEntityConstants;
import com.example.schooltimetable.models.constants.TimetableEntityConstants;
import org.springframework.lang.NonNull;
import javax.persistence.*;
import java.util.UUID;
#Entity
#Table(name = StudentEntityConstants.TABLE_NAME)
public class StudentEntity {
#Id
#Column(name = StudentEntityConstants.ID)
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(name = StudentEntityConstants.FIRST_NAME)
#NonNull
private String firstName;
#Column(name = StudentEntityConstants.LAST_NAME)
#NonNull
private String lastName;
#Column(name = StudentEntityConstants.REFERENCE)
#GeneratedValue(strategy = GenerationType.AUTO)
private UUID reference;
#OneToOne(targetEntity = TimeTableEntity.class)
#JoinColumn(name = TimetableEntityConstants.REFERENCE, updatable = false, insertable = false)
private TimeTableEntity timeTable;
public long getId() {
return this.id;
}
public void setId(long id) {
this.id = id;
}
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public UUID getReference() {
return this.reference;
}
public void setReference(UUID reference) {
this.reference = reference;
}
public TimeTableEntity getTimeTable() {
return this.timeTable;
}
}
Thanks to #Abhinaba Chakraborty for pointing me in the right direction
First of all , you don't need a component scan with the annotation SpringBootApplication in place. Spring automatically scans all components annotated with Component,Service,RestController,Respository,Configuration etc. and creates the Beans.
The request mapping annotation value in StudentController should be prefixed with "/" eg. #RequestMapping("/student") - Although it has nothing to do with dependency injection . But this is the reason why you are getting a 404 at http://localhost:8080/student/getAll
In the repository interface, just use #Repository annotation instead of having both #Repository and #Component annotations.
Also I dont see a data-jpa dependency defined in your POM.xml yet How are you importing the org.springframework.data.repository.CrudRepository in your repository. You need that dependency.
As far as directory structure concerned, it looks OK ,but please verify:
FIXED!!!
So the problem was with the way I'd implemented the #OneToOne relationship between the student and the Timetable.
The edit in the question was a work around as stated by #M.Deinum. The correct solution was to first clean up the relationship between Student and Timetable, like so:
StudentEntity
package com.example.schooltimetable.models.entities;
import com.example.schooltimetable.models.constants.StudentEntityConstants;
import org.springframework.lang.NonNull;
import javax.persistence.*;
#Entity
#Table(name = StudentEntityConstants.TABLE_NAME)
public class StudentEntity {
#Id
#Column(name = StudentEntityConstants.ID)
private long id;
#Column(name = StudentEntityConstants.FIRST_NAME)
#NonNull
private String firstName;
#Column(name = StudentEntityConstants.LAST_NAME)
#NonNull
private String lastName;
#OneToOne(mappedBy = "student", cascade = CascadeType.ALL) // no need to join the columns on the Student.
private TimeTableEntity timeTable;
public long getId() {
return this.id;
}
public void setId(long id) {
this.id = id;
}
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public TimeTableEntity getTimeTable() {
return this.timeTable;
}
public void setTimeTable(TimeTableEntity timeTable) { this.timeTable = timeTable; }
}
TimeTableEntity
package com.example.schooltimetable.models.entities;
import com.example.schooltimetable.models.constants.TimetableEntityConstants;
import javax.persistence.*;
import java.io.Serializable;
import java.util.LinkedHashSet;
import java.util.Set;
#Entity
#Table(name = TimetableEntityConstants.TABLE_NAME)
public class TimeTableEntity implements Serializable {
#Id
#Column(name = TimetableEntityConstants.ID)
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#OneToOne
#MapsId // <-- This automatically knows to join by the student ID column
private StudentEntity student;
#OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private final Set<ModuleEntity> modules = new LinkedHashSet();
public long getId() {
return this.id;
}
public void setId(long id) {
this.id = id;
}
public void setStudent(StudentEntity student) {
this.student = student;
}
public Set<ModuleEntity> getModules() {
return this.modules;
}
public void setModules(ModuleEntity module) {
this.modules.add(module);
}
}
Now, the next few refactors, I could just do, I don't know why it worked all of a sudden but I have a feeling it was to do with the bad entity setup.I was able to remove the
#EntityScan("com.example.schooltimetable.models.entities") & #EnableJpaRepositories("com.example.schooltimetable.repository")
Annotations from my main class, and I was also able to remove a lot of #Scope and #Component annotations from my code. My main class now looks like this:
SchoolTimetableApplication
package com.example.schooltimetable;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.PropertySource;
#SpringBootApplication
#PropertySource("classpath:application.properties")
public class SchoolTimetableApplication {
public static void main(String[] args) {
SpringApplication.run(SchoolTimetableApplication.class, args);
}
}
Much better! I also have data pulling through for the relationships rather than null (another issue I was facing).
i am new to springframework technology and i am struggling to solve the following error.
the project starts successfully, i get the following error when the postman is executed
can anyone hel me solving the issue.
i guess i have pasted the important classes, i can post the whole code if needed
usercontroller
package com.appsdeveloper.blog.app.ws.controller;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.appsdeveloper.blog.app.ws.service.UserService;
import com.appsdeveloper.blog.app.ws.shared.dto.UserDto;
import com.appsdeveloper.blog.app.ws.ui.model.request.UserDetailsRequestModel;
import com.appsdeveloper.blog.app.ws.ui.model.response.UserRest;
#RestController
#RequestMapping("users")//http://localhost:8586/users
public class UserController{
#Autowired(required=true)//the bracket added from the internet
UserService userService;
//#Autowired
//private UserRepository userRepository;
#PostMapping
public UserRest createUser(#RequestBody UserDetailsRequestModel userDetails){
UserRest returnValue = new UserRest();
UserDto userDto = new UserDto();
BeanUtils.copyProperties(userDetails, userDto);
UserDto createdUser = userService.createUser(userDto);
BeanUtils.copyProperties(createdUser, returnValue);
return returnValue;
}
#DeleteMapping
public String deleteUser(){
return "delete user was called";
}
#GetMapping
public String getUser(){
return "get User was called";
}
#PutMapping
public String updateUser(){
return "update user was called";
}
}
UserEntity
package com.appsdeveloper.blog.app.ws.io.entity;
import java.io.Serializable;
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="users", schema = "photo_app" )//name of table created to store information
public class UserEntity implements Serializable {
private static final long serialVersionUID = 7401188933477397731L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="Id")
private long id;
#Column(name= "userId", nullable = false)
private String userId;
#Column(name = "firstName", nullable = false, length = 50)//the length is important to avoid default size 0f 250 varchar
private String firstName;
#Column(name = "lastName", nullable = false, length = 50)
private String lastname;
#Column(name = "email", length = 50)
private String email;
#Column(name = "password", nullable = false)
private String encryptedPassword;
//#Column(name = "emailVerificationToken", nullable = false)
private String emailVerificationToken;
#Column(name = "emailVerificationStatus", nullable=false)
private Boolean emailVerificationStatus = false;
public long getId() {
return id;
}
public String getUserId() {
return userId;
}
public String getFirstName() {
return firstName;
}
public String getLastname() {
return lastname;
}
public String getEmail() {
return email;
}
public String getEncryptedPassword() {
return encryptedPassword;
}
public String getEmailVerificationToken() {
return emailVerificationToken;
}
public Boolean getEmailVerificationStatus() {
return emailVerificationStatus;
}
///////////////////////////////////////////
public void setId(long id) {
this.id = id;
}
public void setUserId(String userId) {
this.userId = userId;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public void setEmail(String email) {
this.email = email;
}
public void setEncryptedPassword(String encryptedPassword) {
this.encryptedPassword = encryptedPassword;
}
public void setEmailVerificationToken(String emailVerificationToken) {
this.emailVerificationToken = emailVerificationToken;
}
public void setEmailVerificationStatus(boolean emailVerificationStatus) {
this.emailVerificationStatus = emailVerificationStatus;
}
}
application.property
spring.datasource.username=root
spring.datasource.password=
spring.datasource.url=jdbc:mysql://localhost:3306/photo_app
server.port=8586
spring.jpa.hibernate.use-new-id-generator-mappings=false
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.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.appsdeveloperblog-app-ws</groupId>
<artifactId>mobile-app-ws</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mobile-app-ws</name>
<description>Demo project for Spring Boot</description>
<properties><!--</tiles:insertDefinition>-->
<!-- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>-->
<java.version>1.8</java.version>
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
</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>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.0.0.Alpha4</version>
<type>pom</type>
</dependency>
<!-- https://mvnrepository.com/artifact/joda-time/joda-time -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jadira.usertype/usertype.core -->
<dependency>
<groupId>org.jadira.usertype</groupId>
<artifactId>usertype.core</artifactId>
<version>7.0.0.CR1</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>
</project>
error code
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: The database returned no natively generated identity value; nested exception is org.hibernate.HibernateException: The database returned no natively generated identity value] with root cause
org.hibernate.HibernateException: The database returned no natively generated identity value
You have to auto-increment your id column in your database.
Something like this: id INT NOT NULL AUTO_INCREMENT
package com.loginregister.loginregister.entities;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
#Entity
public class Role {
#Id
private String name;
#ManyToMany(mappedBy = "roles")
private List<User> users;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
public Role(String name, List<User> users) {
this.name = name;
this.users = users;
}
public Role() {
}
public Role(String name) {
this.name = name;
}
}
Role.java
package com.loginregister.loginregister.entities;
import javax.persistence.*;
import javax.validation.constraints.NotEmpty;
import javax.persistence.GeneratedValue;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
#Entity
public class Task {
#Id
#GeneratedValue
private Long id;
#NotEmpty
private String date;
#NotEmpty
private String startTime;
#NotEmpty
private String stopTime;
#NotEmpty
private String Description;
#ManyToOne
#JoinColumn(name = "USER_EMAIL")
private User user;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getStartTime() {
return startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
public String getStopTime() {
return stopTime;
}
public void setStopTime(String stopTime) {
this.stopTime = stopTime;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Task(String date, String startTime, String stopTime, String description, User user) {
this.date = date;
this.startTime = startTime;
this.stopTime = stopTime;
Description = description;
this.user = user;
}
public Task(String date, String startTime, String stopTime, String description) {
this.date = date;
this.startTime = startTime;
this.stopTime = stopTime;
Description = description;
}
public Task() {
}
}
Task.java
package com.loginregister.loginregister.entities;
import org.springframework.scheduling.config.Task;
import javax.persistence.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import java.util.List;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
#Entity
public class User {
#Id
#Email
#NotEmpty
#Column(unique = true)
private String email;
#NotEmpty
private String name;
#Size(min = 4)
private String password;
#OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
private List<Task> tasks;
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "USER_ROLES",joinColumns = {
#JoinColumn(name = "USER_EMAIL", referencedColumnName = "email")
},inverseJoinColumns = {#JoinColumn(name = "ROLE_NAME", referencedColumnName = "name")})
private List<Role> roles;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public List<Task> getTasks() {
return tasks;
}
public void setTasks(List<Task> tasks) {
this.tasks = tasks;
}
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
public User(String email, String name, String password) {
this.email = email;
this.name = name;
this.password = password;
}
public User() {
}
}
User.java
package com.loginregister.loginregister.repositories;
import com.loginregister.loginregister.entities.Role;
import org.springframework.data.jpa.repository.JpaRepository;
public interface RoleRepository extends JpaRepository<Role, String>{
}
RoleRepository.java
package com.loginregister.loginregister.repositories;
import com.loginregister.loginregister.entities.Task;
import org.springframework.data.jpa.repository.JpaRepository;
public interface TaskRepository extends JpaRepository<Task, Long> {
}
TaskRepository.java
package com.loginregister.loginregister.repositories;
import com.loginregister.loginregister.entities.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, String> {
}
UserRepository
package com.loginregister.loginregister;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class LoginRegisterApplication {
public static void main(String[] args) {
SpringApplication.run(LoginRegisterApplication.class, args);
}
}
LoginRegisterApplication.java
spring.datasource.url=jdbc:mysql://localhost:3306/SpringAuth?useSSL=false
spring.datasource.username=root
spring.datasource.password=****
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create-drop
application.properties
http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
<groupId>com.LoginRegister</groupId>
<artifactId>login-register</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>login-register</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-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-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>
</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>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.0.7.Final</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
pom.xml
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 2.941 s <<< FAILURE! - in com.loginregister.loginregister.LoginRegisterApplicationTests
[ERROR] contextLoads(com.loginregister.loginregister.LoginRegisterApplicationTests) Time elapsed: 0.005 s <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: #OneToOne or #ManyToOne on com.loginregister.loginregister.entities.Task.user references an unknown entity: com.loginregister.loginregister.entities.User
Caused by: org.hibernate.AnnotationException: #OneToOne or #ManyToOne on com.loginregister.loginregister.entities.Task.user references an unknown entity: com.loginregister.loginregister.entities.User
This can be resolved by :
Hibernate jpa 2.1 jar which is a part of spring-boot-started-data-jpa. Remove dependencies in .m2 folder and again report pom.xml
OR<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
Add Repository Annotation