I have a class:
@Entity
@Table(name = "restaurants")
public class Restaurant extends AbstractNamedEntity implements Serializable {
@OneToMany(fetch = FetchType.LAZY, mappedBy = "restaurant")
private Set<Meal> meals = Collections.emptySet();
//other fields, getters, setters, constructors
}
I'm getting my data with Spring Data:
@Repository
public interface RestaurantRepository extends CrudRepository<Restaurant, Integer> {
}
I have REST-controller, which produces JSON data:
@RestController
@RequestMapping(value = RestaurantController.REST_URL, produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
public class RestaurantController {
static final String REST_URL = "/restaurants";
@Autowired
private RestaurantRepository repository;
@GetMapping("{id}")
public List<Restaurant> getOne(@PathVariable Integer id) {
return repository.findById(id);
}
}
How to avoid including that LAZY data (set of Meals) to get them to a SQL request? As I know I need to write a custom JacksonObjectMapper, but I don't know how to do it
You can use @JsonIgnore
annotation in order to ignore the mapping of a field. Then you should do this:
@JsonIgnore
@OneToMany(fetch = FetchType.LAZY, mappedBy = "restaurant")
private Set<Meal> meals = Collections.emptySet();
UPDATED
Based what you want to do " Ignore field dynamically when getting one or not getting alls " you can use @NamedEntityGraphs
annotation to specific what fields you want to join, then by using @NamedEntityGraph
you specify the path and boundaries for a find operation or query and you should use in your custom Repository
the @EntityGraph
annotation who allows to customize the fetch-graph
based what you want to do.
So you should add the following code:
@Entity
@Table(name = "restaurants")
@NamedEntityGraphs({
@NamedEntityGraph(name="Restaurant.allJoins", includeAllAttributes = true),
@NamedEntityGraph(name="Restaurant.noJoins")
})
public class Restaurant extends AbstractNamedEntity implements Serializable {
}
@Repository
public interface RestaurantRepository extends CrudRepository<Restaurant, Integer> {
@EntityGraph(value = "Restaurant.allJoins", type = EntityGraphType.FETCH)
@Override
List<Restaurant> findAll();
@EntityGraph(value = "Restaurant.noJoins", type = EntityGraphType.FETCH)
@Override
Optional<Restaurant> findById(Integer id);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.