0

I want to connect a Spring Boot environment with a dataBase. I followwed the tutorial: https://www.youtube.com/watch?v=8SGI_XS5OPw I have a MySQL db and just want to add some test data to my database. But when I run the code with just the models and repository I get the following error: (removed some lines)

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demo' defined in com.canbus.CanBusDatabaseApplication: Unsatisfied dependency expressed through method 'demo' parameter 0: Error creating bean with name 'messageRepository' defined in com.canbus.db.repo.MessageRepository defined in @EnableJpaRepositories declared on CanBusDatabaseApplication: Not a managed type: class com.canbus.db.models.Message
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:800) ~[spring-beans-6.0.8.jar:6.0.8]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1293) ~[spring-boot-3.0.6.jar:3.0.6]
    at com.canbus.CanBusDatabaseApplication.main(CanBusDatabaseApplication.java:26) ~[classes/:na]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'messageRepository' defined in com.canbus.db.repo.MessageRepository defined in @EnableJpaRepositories declared on CanBusDatabaseApplication: Not a managed type: class com.canbus.db.models.Message
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1770) ~[spring-beans-6.0.8.jar:6.0.8]
    ... 18 common frames omitted
Caused by: java.lang.IllegalArgumentException: Not a managed type: class com.canbus.db.models.Message
    at org.hibernate.metamodel.model.domain.internal.JpaMetamodelImpl.managedType(JpaMetamodelImpl.java:181) ~[hibernate-core-6.1.7.Final.jar:6.1.7.Final]

First my code:

com.project.DemoApplication.java :

package com.project;

import java.util.Arrays;
import java.util.List;

import com.project.db.models.Message;
import com.project.db.repo.MessageRepository;

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.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@SpringBootApplication
@EnableJpaRepositories(basePackageClasses = MessageRepository.class)
@ComponentScan(basePackages = { "com.project.*" })
@EntityScan("com.project.*")
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Bean
    public CommandLineRunner demo(MessageRepository repository) {
        return (args) -> {
            List<Message> messages = Arrays.asList(
                    new Message(123456789, "truck1", "{\"speed\": 80}", 52.3667, 4.8945, System.currentTimeMillis(), System.currentTimeMillis()),
                    new Message(123456789, "truck1", "{\"speed\": 90}", 52.3667, 4.8945, System.currentTimeMillis(), System.currentTimeMillis()),
                    new Message(987654321, "truck2", "{\"speed\": 60}", 52.3667, 4.8945, System.currentTimeMillis(), System.currentTimeMillis())
            );
            repository.saveAll(messages);
        };
    }
}

com.project.db.models.Message.java:

package com.project.db.models;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.SEQUENCE;

@Entity(name = "message")
@Table(
        name = "message",
        uniqueConstraints = {
                @UniqueConstraint(name = "device_IMEI_device", columnNames = "device_IMEI")
        })
public class Message {
    public Message(Integer device_IMEI, String connected_truck, String data_json, double latitude, double longitude, long data_received, long data_send) {
        this.device_IMEI = device_IMEI;
        this.connected_truck = connected_truck;
        this.data_json = data_json;
        this.latitude = latitude;
        this.longitude = longitude;
        this.data_received = data_received;
        this.data_send = data_send;
    }
    public Message (){}

    @Id
    @GeneratedValue(
            strategy = SEQUENCE,
            generator = "message_sequence"
    )
    @Column(name = "data_pk")
    private Integer data_pk;
    @Column(name = "device_IMEI")
    private Integer device_IMEI;
    @Column(name = "connected_truck")
    private String connected_truck;
    @Column(name = "data_json")
    private String data_json;
    @Column(name = "latitude")
    private double latitude;
    @Column(name = "longitude")
    private double longitude;
    @Column(name = "data_received")
    private long data_received;
    @Column(name = "data_send")
    private long data_send;

/* getters and setters for the data */

    @Override
    public String toString() {
        return "Message{" +
                "data_pk=" + data_pk +
                ", device_IMEI=" + device_IMEI +
                ", connected_truck='" + connected_truck + '\'' +
                ", data_json='" + data_json + '\'' +
                ", latitude=" + latitude +
                ", longitude=" + longitude +
                ", data_received=" + data_received +
                ", data_send=" + data_send +
                '}';
    }
}

com.project.db.repo.MessageRepository.java

package com.project.db.repo;

import com.project.db.models.Message;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.data.jpa.repository.JpaRepository;

@EntityScan("com.project.db.models")
public interface MessageRepository extends JpaRepository <Message, Integer> {
}

application.properties

spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/PROJECT_NAME
spring.datasource.username=USERNAME_HERE
spring.datasource.password=PASSWORD_HERE
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.show-sql: true

Last the pom.xml 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>3.0.6</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>
  <groupId>com.project</groupId>
  <artifactId>project-database</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>project-database</name>
  <description>Demo project for Spring Boot Spring Data JPA</description>
  <properties>
    <java.version>20</java.version>
  </properties>
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

    <dependency>
      <groupId>com.mysql</groupId>
      <artifactId>mysql-connector-j</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>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>19</source>
          <target>19</target>
        </configuration>
      </plugin>
    </plugins>
  </build>

</project>

When searching for this error I have found numerous solutions, but all of them did not fix it.

  • @EnableJpaRepositories(basePackageClasses = MessageRepository.class)
  • @ComponentScan(basePackages = { "com.project.*" })
  • @EntityScan("com.project.*")

I will be trying another PC later today but that should not fix the problem I hope.

Jesse
  • 1
  • 2
  • `@EntityScan` in your `MessageRepository` is plainly wrong. Remove it. Your `@EntityScan` in your main class should receive the route to the package where all your classes annotated with `@Entity` are. It should be `com.project.db.models`. – Jetto Martínez May 04 '23 at 16:05
  • Thanks for your reaction! Just to clarify, `@EntityScan({"com.project.db.models", "com.project.db.repo"})` or `@Entity(name = "com.project.db.models")` in the `Message.java`? I have tried both but still got the same error: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'commandLineRunner' defined in Application: Unsatisfied dependency expressed through method 'CmdLRunner' parameter 0: Error creating bean with name 'messageRepo' defined in MessageRepo defined in @EnableJpaRepositories declared on Application: Not a managed type: class Message – Jesse May 05 '23 at 07:48
  • The `@EntityScan` in your `DemoApplication.java` should have the path to the package where the `@Entity`-ies classes are (As it is in the repository, actually). The `@EntityScan` in your `MessageRepository.java` should not be there, so remove it. The `@ComponentScan` in `DemoApplication.java` should not be necessary either. I'd define the path to the package where the interfaces extending `JpaRepository` are in your `@EnableJpaRepositories` too, but it shouldn't be a problem. Also, totally as a side, irrelevant note, in Java, we use loweCammelCase as a convention. – Jetto Martínez May 05 '23 at 15:24

1 Answers1

0

Question answered here. Spring boot - Not a managed type

jpa entity is not a managed type

Root cause if experienced in recent versions of Sp:

In the recent version of Springboot and JDK, this error is a result of the "Javax" namespace used in Java EE being replaced with the "Jakarta" namespace in Jakarta EE.

Fix

Therefore, in a newer version of Spring Version and JDK. e.g. Spring 6+ and JDK 17+, you would now need to replace javax.persistence.Entity when with jakarta.persistence.Entity to resolve the jpa entity is not a managed type error