Home > Blockchain >  How to insert many db records from Hibernate
How to insert many db records from Hibernate

Time:09-17

I have entity class

@Data
@NoArgsConstructor
@Entity
@Table(name = "tx")
public class Tx{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id", nullable = false)
    private int id;
    @Column(name = "aaa")
    private String aaa;
}

and i try to insert 100 template records into db.

Tx tx = applicationContext.getBean(Tx.class);
Session session = sessionFactory.openSession();
session.beginTransaction();
IntStream.range(0, 100).forEach(index -> session.save(tx));
session.getTransaction().commit();
session.close();

but as a result, only 1 record is inserted into the database. What am I doing wrong?

CodePudding user response:

Tx tx = applicationContext.getBean(Tx.class); makes no sense. Beans managed by the Application Context are Controller, Services, Repositories... Things that do something. An Entity represents Data. I'm wondering why this even working try something linke this:

Session session = sessionFactory.openSession();
session.beginTransaction();
IntStream.range(0, 100).forEach(index -> {
   Tx tx = new Tx();
   tx.setAaa(index);
   session.save(tx);
});
session.getTransaction().commit();
session.close();

CodePudding user response:

Use CrudRepository<Model, Id> and Call its saveAll(List) Method for this

UserRepository

public interface UserRepository extends CrudRepository<User, Integer> {

    public List<User> findByName(String name);

    public List<User> findByCity(String city);

    public List<User> findByNameAndCity(String name, String city);  

}

Main Method

public static void main(String[] args) {
    ApplicationContext context = SpringApplication.run(BootJpaExampleApplication.class, args);
    UserRepository userRepo = context.getBean(UserRepository.class);
    
    //save Single user 
    userRepo.save(new User(101, "Aniruddh", "Delhi", "I am Java Developer"));
    
    
    // save Multiple Users
    
    User user = new User();
    user.setName("Rahul");
    user.setCity("Bhopal");
    user.setStatus("Python Developer");
    
    User user1 = new User();
    user1.setName("Ram");
    user1.setCity("Jabalpur");
    user1.setStatus("Database Developer");
    
    Iterable<User> users = List.of(user, user1);
    userRepo.saveAll(users);

}
  • Related