简体   繁体   中英

How to generate a map in java 8 from a list in hibernate single table strategy for the below scenario

@Entity
@Table(name="PLAYER")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(
          name="TEAM", 
          discriminatorType=DiscriminatorType.STRING
          )
public abstract class Player{
    @Id
    @Column(name="ID")
    @GeneratedValue(generator = "seq_gen")
    @SequenceGenerator(name = "seq_gen", sequenceName = "CONSTANTS_SEQ")
    protected long id;
    @Column(name="NAME")
    protected String name;
    @Column(name="YEAR")
    protected int year; 
}

@Entity
@DiscriminatorValue(value = "SUNRISERS")
public class SunRisersPlayer extends Player{

}

@Entity
@DiscriminatorValue(value = "KNIGHT_RIDERS")
public class KnightRidersPlayer extends Player{

}

@Entity
@DiscriminatorValue(value = "DARE_DEVILS")
public class DareDevilsPlayer extends Player{

}

Here, I am trying to fetch all team players at once

public interface PlayerDao extends CrudRepository<Player, Long>{

    List<Player> findAll();
}

Sample PLAYER Table Data is

ID      name        year    team
1000    gilchrist   2015    SUNRISERS
1001    Yuvraj      2015    SUNRISERS
1002    Ghambir     2015    KNIGHT_RIDERS
1004    Pathan      2015    KNIGHT_RIDERS
1006    Umesh       2015    KNIGHT_RIDERS
1007    Zaheer      2015    DARE_DEVILS
1008    Venu        2015    DARE_DEVILS

Once I get the complete list, how to prepare a Map in Java 8 with the key as Team name and value as a list of players corresponding to that team?

I was able to use groupBy to get the complete list as shown below

Defined a transient variable in Player entity to get the team name

@Transient
public String getName(){
    DiscriminatorValue val = this.getClass().getAnnotation( DiscriminatorValue.class );
    return val == null ? null : StringUtils.remove(WordUtils.capitalizeFully(val.value(), '_'), "_");
}

By using team Name, I am grouping by as shown below to get the players for each team ( Map<String, List<Player>> )

List<Player> players = playerDaoImpl.findAll();
Map<String, List<Player>> playersPerTeam= players.stream()
              .collect(Collectors.groupingBy(Player::getName));

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