mbf
mbf

Reputation: 43

Hibernate entity is updated existing row instead of creating new row using saveAndFlush

I am Using Spring data JPA, hibernate, sqlserver in a Spring Rest Application.

i) For the first request a record is inserted into data base. working fine until here.

ii) when i make another new request with new data updating existing record instead of inserting new record into data base

iii)But when application context reloads I am able to insert new record.

Here below is the code snippet.

1) Hibernate Configuration

public class HibernateConfiguration {

@Autowired
private Environment env;

@Bean
public DataSource dataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();

  dataSource.setDriverClassName(env.getRequiredProperty
       ("db.driverClassName"));
    dataSource.setUrl(env.getRequiredProperty("db.url"));
    dataSource.setUsername(env.getRequiredProperty("db.username"));
    dataSource.setPassword(env.getRequiredProperty("db.password"));

    return dataSource;
}

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
    LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
    entityManagerFactoryBean.setDataSource(dataSource);
    entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
    entityManagerFactoryBean.setPackagesToScan(new String[] { my.domains.package });

    entityManagerFactoryBean.setJpaProperties(hibProperties());

    return entityManagerFactoryBean;
}

private Properties hibProperties() {
    Properties properties = new Properties();
    properties.put("hibernate.dialect", env.getRequiredProperty("hibernate.dialect"));
    properties.put("hibernate.show_sql", env.getRequiredProperty("hibernate.show_sql"));
    properties.put("hibernate.hbm2ddl.auto", env.getRequiredProperty("hibernate.hbm2ddl.auto"));
    return properties;
}

@Bean
public JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
    JpaTransactionManager transactionManager = new JpaTransactionManager();
    transactionManager.setEntityManagerFactory(entityManagerFactory);
    return transactionManager;
}

2)Domain

@Entity
@Table(name="Emp_Detetail")
public class EmpDetail implements java.io.Serializable {

private static final long serialVersionUID = 7342724430491939936L;

@Column(name="EmployeeId")
@Id
@GeneratedValue
private int employeeId;

   .......
}

3)JPA Respository

public interface EmpDetailRepository extends JpaRepository<EmpDetail, Integer>  {    

   }

4) DAO

@Repository("empDetailDao")
public class EmpDetailDaoImpl implements EmpDetailDao {

  @Resource
   private EmpDetailRepository empDetailRepository;

  @Override
  @Transactional
  public EmpDetail insertEmpDetails(EmpDetail empDetail) {
    return empDetailRepository.saveAndFlush(archive);
  }
}

5) Service Class

@Service
public class EmpDetailServiceImpl implements EmpDetailService{

  @Autowired
  private EmpDetailDao empDetailDao;

  @Autowired
  private EmpDetail empBO;

 private EmpDetail toInsertEmpDetails(int active, String empName) throws
  Exception {
     empBO.setName(empName);
     empBO.setActive(active);
    empBO = empDetailDao.insertEmpDetails(empBO);
   }
   return empBO;
 }

6) Controller code is

 @RestController
 public class EmpDeatilController {

  @Resource
  private EmpDetailService empDetailService;

  @RequestMapping(value = "/insertEmpDetail", method =
    RequestMethod.GET)
  @ResponseBody
  public EmpDetialResponse insertEmpDetail(@RequestParam("empName") String
    empName, @RequestParam("active") int active) throws Exception{

     return empDetailService.toInsertEmpDetails(active, empName);
   }

 }

Please help me.

Thanks in advance

Upvotes: 1

Views: 3363

Answers (1)

dunni
dunni

Reputation: 44545

When you insert the first entry, you save the inserted object in the field

@Autowired
private EmpDetail empBO;

in the EmpDetailServiceImpl bean. Since this is a singleton bean, when you do further calls of the method toInsertEmpDetails, it will use the saved object, update its name and active flag and persist this. Since this object then already has an id (from your first call), it will update the entry in the database instead of creating a new one. To solve that, just remove the field empBO, there is usually no need to have such a field in a service (which should be stateless).

Upvotes: 2

Related Questions