How to edit data inside tables automatically created by hibernate?

As I wrote in Subject. I have a table created automatically by hibernate, because of use this lines of code. ( @ManytoMany )

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO )
    private Long idMeal;

    private String name;

    @ManyToMany
    private Map<Product, Weight> productsWithWeight;**

I want to create "patch" methods which should be able to edit data in this table. Replace Product by other Product, and Weight by other Weight. What I need to do ? Have You some good arcticles about how it works "underhood" ?

1 answer

  • answered 2019-08-13 04:05 mate00

    Cześć! :) @ManyToMany annotation is intended to map a relation between two different objects/tables. For example, you can have these entities:

    A user that you can log in to your website:

    @Entity
    public class User {
      int id;
      String username;
      String password;
    }
    

    And a role that a given user has (like admin, read-only, ect.):

    @Entity
    public class Role {
      int id;
      String roleName;
    }
    

    There may be many roles in the system, and many users. Each user can have many roles, so we add:

    @Entity
    public class User {
      int id;
      String username;
      String password;
    
      @ManyToMany
      Set<Role> roles = new HashSet<>();
    }
    

    You will create some CrudRepository for each type, and save your user for example like this:

    //...
    Set<Role> roles = new HashSet<>();
    roles.add(roleRepository.findByRoleName("ADMIN").get()); // <- maybe orElse() would be better, but it's just to show the use case
    
    User user = new User(1, "SztyJkmajster", "password", roles);
    userRepository.save(user);
    

    At this moment you will have populated rows in USER, ROLE and USERS_ROLES tables.