我创建了一个有两个表(books,members)的MySql数据库。 一个成员可以有很多本书,某本书只能有一个成员。 我想创建一个spring boot项目,它将是一个REST API,在数据库上预形成CRUD操作。 对于数据库操作,我使用的是Spring Data JPA。
接下来,我创建了两个名为books和Members的类。@Entity
@Table(name = "members")
public class Members {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name = "last_name")
private String lastName;
@Column(name = "first_name")
private String firstName;
@Column(name = "address")
private String address;
@Column(name = "phone_num")
private String phoneNum;
@Column(name = "email")
private String email;
@OneToMany(mappedBy = "members", cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
private List books;
//getters and setters
@Entity
@Table(name = "books")
public class Books {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name = "title")
private String title;
@Column(name = "author_last_name")
private String authorLastName;
@Column(name = "author_first_name")
private String authorFirstName;
@Column(name = "publisher")
private String publisher;
@Column(name = "publishing_year")
private String publishingYear;
@ManyToOne(cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
@JoinColumn(name = "id_member")
private Members members;
//getters and setters
我创建了一个名为LibraryRepository的接口,它扩展了JParePository。public interface LibraryRepository extends JpaRepository {
}
我的LibraryService接口public interface LibraryService {
List findAll();
}
和LibraryServiceImpl类@Service
public class LibraryServiceImpl implements LibraryService {
private LibraryRepository libraryRepository;
@Autowired
public LibraryServiceImpl(LibraryRepository libraryRepository) {
this.libraryRepository = libraryRepository;
}
@Override
public List findAll() {
return libraryRepository.findAll();
}
}
和rest控制器@RestController
@RequestMapping("/api")
public class LibraryRestController {
private LibraryService libraryService;
@Autowired
public LibraryRestController(LibraryService libraryService) {
this.libraryService = libraryService;
}
@GetMapping("/loans")
public List findAll(){
return libraryService.findAll();
}
}
其中一个成员借了一本书。 当我运行应用程序并在http://localhost:8080/api/loans上使用GET方法时,返回的是一个无限列表。 一个会员有一本书而这本书有一个会员,这会员有一本书等等。。。。
我相信有些东西被错误地映射到了我的实体类上,但我无法找到确切的内容。