É possivel utilizar JpaRepository sem entidade?

é possivel utilizar JpaRepository sem entidade? No caso, substituindo por um DTO.

como segue o exemplo

@Repository
public interface BffRepository extends JpaRepository<BffDTO, String> {

@Query(nativeQuery = true, value = "select\n"
		+ "ent.name as enterprise_name, dep.name as department_name,\n"
		+ "sq.name as squad_name, acc.firstname as job_owner_name,\n"
		+ "tpt.name as test_template_name, job.name, job.job_blocked, job.job_removed,\n"
		+ "job.bot_scm_branch, job.bot_scm_url, job.schedule_startdate,\n"
		+ "job.expiration_date, job.timestamp,job.uuid,job.schedule_starttime,\n"
		+ "tpt.job_execution_timeout\n"
		+ "from portal.jobs job\n"
		+ "left join portal.enterprises ent on (ent.uuid = job.enterprise_id)\n"
		+ "left join portal.departments dep on (dep.uuid = job.department_id)\n"
		+ "left join portal.squads sq on (sq.uuid = job.squad_id)\n"
		+ "left join portal.accounts acc on (acc.uuid = job.job_owner)\n"
		+ "left join portal.test_plan_templates tpt on (tpt.uuid = job.template_id) where\n"
		+ "job.job_owner = ?1 and job.job_removed = false order by timestamp desc;")
List<BffDTO>buscarPorJobOwner(String jobOwner);

Há alternativas para este caso?

OBS: o DTO ja esta mapeado, mas não gostaria de criar uma view para transformar esse DTO em uma Entity.

Talvez seja melhor vc ter uma classe com o EntityManager injetado e fazer essa consulta usando ele.

Entendo. Eu tentei utilizar o EntityManager para fazer essa injeção, mas o mesmo retorna erro, por isso estou tentando através de Repository…

Segue o erro do EntityManager


***************************
APPLICATION FAILED TO START
***************************

Description:

Field repository in br.com.yaman.cloud.api.service.impl.BffServiceImpl required a bean of type 'br.com.yaman.cloud.api.repository.BffRepository2' 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 'br.com.yaman.cloud.api.repository.BffRepository2' in your configuration.

No caso as classes que ele se refere são a “Repository”

@Repository
public class BffRepository2 implements Serializable {

	private static final long serialVersionUID = 2303500355702346668L;


