#Saving entity in entity

37 messages · Page 1 of 1 (latest)

rough oriole
#

Hello !
I have a ProfileFactory entity that contains List<ProfileRoleFactory> and I don't know how to tell to Springboot to save automatically when I add a role to a profile like:
myProfile.getRoles().addRole(roleExample);

Thank you in advance for your help

ProfileFactory.class

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Data
@Entity
@Table(name = "profiles")
public class ProfileFactory {

    @Id
    @Column(name = "id",
            nullable = false,
            columnDefinition = "CHARACTER VARYING(36)")
    private String id;

    @Column(name = "name",
            nullable = false,
            unique = true)
    private String name;

    @OneToMany(mappedBy = "profileId", fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST, CascadeType.MERGE})
    @JsonIgnore
    private List<ProfileRoleFactory> roles;```

**ProfileRoleFactory.class**
```java
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Data
@Entity
@Table(name = "profile_role")
public class ProfileRoleFactory {

    @EmbeddedId
    private ProfileRoleIdFactory id;

    @ManyToOne(fetch = FetchType.EAGER)
    @MapsId("profileId")
    @JoinColumn(name = "profile_id",
            updatable = false,
            nullable = false,
            referencedColumnName = "id",
            foreignKey = @ForeignKey(name = "id.profile_id"),
            columnDefinition = "CHAR(36)")
    private ProfileFactory profileId;

    @ManyToOne(fetch = FetchType.EAGER)
    @MapsId("roleId")
    @JoinColumn(name = "role_id",
            nullable = false,
            updatable = false,
            referencedColumnName = "id",
            foreignKey = @ForeignKey(name = "id.role_id"),
            columnDefinition = "BIGINT")
    private RoleFactory roleId;

    @Column(name = "applied_at",
            nullable = false,
            columnDefinition = "TIMESTAMP WITHOUT TIME ZONE")
    private Timestamp appliedAt = new Timestamp(System.currentTimeMillis());```
jagged mountainBOT
#

This post has been reserved for your question.

Hey @rough oriole! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

rough oriole
#

And also my method to update an profile:

    @PutMapping(path = "/{id}")
    public ResponseEntity<String> updateOne(@RequestBody ProfileFactory profileFactory) {
        profileService.update(profileFactory);
        
        if (null != profileFactory.getNicknameId()) {

            NicknameDto nicknameDto = new NicknameDto();
            nicknameDto.setAvailable(true);

            nicknameService.update(profileFactory.getNicknameId().getId(), nicknameDto);
        }

        return ResponseEntity.ok("Profile was successfully updated with ID: " + profileFactory.getId());
    }```
last grotto
#

send nicknameService as well

#

but otherwise the process is the same

you have an entity user with a list of roles
you get a user in the persistance layer. you add the new role you need. save the user. jpa/hibernate/whatever should automatically do the saving and add the relationship

#

same is with removing a role from a user. you get the user. remove the wanted role from the list and save the user again

both of these will leave the role inside the db and not delete it. if you want to do that you'll have to do that manually

#

if the role you have isn't in the db already/saved. You'll need a persist cascade or to do it manually yourself

rough oriole
# last grotto send nicknameService as well
@AllArgsConstructor
@Service
public class NicknameService implements NicknameServiceInterface {

    @Autowired
    private final NicknameRepository nicknameRepository;

    @Override
    public NicknameFactory getOne(long id) {
        return nicknameRepository.findById(id);
    }

    @Override
    public NicknameFactory getOne(String name) {
        return nicknameRepository.findByName(name);
    }

    @Override
    public List<NicknameFactory> getAll() {
        return nicknameRepository.findAll();
    }

    @Override
    public NicknameFactory update(long id, NicknameDto nicknameDto) {
        NicknameFactory nicknameFactory = nicknameRepository.findById(id);
        nicknameFactory.setAvailable(nicknameDto.isAvailable());
        nicknameFactory.setUpdatedAt(new Timestamp(System.currentTimeMillis()));
        return nicknameRepository.save(nicknameFactory);
    }

}```
rough oriole
last grotto
#

Typically hibernate should save it but for some reason it isn't
I should've made you send profileService not nicknameService, my bad

rough oriole
# last grotto Typically hibernate should save it but for some reason it isn't I should've made...

ProfileService.class

@AllArgsConstructor
@Service
public class ProfileService implements ProfileServiceInterface {

    @Autowired
    private final ProfileRepository profileRepository;

    @Override
    public ProfileFactory getOne(String id) {
        return profileRepository.findProfileById(id);
    }

    @Override
    public ProfileFactory getOneByName(String name) {
        return profileRepository.findByName(name);
    }

    @Override
    public List<ProfileFactory> getAll() {
        return profileRepository.findAll();
    }

    @Override
    public ProfileFactory save(ProfileFactory profileFactory) {
        return profileRepository.save(profileFactory);
    }

    @Override
    public ProfileFactory update(ProfileFactory profileFactory) {
        return profileRepository.save(profileFactory);
    }

    @Override
    public boolean isExists(String id) {
        return profileRepository.existsById(id);
    }

    @Override
    public boolean isExistsByName(String name) {
        return profileRepository.existsByName(name);
    }

}```
rough oriole
jagged mountainBOT
last grotto
#

cuz I'm not seeing you adding the roles anywhere

rough oriole
#

I add roles to my profile object as follows:
myProfile.getRoles().add(roleAdmin);

Then I save the profile with the update() method I've given. I don't do anything else.

rough oriole
# last grotto where?

I'm just testing by doing it this way:

    @Override
    public void run(String... args) {
        RoleFactory adminRole = new RoleFactory();
        adminRole.setName("admin");
        adminRole.setShortName("admin");
        adminRole.setChatPrefix("admin");
        adminRole.setChatFormat("admin");
        adminRole.setTabPrefix("admin");
        adminRole.setChatDivider(">>");
        adminRole.setDefault(false);
        adminRole.setPower(1000);
        roleRepository.save(adminRole);

        ProfileFactory profile = new ProfileFactory();
        profile.setId("d734a4a6-dd2a-46fc-b4c8-erf895g");
        profile.setName("AnPlayer");
        profile.setCoins(10);
        ProfileRoleFactory myRole = new ProfileRoleFactory();
        myRole.setDuration(10);
        myRole.setProfileId(profile);
        myRole.setRoleId(adminRole);
        profile.getRoles().add(myRole);
        profileRepository.save(profile);```
last grotto
#

ok what queries get executed? this should be saving the roles as well.

#

also can you send a picture of the schema (or draw one yourself) just for the relationships between those 2-3 (or however many)

rough oriole
#

This is what happens when I update

jagged mountainBOT
#

💤 Post marked as dormant

This post has been inactive for over 300 minutes, thus, it has been archived.
If your question was not answered yet, feel free to re-open this post or create a new one.
In case your post is not getting any attention, you can try to use /help ping.
Warning: abusing this will result in moderative actions taken against you.

last grotto
#

ohhh so you have a class for that table as well

#

then you'll have to save the ProfileRole as well

#

manually since you aren't using a normal many to many relationship

rough oriole
split briar
#

just many to many yes, but you added extra fields

rough oriole
last grotto
#

if you have the relationship like this
with the "default" many to many table it will work as expected

#

but since you have extra fields like this
you'll have to use a class and do everything manually as the other "normal entities"

#

and the reason it works that way is if you want to access the duration of a random entry in UserRoles how would you do that without a class?

rough oriole
#

Ah okay I understand now, it's true that it's totally logical, thanks for the advice to you 2!

jagged mountainBOT