#Spring boot stop recursive resolution in repository.

86 messages · Page 1 of 1 (latest)

austere sedge
#

I have two models that reference each other.
An employee works in an department and a department has multiple employees.
If I try to get an employee, I get an error because Jaxon tries to serialize recursively.

How could I fix that?
I guess that should not be too uncommon

dire ivyBOT
#

This post has been reserved for your question.

Hey @austere sedge! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

rapid quartz
austere sedge
#

Thanks

dire ivyBOT
# austere sedge Thanks

If you are finished with your post, please close it.
If you are not, please ignore this message.
Note that you will not be able to send further messages here after this post have been closed but you will be able to create new posts.

dire ivyBOT
#

💤 Post marked as dormant

This post has been inactive for over 300 minutes, thus, it has been archived.
If your question was not answered yet, feel free to re-open this post or create a new one.

austere sedge
#

I am implementing the dto pattern with modelmapper following a guide from baeldung.
https://www.baeldung.com/entity-to-and-from-dto-for-a-java-spring-application

In section 4 (https://www.baeldung.com/entity-to-and-from-dto-for-a-java-spring-application#service) of this guide he talks about a service layer.
I am not that deep into Spring-Boot (I'm still geting started) and I don't know if I have to annotate it with something special, or if that is just a helper class, or if i could just omit it for simplicity sake...

And please laugh at me if it is a dumb problem 😄

Baeldung

How to to simpler conversions from Entities to DTOs and back in a Spring REST API.

rapid quartz
austere sedge
#

Thanks. I thought so, but I was unsure. And I was not in the mood to try it and maybe fail

dire ivyBOT
rapid quartz
austere sedge
#

I will, thanks for your help

dire ivyBOT
# austere sedge I will, thanks for your help

If you are finished with your post, please close it.
If you are not, please ignore this message.
Note that you will not be able to send further messages here after this post have been closed but you will be able to create new posts.

austere sedge
#

Still not working right...
I am getting an error when spring starts up:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'employeeController': Unsatisfied dependency expressed through field 'service': Error creating bean with name 'employeeService': Unsatisfied dependency expressed through field 'repository': Error creating bean with name 'employeeRepository' defined in com.example.springTest.repository.EmployeeRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Could not create query for public abstract com.example.springTest.model.Employee com.example.springTest.repository.EmployeeRepository.findByHrId(java.lang.Long); Reason: Failed to create query for method public abstract com.example.springTest.model.Employee com.example.springTest.repository.EmployeeRepository.findByHrId(java.lang.Long); No property 'hrId' found for type 'Employee'

rapid quartz
#

If your hrId is actually the called id on the Entity, this will fail

austere sedge
#

I'll go ahead and simply rename the field in my model to match, so it is less confusing

rapid quartz
#

Yeah, Spring/Hibernate is building the Query based on reflection of the fields, so the fields need to match 1:1 (Minus the First Letter being UpperCase)

austere sedge
#

I knew that, but I still messed it up 😄

#

I used modelmapper to map my Entities to dtos. But the dates in my model ended up null, when calling setDateConverted as in every example ive seen.
I'll check myself first.

rapid quartz
#

I personally prefer MapStruct to ModelMapper

austere sedge
#

Just preference, or is there any reason?

#

And I got it working for now.
I am toying around and learning spring, so I can be more productive at work.

rapid quartz
#

Find the syntax to be better. MapStruct is just Interface + Some annotations, and it generates a mapper at buildtime.

#

So you can get something like

@Mapper(componentModel = MappingConstants.ComponentModel.SPRING)
public interface MyDtoMapper  {

   MyDto fromEntityToDto(MyEntity entity);
   MyEntity fromDtoToEntity(MyDto dto);
}

And assuming your fields are named the same, it just works.

austere sedge
#

That seems to be really nice. I think id like to read the docs for that.
Dont worry, Ill find it on my own

rapid quartz
#

When in doubt, look up "<Topic> Baeldung" and they'll likely have an article on it

#

I think the older versions might have an issue with Lombok, not sure if that's fixed without having another Maven Plugin. But there is a Maven Plugin to do it.

austere sedge
#

Okay, thanks.
But could you tell me if mapstruct handles converting to other datatypes nicely?

dire ivyBOT
austere sedge
#

Nvm... Found it.. That seems really primitive, I like it and I will switch to that then 😄

rapid quartz
#

It can, there are a lot of additional things it can do, the official docs have more

#

I really like target="foo", source="deep.inner.value.", since it will add null checks to all of the inner fields.

austere sedge
#

that is really nice

austere sedge
#

Seems like it is still broken.

#

Got it working, but still need to add the annotations to convert dates

#

Got a little Problem...

@Mapper
public interface EmployeeMapper {
    @Mapping(target = "birthDate", source = "entity.birthDate", dateFormat = Constants.dateFormatString)
    public EmployeeDTO toDTO(Employee entity);
    @Mapping(target = "birthDate", source = "dto.birthDate", dateFormat = Constants.dateFormatString)
    public Employee toEntity(EmployeeDTO dto);
}

This is my mapper and I get the following error:
java: The type of parameter "entity" has no property named "birthDate".

rapid quartz
#

Is it birthday on the employee?

austere sedge
#

Yes

rapid quartz
#

Well, that would cause the issue

austere sedge
#

Ah, I think I understand

austere sedge
#

What does this error mean?
I am trying to simple crud operations on my controller and used @Mapper(componentModel = "spring") so that i could use a a service to get a field from the database upon creation...

This is my error:

Field mapper in com.example.springTest.controller.EmployeeController required a single bean, but 2 were found:
    - employeeMapperImpl: defined in file [/home/stefan/ideaProjects/springTest/springTest/target/classes/com/example/springTest/mapper/EmployeeMapperImpl.class]
    - modelMapper: defined by method 'modelMapper' in com.example.springTest.SpringTestApplication
rapid quartz
#

It looks like your ModelMapper is causing stuff to fail

#

Have you removed the ModelMapper project from the dependencies in favor of MapStruct?

stone lotus
#

Hey guys do anyone use JBoss here?

austere sedge
#

I removed modelmapper from my code and removed it from my project dependencies.
Then I implemented a mapstruct and later i tried to modify the mapstruct mapper to enrich the contract and department field with the corresponding model objects.
After that it started failing.

#

This is my mapper currently:

@Mapper(componentModel = "spring")
public abstract class EmployeeMapper {
    @Autowired
    DeparmentService departmentService;
    @Mapping(target = "department", source = "entity.department.name")
    @Mapping(target = "birthDate", dateFormat = Constants.dateFormatString)
    public abstract EmployeeDTO toDTO(Employee entity);
    @Mapping(target = "department", expression = "java(departmentService.getDepartmentByName(dto.getDepartment()))")
    @Mapping(target = "birthDate", dateFormat = Constants.dateFormatString)
    public abstract Employee toEntity(EmployeeDTO dto);
}
austere sedge
#

Fixed it. When using componentModel = "spring" it defines its own bean and I still had a Function to get the mapper as a bean, so it was confused

austere sedge
#

Still more problems....
I implemented a second controller for my departments and I get the following error...

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Ambiguous mapping. Cannot map 'departmentController' method com.example.springTest.controller.DepartmentController#getDepartments() to {GET [/ || ], produces [application/json]}: There is already 'departmentController' bean method

rapid quartz
austere sedge
#

I set @RequestMapping("/employee") and the other @RequestMapping("/department").
Maybe I missunderstood the meaning of @RequestMapping

rapid quartz
#

No that should be good

#

Does DepartmentController have multiple methods?

austere sedge
#

Yes, two get mappings. One to get all and one to get details for one specifically

rapid quartz
#

With seperate @GetMapping("/some/different/path") on each functions?

austere sedge
#

yes

rapid quartz
#

This is one of those "very hard to figure out without the code" problems.
Are the methods called the same thing?

austere sedge
#

One on "" and one with "/{id}/"

#
@RestController
@RequestMapping(name = "/department")
public class DepartmentController {
    @Autowired
    DepartmentMapper mapper;
    @Autowired
    DeparmentService service;

    @GetMapping(name = "", produces = "application/json")
    public List<DepartmentDTO> getDepartments() {
        return service.getDepartments().stream().map(mapper::toDTO).collect(Collectors.toList());
    }

    @GetMapping(name = "/{name}/", produces = "application/json")
    public DepartmentDTO details(@PathVariable String name) {
        return mapper.toDTO(service.getDepartmentByName(name));
    }
}
rapid quartz
#

.. I have no idea. I can tell you that if you're using default configuration produces="application/json" is assumed.

austere sedge
#

I merely put that in, because swagger reports it as unknown if i don't put that in

rapid quartz
#

Are you using Swagger 2, or Open API (Swagger 3)

austere sedge
#

Open API

rapid quartz
#

Weird

#

Your stuff is acting weird for reasons I can't explain.

austere sedge
#

Should i kill my local maven repository and do a clean build?

rapid quartz
#

Eh, refresh project -> clean -> install is fine

austere sedge
#

And the most funy thing is that i copied the EmployeeController and changed the names. And the employeeController works fine

rapid quartz
#

Killing your local maven repo is a bit overkill if you're only using official repos.

#

OH

#

Get rid of name= in Request Mapping to path, along with GetMapping

#

Name assigns the name of the Mapping, path actually configures the path. @RequestMapping("/department") == @RequestMapping(path="/department"). I was thrown off because I've personally never seen name before, and just assumed. But I checked the docs to be sure.

austere sedge
#

Never mind....
I copied the EmployeeController again and changed the names again and it magically was working

#

I don't fucking know why on earth that would change anything....

rapid quartz
#

Did you swap name to Path?

austere sedge
#

Yes, but it also was working with name 🤷‍♂️

rapid quartz
#

That doesn't make sense

#

It's too early to debug Spring nonsense

#

Happy it's working

austere sedge
#

But thanks for your patience with me 😅
I am going to check out some swagger stuff now.
I hope that shit is woring 😓

dire ivyBOT