	@SuppressWarnings("unchecked")
	public List<BffDTO> buscarPorJobOwner(String jobOwner) {
		try {
			EntityManager entityManager = HibernateEntityManagerHelper.getEntityManager();
			List<BffDTO> listReturn = new ArrayList<>();
			try {
				listReturn = entityManager
						.createQuery("select\n" + "ent.name as enterprise_name, dep.name as department_name,\n"
								+ "sq.name as squad_name, acc.firstname as job_owner_name,\n"
								+ "tpt.name as test_template_name, job.name, job.job_blocked, job.job_removed,\n"
								+ "job.bot_scm_branch, job.bot_scm_url, job.schedule_startdate,\n"
								+ "job.expiration_date, job.timestamp,job.uuid,job.schedule_starttime,\n"
								+ "tpt.job_execution_timeout\n" + "from portal.jobs job\n"
								+ "left join portal.enterprises ent on (ent.uuid = job.enterprise_id)\n"
								+ "left join portal.departments dep on (dep.uuid = job.department_id)\n"
								+ "left join portal.squads sq on (sq.uuid = job.squad_id)\n"
								+ "left join portal.accounts acc on (acc.uuid = job.job_owner)\n"
								+ "left join portal.test_plan_templates tpt on (tpt.uuid = job.template_id) where\n"
								+ "job.job_owner = ?1 and job.job_removed = false order by timestamp desc;")
						.setParameter(1, jobOwner)
						.getResultList();
				
			} catch (NoResultException nre) {
				nre.printStackTrace();
			} finally {
				HibernateEntityManagerHelper.closeEntityManager();
			}
			return  listReturn;
		} catch (Exception e) {
			e.printStackTrace();
			return Collections.emptyList();
		}

	}
}```


e a service

@Inject
	private BffRepository2 repository;
	
@Override
	public ResponseEntity<String> listaJobsPorJobOwner(String jobOwner) {
		ResponseEntity<String> response = null;
		List<BffDTO> lista = repository.buscarPorJobOwner(jobOwner);
		try {
			if (jobOwner != null) {
				if (!jobOwner.isBlank()) {
					
					List<BffDTO> listWithStatus = checkStateJobRemote(lista);
					
					List<JsonObject> list = new ArrayList<JsonObject>();
					for (BffDTO job : listWithStatus) {
						JsonObject innerObject = new JsonObject();
						String uuId = job.getUuid();
						String name = job.getName();
						String enterpriseName = job.getEnterprise_name();
						String departmentname = job.getDepartment_name();
						String squadName = job.getSquad_name();
						String testTemplateName = job.getTest_template_name();
						Boolean jobBlocked = job.getJob_blocked();
						Boolean jobRemoved = job.getJob_removed();
						String bot_scm_branch = job.getBot_scm_branch();
						String bot_scm_url = job.getBot_scm_url();
						String schedule_startdate = job.getSchedule_startdate();
						String expiration_date = job.getExpiration_date();
						String timestamp = job.getTimestamp();
						String schedule_starttime = job.getSchedule_starttime();
						Integer job_execution_timeout = job.getJob_execution_timeout();
						String status = job.getStatus();
						
						if (!jobRemoved) {
							innerObject.addProperty("uuid", uuId);
							innerObject.addProperty("name", name);
							innerObject.addProperty("enterpriseName", enterpriseName);
							innerObject.addProperty("departmentName", departmentname);
							innerObject.addProperty("squadName", squadName);
							innerObject.addProperty("testTemplateName", testTemplateName);
							innerObject.addProperty("jobBlocked", jobBlocked);
							innerObject.addProperty("jobRemoved", jobRemoved);
							innerObject.addProperty("botScmBranch", bot_scm_branch);
							innerObject.addProperty("botScmUrl", bot_scm_url);
							innerObject.addProperty("scheduleStartdate", schedule_startdate);
							innerObject.addProperty("expiration_date", expiration_date);
							innerObject.addProperty("timestamp", timestamp);
							innerObject.addProperty("scheduleStarttime", schedule_starttime);
							innerObject.addProperty("jobExecutionTimeout", job_execution_timeout);
							innerObject.addProperty("status", status);
							list.add(innerObject);
						}
					}

					String jsonResponse = new Gson().toJson(list);
					response = new ResponseEntity<String>(jsonResponse, HttpStatus.OK);
				} else {
					response = new ResponseEntity(new Gson().toJson("JobOwner id Cannot be found"),
							HttpStatus.NO_CONTENT);
				}
			} else {
				response = new ResponseEntity(new Gson().toJson("Invalid Parameters"), HttpStatus.UNPROCESSABLE_ENTITY);
			}
		} catch (Exception e) {
			LOGGER.info("Error into ListJobWithDepartament: " + e.getMessage());
			response = new ResponseEntity<String>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
		}
		return response;
	}

Tente usar o EntityManager por injeção:

@Repository
public class BffRepository2 {

  private final EntityManager entityManager;

  public BffRepository2(EntityManager entityManager) {
    this.entityManager = entityManager;
  }
}

Por Injeção, apresenta o seguinte erro

Caused by: java.lang.IllegalArgumentException: Not a managed type: class br.com.yaman.cloud.api.domain.dto.BffDTO
Como se eu tivesse que tratar como Entity.

Assim ficou o repository.

@Repository
public class BffRepository2 implements Serializable {

	private static final long serialVersionUID = 2303500355702346668L;
	
	private final EntityManager entityManager;

	public BffRepository2(EntityManager entityManager) {
	    this.entityManager = entityManager;
	  }
	
	
	@SuppressWarnings("unchecked")
	public List<BffDTO> buscarPorJobOwner(String jobOwner) {
		try {
			List<BffDTO> listReturn = new ArrayList<>();
			try {
				listReturn = entityManager
						.createQuery("select\n" + "ent.name as enterprise_name, dep.name as department_name,\n"
								+ "sq.name as squad_name, acc.firstname as job_owner_name,\n"
								+ "tpt.name as test_template_name, job.name, job.job_blocked, job.job_removed,\n"
								+ "job.bot_scm_branch, job.bot_scm_url, job.schedule_startdate,\n"
								+ "job.expiration_date, job.timestamp,job.uuid,job.schedule_starttime,\n"
								+ "tpt.job_execution_timeout\n" + "from portal.jobs job\n"
								+ "left join portal.enterprises ent on (ent.uuid = job.enterprise_id)\n"
								+ "left join portal.departments dep on (dep.uuid = job.department_id)\n"
								+ "left join portal.squads sq on (sq.uuid = job.squad_id)\n"
								+ "left join portal.accounts acc on (acc.uuid = job.job_owner)\n"
								+ "left join portal.test_plan_templates tpt on (tpt.uuid = job.template_id) where\n"
								+ "job.job_owner = ?1 and job.job_removed = false order by timestamp desc;")
						.setParameter(1, jobOwner)
						.getResultList();
				
			} catch (NoResultException nre) {
				nre.printStackTrace();
			} finally {
				HibernateEntityManagerHelper.closeEntityManager();
			}
			return  listReturn;
		} catch (Exception e) {
			e.printStackTrace();
			return Collections.emptyList();
		}

	}
}

Ao usar o método createQuery, significa que irá executar uma jpql e não sql. Para executar sql, vc deve usar o método createNativeQuery.

Real, vacilo meu.

O erro agora é outro.

javax.persistence.PersistenceException: No Persistence provider for EntityManager named web-unit

Seu projeto usa algum persistence.xml?

Não… utilizo apenas de application.properties

Usa JdbcTemplate, é bem mais transparente de trabalhar, direto com DTO sem precisar de amarrações de classes de entidades.

Opa, Obrigado pela dica, irei procurar sobre