SpringBootJPA如何从多表中检索数据?

uinbv5nw  于 2021-07-06  发布在  Java
关注(0)|答案(2)|浏览(312)

我在学春靴。现在我与一个用户实体和一个团队实体有很多关系。所以一个用户可以有几个团队,一个团队可以有几个用户。

@Entity
    public class User {
        @Id
        @GeneratedValue(strategy=GenerationType.IDENTITY)
        @Column(name="id", nullable =false, updatable = false)
        private Long id;
@ManyToMany
    @JoinTable(
            name = "team_have",
            joinColumns = @JoinColumn(name = "id"),
            inverseJoinColumns = @JoinColumn(name = "teamId"))
    List<Team> haveTeams;

这是团队实体:

@Entity
@Table(name="TEAM")
public class Team {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long teamId;
    @OneToMany(cascade = CascadeType.ALL, mappedBy="team")
    private List<Task> tasks;

这是我的存储库:

public interface TeamRepository extends CrudRepository<Team, Long>{
    List<Team>findByName(String name);

}

如何找到属于一个用户的所有团队?

k2arahey

k2arahey1#

用户已Map为 List<Team> ,您需要使用 UserRepository 而不是 TeamRepository .

public interface UserRepository extends CrudRepository<User, Long>{
    User findByName(String name);

}

在这里,您将得到一个用户,该用户拥有他所属的所有团队(假设用户名是唯一的)

如果您有双向多对多(团队也Map了 Lis<User> )喜欢追随

@Entity
@Table(name="TEAM")
public class Team {

    ....
    @ManyToMany(cascade = CascadeType.ALL, mappedBy="haveTeams")
    private List<User> users;

然后您可以定义如下的查询方法来获取一个用户的所有团队,

public interface TeamRepository extends CrudRepository<Team, Long>{
    List<Team> findByUsers(User user);

}
6pp0gazn

6pp0gazn2#

建立它们之间联系的最佳方法是使用双向关系,如: User Entity ```
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
/* @Column(name = "id", nullable = false, updatable = false) You don't need this,
the name is taken from the name of the variable and it cannot be null since you
have @GeneratedValue */
private Long id;

@ManyToMany(fetch = LAZY, cascade = CascadeType.PERSIST)
@JoinTable(
    name = "user_team", // I would name this user_team since the user can have many teams, and vice versa
    joinColumns = @JoinColumn(name = "user_id" , referencedColumnName = "id"),
    inverseJoinColumns = @JoinColumn(name = "team_id",  referencedColumnName = "id"))
 Set<Team> teams = new HashSet<>();

}
`Team Entity`
@Entity
@Table(name="team")
public class Team {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long teamId;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "team")
private List<Task> tasks;

@ManyToMany(mappedBy = "teams", fetch = LAZY, cascade = CascadeType.PERSIST)
private Set<User> users = new HashSet<>();

}
`Team Repo`
public interface TeamRepository extends CrudRepository<Team, Long>{
@Query(value = "SELECT * FROM team t1 INNER JOIN user_team t2 ON t1.id = t2.team_id WHERE t2.user_id = ?1 ")
List findAllByUserId(long userId);
}

使用示例:

List teams = teamRepo.findAllByUserId(1);

很棒的教程:https://attacomsian.com/blog/spring-data-jpa-many-to-many-mapping

相关问题