简体   繁体   中英

How to OneToMany unidirectional relationship (Spring boot + JPA)

I'm trying to get results from an unidirectional OneToMany relation in Spring Boot.

This is my "Brand" entity

@Entity
@Table
class Brand {

@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Long id 

@Column(nullable = false, length = 255)
private String name 

@OneToMany(orphanRemoval = true, fetch = FetchType.LAZY)
@JoinColumn(name = "id_model", referencedColumnName = "id")
private List<Model> models  // Listado de modelos

@CreationTimestamp
@Column(name = "fecha_alta")
private Timestamp fechaAlta // Fecha de alta

*getters and setters*

And this is my "Model" entity

@Entity
@Table
class Model {

@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Long id // Identificaodr único del modelo

@Column(nullable = false, name="id_model")
private Long idModel // Identificador de la comisión

*getters and setters*

I want to get the list of "brands" with their respective models using repository, service and controller by Spring Boot and I don't know how to do it. Any ideas?

BrandRepository.class

interface BrandRepository implements CrudRepository<Brand,Long> {
  @Query("SELECT b FROM Brand b JOIN FETCH b.models")
  List<Brand> getAll();
}

BrandService.class

@Service
class BrandService {
  private final BrandRepository brandRepository;

  public BrandService(BrandRepository brandRepository) {
    this.brandRepository = brandRepository;
  }

  List<Brand> getAll() {
    return brandRepository.getAll();
  }
}

BrandController.class

@RestController
@RequestMapping("/brands")
class BrandController {
  private final BrandService brandService;

  public BrandController(BrandService brandService) {
    this.brandService = brandService;
  }

  @GetMapping
  public List<Brand> getAll() {
    return brandService.getAll();
  }
}

As a suggestion,

Brand.class:

-@Table remove annotation. (There is no need if you will not name the table. Creates a table named class by default.)

-models field, remove fetch strategy. (@OneToMany default fetch, LAZY)

These articles can help you understand the answer:

Working with Spring Data Repositories

Accessing Data with JPA

Building a RESTful Web Service

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM