nilesh
nilesh

Reputation: 1336

Insert into multiple rows in mysql (or JPA)

I want to insert something like

insert into person (person_name, person_city, person_contact) values ("nilesh", "pune", (1234567, 987654, 562917, 357181));

person_contact can be any in number. Its giving error "Operand should contain 1 column(s)"

I have other way in ejb is -

for(Integer specializationId : specializationIds){

        Person person = new Person();
                person.setPersonName(personName);
                person.setPersonCity(personCIty);
                person.setPersonContact(personContact);
                em.persist(person);

            }

is there any other way to do this?

Upvotes: 1

Views: 1989

Answers (3)

Asad Shakeel
Asad Shakeel

Reputation: 2285

You may use the following approach to add multiple rows in DB

    List<Person> persons = new ArrayList<>();
    for (**LOOP_UPTO_NUMBER_OF_PERSONS_YOU_WANT_TO_ADD**){
        Person person = new Person();
        person.setPersonName(personName);
        person.setPersonCity(personCIty);
        person.setPersonContact(personContact);
        // add into list
        persons.add(person);
    }
    personRepository.saveAll(persons);

or if you already have a list of persons you can simply do using

    List<Person> persons = **PERSONS_YOU_WANT_TO_ADD**
    personRepository.saveAll(persons);

Upvotes: 0

SanTech
SanTech

Reputation: 128

You can use variables to hold data and use it in SQL query and then use for loop.

e.g.

for()
{
    String name = Get Name value;
    String city = Get City value;
    double number = Mobile Number;

    query = insert into tbl_name values(name,city,number);
}

Upvotes: 1

Fuad Hanif
Fuad Hanif

Reputation: 33

please try

insert into person (person_name, person_city, person_contact) values 
("nilesh", "pune", 1234567) , ("nilesh", "pune",987654) , ("nilesh", "pune",562917) , ("nilesh", "pune",357181);

Upvotes: 0

Related Questions