我在学春靴。现在我与一个用户实体和一个团队实体有很多关系。所以一个用户可以有几个团队,一个团队可以有几个用户。
@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);
}
如何找到属于一个用户的所有团队?
2条答案
按热度按时间k2arahey1#
用户已Map为
List<Team>
,您需要使用UserRepository
而不是TeamRepository
.在这里,您将得到一个用户,该用户拥有他所属的所有团队(假设用户名是唯一的)
或
如果您有双向多对多(团队也Map了
Lis<User>
)喜欢追随然后您可以定义如下的查询方法来获取一个用户的所有团队,
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;
}
`Team Entity`
@Entity
@Table(name="team")
public class Team {
}
`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);