Ajay Kumar
Ajay Kumar

Reputation: 3250

Spring Data JPA - for loop not saving entity

I am trying to save multiple strings into one column into MySQL DB. Using Spring Data JPA with Hibernate.

I have my PersonserviceImpl as

    @Override
public void createnewPerson(AppPerson appPerson) {

    List<AppPersonproperty> personProperties = personpropertyRepository
            .findByPersonid(appPerson.getAppPersontype().getId());

        for (AppPersonproperty app : personProperties) {
            System.out.println(app.getPersonpropertyname());
            entity.setPersonpropertyname(app.getPersonpropertyname());
        }

    personRepository.save(entity);
}

Only the last value gets save from Person's previous names.

Sysout:

SpiderMan
Spidey

Expected value in the column:

SpiderManSpidey

Actual value in the column:

Spidey

What am I doing wrong here?

Upvotes: 0

Views: 701

Answers (1)

Jens Schauder
Jens Schauder

Reputation: 81907

Why would JPA append Strings in a column when you are replacing them on the Java side?

If you want them appended in the column you need to append them on the Java side as well. Replacing

entity.setPersonpropertyname(app.getPersonpropertyname());

with

entity.setPersonpropertyname(entity.getPersonpropertyname() + app.getPersonpropertyname());

should do the trick.

Upvotes: 1

Related Questions