java – How can I get list of an entity according to associated entity id in Spring JPA?

I have an library entity and this library entity has one-to-many relation with book entity.

How can I write the query for library repository to get Library list by book id?

Thanks

My entities:

@Entity
@Table(name = "LIBRARY", schema = LBRY)
public class Library {

    @Id
    private Long id;


    @OneToMany(cascade=CascadeType.ALL)
    @JoinColumn(name="LIBRARYID")
    private List<Book> books;

   //Getter/Setter functions

}

@Entity
@Table(name = "BOOK", schema = LBRY)
public class Book {

    @Id
    private Long id;


    @ManyToOne
    private Library library;

    //Getter/Setter functions
}

java – Relación OneToOne en Springboot 2.3 y JPA: Qué anotaciones usar?

hace muchísimo tiempo que no trabajo con BBDD relacionales y me estoy volviendo loco estos días, y seguro que mi pregunta os va a parecer de lo más trivial.

Tengo dos tablas:

introducir la descripción de la imagen aquí

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(256) NOT NULL DEFAULT '',
  `password` varchar(256) NOT NULL,
  `enabled` tinyint(1) NOT NULL DEFAULT '0',
  `created` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `username_unique_idx` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=latin1;

CREATE TABLE `users_confirmation` (
  `users_confirmation_id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `confirmationcode` varchar(64) NOT NULL DEFAULT '',
  `created` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `expires` int(11) unsigned DEFAULT '86400',
  PRIMARY KEY (`users_confirmation_id`),
  UNIQUE KEY `username_confirmation_idx` (`user_id`),
  CONSTRAINT `username_confirmation_fk` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=latin1;

Tienen una relación uno a uno, es decir, un usuario sólo puede tener código de confirmación, en esta última tabla existe una FK al id del usuario, y la tabla users no tiene ninguna referencia hacia la tabla de confirmación.

A partir de ahí, he probado todo, no pongo código porque os volvería locos, pero no tengo forma de que al guardar un usuario pueda grabar también la confirmación y después pueda buscar un usuario por el código de confirmación sin tener que hacer dos consultas a la BD.

Sabéis qué anotaciones debo usar? Si creéis que incluso estoy planteando mal la relación a nivel de BD decídmelo sin tapujos. Llevo demasiado tiempo trabajando con BBDD No SQL y se me está haciendo duro volver a las relacionales.

Muchas gracias por anticipado!!

java – How to assign or read JSON data returned from a Query to postgresql data into JPA Repository. row_to_json select query

I have the below code situated in the JpaRepository on a spring boot project, the query return a JSON

I am getting the Error: Resolved (org.springframework.orm.jpa.JpaSystemException: No Dialect mapping for JDBC type: 1111; nested exception is org.hibernate.MappingException: No Dialect mapping for JDBC type: 1111)*

  String queryString = "SELECT row_to_json(fc)n" +
          " FROM ( SELECT 'FeatureCollection' As type, array_to_json(array_agg(f)) As featuresn" +
          " FROM (SELECT 'Feature' As typen" +
          "    , ST_AsGeoJSON(lg.column1) As geometryn" +
          "    , row_to_json((column2, column3)) As propertiesn" +
          "   FROM public.table As lg ) As f )  As fc;";


  @Query(value=queryString, nativeQuery=true) 
  Json getData(@Param("id") Long id);

The Query returns a json Object, and i want to assign or be able to read it into java.

Please bare with me with the way i asked the question, i am new here.

java – Dúvida sobre a relaçao ManyToMany JPA

Olá, possuo duas classes na minha API, pokemon e type, e elas possuem uma relação ManyToMany entre si. Quando eu executo os métodos nos meus controllers para buscar todos os pokemons ou todos os types acaba gerando uma recursão infinita.

Depois de pesquisar um pouco vi que sempre que se usa um relacionamento bidirecional você precisa anotar um lado da relação para que ela seja ignorada na hora do jackson fazer a serialização. Porém após anotar o atributo da classe Type com @JsonIgnore, o meu método de buscar todos os Types não trás os pokemons correspondentes a cada type no json e o método de buscar todos os pokemons funciona corretamente.

Alguém teria uma solução para evitar a recursão infinita na serialização e ao mesmo tempo possibilitar que ambos os lados da relação consigam serializar os seus atributos?

Pokemon:

@Getter @Setter @NoArgsConstructor @AllArgsConstructor
@Entity
@Table(name="pokemons")
public class Pokemon implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;
    
    private String name;
    
    private String url;
    
    private String img;
    
    @ManyToMany
    @JoinTable(
        name = "pokemon_types",
        joinColumns = @JoinColumn(name = "pokemon_id"),
        inverseJoinColumns = @JoinColumn(name = "type_id"))
    private Set<Type> types;
    
}

Type:

@Setter @Getter @NoArgsConstructor @AllArgsConstructor
@Entity
@Table(name="types")
public class Type implements Serializable{

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;
    
    private String name;
    
    @JsonIgnore
    @ManyToMany(mappedBy = "types")
    Set<Pokemon> pokemons;

}

Implementing a user ID system like Discords for a web app using Java Spring, JPA, Hibernate and MySQL

I’m trying to create a web application with a forum and user profile along with other functions. However I’m thinking about how I might implement an ID for each user. The best way I’ve seen other applications do it so far is like Discords, which is something I’d like to emulate in my own app.

Here is a link to Discords Wikipedia page if you’re not sure what it is.

In Discords approach every user has an assigned 4 digit number in the form of #5456 for example. There is also a user chosen username that can be always be changed. This username is prepended before the assigned number so the full ID has the form of something like user#7853. See the screenshot below for a real world example:

enter image description here

I like this approach as it allows the user to change their name to a username that is already taken.
However there are few things that are confusing me, firstly Discord has way more than 9999 users yet each user has a 4 digit ID. Secondly I’ve seen some users with duplicate numbers, usually that of #0001, which I think is what you get after buying some premium feature.

I have no idea how this works since I assumed the assigned numbers had to be unique. The only way I can think of both of these problems being solved is that the username and number are tied into a single ID, making both the username and number the factors that make the ID unique. But I’m not entirely sure if this is how it works.

If we assume that the latter is true where the both the name and number make up the entire ID, how might I be able to implement that into a MySQL user table using Java Spring JPA and Hibernate? At the moment I have this entity class for a user:

@Entity
public class User
{
    @OneToOne(mappedBy = "user", cascade = CascadeType.ALL)
    private UserProfile userProfile;

    @OneToOne(mappedBy = "user", cascade = CascadeType.ALL)
    private UserPosts userPosts;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    private long points;
    private String email, username, password;
    private Date dateJoined;

    public User() { }

    // getters and setters
}

I have an ID of type long, but I think this would need to be changed into a new type that can be composed of both a string and a number. So I thought about creating a new ID object that can have both a string and a number.

Would I be able to store an object like this as an ID in a MySQL table and would this be the right approach by creating an ID object? Are my assumptions about how Discords user ID system works correct?

Any insight on the matter would be appreciated.

Thanks.

java – How to achieve both: clean (hexagonal) architecture with JPA goodies?

How do I achieve both goodies of two things at the same time writing Java Spring Application:

  1. Clean Architecture
  2. JPA goodies (@Transactional, Optimistic Locking, dirty checking, etc).

I like the idea of database / orm framework being a not-important detail that can be easily replaced, but I’m not sure how to effectively implement it.

Let’s say potentially I want to replace JPA/Hibernate with jOOQ or Spring Data JDBC.

But at the same time, I want to have support for transactions, dirty checking, etc.

How should I process use case in a application / domain layer so it can have merits of two worlds?

I don’t have to mention that with clean architecture I have to convert domain type to entity type every time I speak with database.

Any good answers appreciated much 🙏

java – JPA no respeta tamaño de columna de tipo VARCHAR FOR BIT DATA

Estoy probando almacenar una cadena encriptada en DB2 que puede tener una longitud de hasta 8000 caracteres, si hago el INSERT directamente en el manejador funciona correctamente, el problema está cuando se intenta insertar un registro desde la aplicación, el error que me marca indica que la cadena excede el tamaño permitido pero la cadena solo tiene 280 caracteres.

El campo fue declarado la siguiente manera:

ENCRYPTED_DATA VARCHAR(8000) FOR BIT DATA NOT NULL,

Y en JAVA se consume con un @ColumnTransformer

@ColumnTransformer(
    forColumn = "ENCRYPTED_DATA",
    read = "DECRYPT_CHAR(ENCRYPTED_DATA, 'PASSS')",
    write = "ENCRYPT(?, 'PASS')")
  @Column(name = "ENCRYPTED_DATA", length = 8000, columnDefinition = "VARCHAR(8000) FOR BIT DATA")
  private String encryptedData;

Si se quita la etiqueta @ColumnTransformer, el error con el tamaño desaparece.

hibernate: JPA @Transient field is cleared before @PostUpdate

My problem is similar to other posts like:

JPA @Transient fields are cleared before @PreUpdate method is called

JPA transient fields with callback methods

but the solution proposed by other users doesn't work for me and I don't know what I'm doing wrong. My flow is as follows:
When I run an update, the audDescription field is populated but when that field is received by the auditListener class it is null. I have added the updatedtable = true or false property but the field is still null. When I run an insert, the first time it works fine.

This is my class of service:

@Transactional
public void update(ParametrosDTO paramDTO) {
   try {
    Parametros entity = paramDao.findById(paramDTO.getIdParametro()).orElse(null);

    Parametros entity2 = modelMapper.map(paramDTO, Parametros.class);
    entity2.setAudDescription(
            String.format(EnumAuditDescription.ALTA_PARAMETROS.getDescription(), paramDTO.getNombre()));
    paramDao.save(entity2);
} catch (DataAccessException e) {
    if (e.getCause().getCause().getMessage().contains("NAME_TEC_IDX")) {
        log.error("Registro Duplicado");
        throw new TechnicalException("Registro Duplicado");
    }
    log.error("Error tecnico al insertar el nuevo parametro {}", e.getMessage());
    throw new TechnicalException("Error tecnico al insertar el nuevo parametro", e);
} catch (Exception e) {
    log.error("Error generico al grabar el nuevo parametro {}", e.getMessage());
    throw new BusinessException("Error generico en la insercion del nuevo parametro", e);
}}

This is the feature class and the transient field is "audDescription"

@Data
@Entity
@EntityListeners(AuditableListener.class)
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Parametros implements Serializable,Auditable {

 private static final long serialVersionUID = 1L;

 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 @Column(name="ID_PARAM")
 private Integer idParametro;

 @Column(name="NAME_TEC")
 private String nameTec;

 @Column(name="nombre")
 private String nombre;

 private Double valor;

 private Integer activo;

 @Transient
 private String audDescription;

 @Override
 public void setAudDescription(String audDescription) {
      this.audDescription = audDescription;   
 }

 @Override
 public String getAudDescription() {        
    return audDescription;
 }

 @Override
 public void setIdInmueble(Long idInmueble) {
  // TODO Auto-generated method stub
 }

 @Override
 public Long getIdInmueble() {
        // TODO Auto-generated method stub
   return null;
 }
 }

And this is my AuditListener class.

@Slf4j
@Component
public class AuditableListener {


@PostPersist
public void saveAudit(Auditable entity) {
 perform(entity);        
}
@PreUpdate
public void updateAudit(Auditable entity) {
 perform(entity);        
}

public void perform(Auditable entity) {
try {
    EntityManager entityManager = BeanUtil.getBean(EntityManager.class);
    Auditoria auditoria = Auditoria.builder()
            .idAud(Long.parseLong(AgdUtils.getUUID()))
            .idInmueble(entity.getIdInmueble())
            .fecha(Timestamp.valueOf(LocalDateTime.now()))
            .createdBy(getUsuario())
            .accion(entity.getAudDescription()).build();                    
    entityManager.persist(auditoria);
} catch (Exception e) {
    log.error("Error al auditar:",e.getMessage());          
}}

private String getUsuario() {
     Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
     return authentication.getName();
}}

jpa – There is no qualified bean – Kotlin spring boot

I am learning Kotlin: Springboot and CrudRepository do not work in my project.
I used all the annotations (@Repository, @Component, @ComponentScan in MainApplication.kt …)
Now I need help with this problem of Autowired and Repository not found

here it is WorkerService.kt

package com.tistory.fonercis.nins.application
import com.tistory.fonercis.nins.domain.ProjectRepository
import com.tistory.fonercis.nins.domain.Worker
import com.tistory.fonercis.nins.domain.WorkerRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
@Service
class WorkerService constructor(@Autowired private val workerRepository: WorkerRepository,
                                @Autowired private val projectRepository: ProjectRepository) {

    fun getWorkers(): ArrayList {
        val workers: ArrayList = workerRepository.findAll()
        return workers
    }
    fun getWorker(id: Long): Worker {
        val worker = workerRepository.findById(id)
        val projects = projectRepository.findAllByProjectId(id)
        worker.setProjects(projects)
        return worker
    }
    fun addWorker(worker: Worker): Worker {
        return workerRepository.save(worker)
    }
}

and here it is ProjectRepository.kt

package com.tistory.fonercis.nins.domain

import org.springframework.data.repository.CrudRepository

interface ProjectRepository : CrudRepository { //
    fun findAllByProjectId(projectId: Long): ArrayList
}

and error messages

java.lang.IllegalStateException: Failed to load ApplicationContext

    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:132)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:123)
    at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:190)
    at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:132)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:244)
    at org.springframework.test.context.junit.jupiter.SpringExtension.postProcessTestInstance(SpringExtension.java:98)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$5(ClassBasedTestDescriptor.java:337)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.executeAndMaskThrowable(ClassBasedTestDescriptor.java:342)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$6(ClassBasedTestDescriptor.java:337)
    at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
    at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175)
    at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1382)
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:482)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:472)
    at java.util.stream.StreamSpliterators$WrappingSpliterator.forEachRemaining(StreamSpliterators.java:312)
    at java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:743)
    at java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:742)
    at java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:580)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.invokeTestInstancePostProcessors(ClassBasedTestDescriptor.java:336)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.instantiateAndPostProcessTestInstance(ClassBasedTestDescriptor.java:259)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$2(ClassBasedTestDescriptor.java:252)
    at java.util.Optional.orElseGet(Optional.java:267)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$3(ClassBasedTestDescriptor.java:251)
    at org.junit.jupiter.engine.execution.TestInstancesProvider.getTestInstances(TestInstancesProvider.java:29)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$prepare$0(TestMethodTestDescriptor.java:106)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:105)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:69)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$prepare$1(NodeTestTask.java:107)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.prepare(NodeTestTask.java:107)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:75)
    at java.util.ArrayList.forEach(ArrayList.java:1257)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.util.ArrayList.forEach(ArrayList.java:1257)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:229)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:197)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:211)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:191)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:128)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:69)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'workerService' defined in file (D:IJProjectsninsnins-apibuildclasseskotlinmaincomtistoryfonercisninsapplicationWorkerService.class): Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.tistory.fonercis.nins.domain.ProjectRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:798)
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:228)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1358)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1204)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:879)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:125)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
    ... 63 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.tistory.fonercis.nins.domain.ProjectRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1695)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1253)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1207)
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:885)
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:789)
    ... 81 more

Inheritance in Java, SpringBoot, JPA

Hi, I have the following problem and I need your help …

I have an entity Person which has a relationship of mucho a mucho with another entity Exercise.
Now from the entity Person inherit two types of people person Y personB.
But I need to save in my database to the person Y personB and its relationship with Exercise without saving in the database to Person.

How could I create these tables in my database using this relationship?
I need your help and if possible an example of the code …
Thanks in advance!!!