如何获得具有多个可能依赖的实体

时间:2017-04-17 20:59:56

标签: sql spring spring-boot spring-data spring-data-jpa

这是我需要通过当前用户ID获取的项目实体:

def show_go_screen(self):
    self.screen.blit(BACKGROUND_IMG, (0, 0))
    text_surface = FONT.render("Press space bar to play again", True, WHITE)
    self.screen.blit(text_surface, (WIDTH / 2, HEIGHT * 7 / 8))
    pg.display.flip()
    done = False
    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                self.running = False
                done = True
            if event.type == pg.KEYDOWN:
                if event.key == pg.K_SPACE:
                    done = True

        self.clock.tick(FPS)

这是用户实体,我将用它来获取产品:

@Entity
@Table(name = "project")
public class Project implements Serializable {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @ManyToMany
  @JoinTable(name = "project_user",
           joinColumns = @JoinColumn(name="projects_id", referencedColumnName="id"),
           inverseJoinColumns = @JoinColumn(name="users_id", referencedColumnName="id"))
  private Set<User> users = new HashSet<>();
}

Repositories类扩展了JpaRepository类。我如何获得当前用户ID的所有项目?

我可以使用的本机SQL语句是:

@Entity
@Table(name = "jhi_user")
public class User extends AbstractAuditingEntity implements Serializable {

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

  @ManyToMany(mappedBy = "users")
  private Set<Project> projects = new HashSet<>();
}

1 个答案:

答案 0 :(得分:1)

应该这么简单......

User user = userRepository.findById(100L);
Set<Projects> projects = user.getProjects();

由于您的映射,JPA负责其余的工作。