i have been trying to fix this issue for the past 2 days and cannot seem to fix them
here is the error code spring gives me:
2023-12-16T23:43:15.665+01:00 WARN 22472 --- [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'addressController' defined in file [C:\target\classes\com\factory\ordersystem\controller\AddressController.class]: Unsatisfied dependency expressed through constructor parameter 0: Error creating bean with name 'addressService' defined in file [C:\target\classes\com\factory\ordersystem\service\AddressService.class]: Unsatisfied dependency expressed through constructor parameter 0: Error creating bean with name 'addressRepository' defined in com.factory.ordersystem.repository.AddressRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Not a managed type: class com.factory.ordersystem.entities.Address
it seems to be something is wrong in my Address files but i cant see why, i will paste the code here:
AddressController:
package com.factory.ordersystem.controller;
import com.factory.ordersystem.entities.Address;
import com.factory.ordersystem.service.AddressService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("/addresses")
public class AddressController {
private final AddressService addressService;
public AddressController(AddressService addressService) {
this.addressService = addressService;
}
@GetMapping("/{id}")
public ResponseEntity<Address> getAddressById(@PathVariable Long id) {
Optional<Address> address = addressService.getAddressById(id);
return address != null ?
(ResponseEntity<Address>) ResponseEntity.ok() :
ResponseEntity.notFound().build();
}
@GetMapping
public ResponseEntity<List<Address>> getAllAddresses() {
List<Address> addresses = addressService.getAllAddresses();
return ResponseEntity.ok(addresses);
}
@PostMapping
public ResponseEntity<Address> createAddress(@RequestBody Address address) {
Address createdAddress = addressService.createAddress(address);
return ResponseEntity.status(HttpStatus.CREATED).body(createdAddress);
}
@PutMapping("/{id}")
public ResponseEntity<Address> updateAddress(@PathVariable Long id, @RequestBody Address updatedAddress) {
Optional<Address> updated = Optional.ofNullable(addressService.updateAddress(id, updatedAddress));
return updated.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteAddress(@PathVariable Long id) {
boolean deleted = addressService.deleteAddress(id);
return deleted ?
ResponseEntity.noContent().build() :
ResponseEntity.notFound().build();
}
}
Adress Entity file
package com.factory.ordersystem.entities;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
@Entity
public class Address {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank
private String street;
@NotBlank
private String city;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "customer_id")
private Customer customer;
public Address() {
}
public Address(String street, String city) {
this.street = street;
this.city = city;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
@Override
public String toString() {
return "Address{" +
"id=" + id +
", street='" + street + '\'' +
", city='" + city + '\'' +
'}';
}
}
address repository
package com.factory.ordersystem.repository;
import com.factory.ordersystem.entities.Address;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface AddressRepository extends JpaRepository<Address, Long> {
}
AddressService
package com.factory.ordersystem.service;
import com.factory.ordersystem.entities.Address;
import com.factory.ordersystem.exception.ResourceNotFoundException;
import com.factory.ordersystem.repository.AddressRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class AddressService {
private final AddressRepository addressRepository;
@Autowired
public AddressService(AddressRepository addressRepository) {
this.addressRepository = addressRepository;
}
public List<Address> getAllAddresses() {
return addressRepository.findAll();
}
public Optional<Address> getAddressById(Long id) {
return addressRepository.findById(id);
}
public Address createAddress(Address address) {
return addressRepository.save(address);
}
public Address updateAddress(Long id, Address updatedAddress) {
Optional<Address> optionalAddress = addressRepository.findById(id);
if (optionalAddress.isPresent()) {
Address existingAddress = optionalAddress.get();
existingAddress.setStreet(updatedAddress.getStreet());
existingAddress.setCity(updatedAddress.getCity());
return addressRepository.save(existingAddress);
} else {
throw new ResourceNotFoundException("Address with id " + id + " not found");
}
}
public boolean deleteAddress(Long id) {
if (addressRepository.existsById(id)) {
addressRepository.deleteById(id);
return true;
} else {
return false;
}
}
}
application.properties
# DataSource Configuration
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.username=sa
spring.datasource.password=password
spring.datasource.driverClassName=org.h2.Driver
# Hibernate Configuration
spring.jpa.hibernate.ddl-auto=update
spring.jpa.open-in-view=false
# H2 Console Configuration
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
and finally 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>3.2.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.factory.ordersytem</groupId>
<artifactId>com.exam.pgr209</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>com.exam.pgr209</name>
<description>order machine backend exam</description>
<properties>
<java.version>21</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.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>javax.persistence-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version> <!-- or the latest version -->
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
any help would be insanely appreciated as it would alleviate the biggest headache of mine the past 2 weeks
I've attempted various troubleshooting steps:
Used VM Debugging. Restructured file organization. Created a new file from scratch. Watched a video tutorial on "not a managed type" error. Attempted to integrate Lombok. Compared our exam project structure with a known working project like 'vet-clinic'. Conducted extensive online research. Scrutinized for potential typographical errors. Utilized EntityScan configurations. Despite these attempts, the issue persisted.
it could be however that my lack of skill has made me do this wrong too
The issue is due to a version conflict between libraries javax-persistence (old one) and jakarta-persistence (current one). To fix it you should remove this dependency from your pom.xml
:
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>javax.persistence-api</artifactId>
<version>2.2</version>
</dependency>
After doing this and updating Maven project you will get compiler errors on import statements with javax.persistence. Just rename it to jakarta.persistence.
Similar issue is with the validation library. Remove this dependency:
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version> <!-- or the latest version -->
</dependency>
and use this one instead:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
A general advice: the best way to get the correct and up-to-date pom.xml
is to generate it using https://start.spring.io/