I would like to know if what i'm doing to read my database and update it, its the way to do it and its a good practice.
When i run my program i load my database into memory:
public static void open() {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("htTeamManagerPU");
EntityManager em = emf.createEntityManager();
TypedQuery<Season> query = em.createQuery("select s from Season s",Season.class);
seasons = query.getResultList(); }
By doing that i have in memory my database of players from a particular season.
Now i have my playerList which is a list of Players, and i want to update it in memory and after that update that player in my database. Can i do it differently as i already have the player in memory, i still have to do the find of the player and make the same changes i already did in memory before ?? seems that i'm doing the same changes twice...
public void finishTraining(int id){
EntityManagerFactory emf = Persistence.createEntityManagerFactory("htTeamManagerPU");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
for (Player player: playerList){
if (player.getPlayerId()==id) {
player.setIsTeam((short)0);
player.setIsToSell((short)1);
//no i find the player in my database with id primary key
Player p1 = em.find(Player.class, id);
//make the same changes i already did in memory
p1.setIsTeam((short)0);
p1.setIsToSell((short)1);
//submit my changes? there is another way of doing this?
em.getTransaction().commit();
}
}
em.close();
emf.close();
}
This is working fine and updating my databse. What i want to know if this is the right and best way to do it. Thanks