Spring 4.3.0.RELEASE + Hibernate 5.2.0.Final – Inert duplicate rows each time

Hi,
There is a lot of version of this problem but all the wats to fix it are failed.
Every time I insert object, it insert me duplicate data

I tried to change the add function with “persist(role)” or “saveOrUpdate(role)” but it is`nt working.

What could be the problem?

StartupDbDataInit

package com.searcher.startup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import com.searcher.dao.EcommerceDAO;
import com.searcher.dao.RoleDAO;
import com.searcher.dao.UserDAO;
import com.searcher.entity.EcommerceEntity;
import com.searcher.entity.RoleEntity;
import com.searcher.service.RoleService;
import com.searcher.service.RoleServiceImp;

@Component
public class StartupDbDataInit implements ApplicationListener<ContextRefreshedEvent>{

    private static final Logger logger = LoggerFactory.getLogger(StartupDbDataInit.class);

    @Autowired
    private RoleService roleService;

    @Override
    public void onApplicationEvent(final ContextRefreshedEvent event) {
        try{
            // Creatinw Role Entity
            RoleEntity roleUser = new RoleEntity();
            RoleEntity roleAdmin = new RoleEntity();

            roleUser.setName("ROLE_USER");
            roleAdmin.setName("ROLE_ADMIN");

            roleService.add(roleUser);
            roleService.add(roleAdmin);
            logger.info("------------------------------------------------------");
            logger.info("StartupDbDataInit Working!!!!!");
            logger.info("------------------------------------------------------");

            // TODO: Swhatever you need here
            }catch (Exception ex){
                logger.info("StartupDbDataInit Failed!!!!!, SellerEntity Details="+ex.getMessage());
                throw ex;
            }
    }
}

RoleEntity.java:

package com.searcher.entity;

import java.util.Set;

import javax.persistence.*;

@Entity
@Table(name = "role")
public class RoleEntity {

    @Id
    @GeneratedValue
    @Column(name="Id")
    private Long Id;

    @Column(name="Name")
    private String Name;

    @ElementCollection(targetClass=UserEntity.class)
    private Set<UserEntity> users;

    public Long getId() {
        return Id;
    }
    public void setId(Long id) {
        this.Id = id;
    }
    public String getName() {
        return Name;
    }
    public void setName(String name) {
        this.Name = name;
    }

    @ManyToMany(mappedBy = "roles")
    public Set<UserEntity> getUsers() {
        return users;
    }
    public void setUsers(Set<UserEntity> users) {
        this.users = users;
    }
}

RoleDAO.java (interface)

package com.searcher.dao;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.searcher.entity.RoleEntity;

@Repository
public interface RoleDAO {
    public void add(RoleEntity role);
    public void edit(RoleEntity role);
    public void deleteById(int id);
    public RoleEntity getRoleById(int id);
    public RoleEntity getRoleByName(String name);
    public List<RoleEntity> getAllRole();
}

RoleDAOImp.java

package com.searcher.dao;

import java.util.List;

import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.searcher.entity.RoleEntity;

@Repository
public class RoleImp implements RoleDAO {

    private static final Logger logger = LoggerFactory.getLogger(RoleDAO.class);

    @Autowired
    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sf){
        this.sessionFactory = sf;
    }

    @Override
    public void add(RoleEntity role) {
        this.sessionFactory.getCurrentSession().saveOrUpdate(role);
        logger.info("RoleEntity saved successfully, RoleEntity Details="+role);
    }

    @Override
    public void edit(RoleEntity role) {
        this.sessionFactory.getCurrentSession().update(role);
        logger.info("RoleEntity updated successfully, RoleEntity Details="+role);
    }

    @Override
    public void deleteById(int id) {
        RoleEntity roleToDelete = getRoleById(id);
        this.sessionFactory.getCurrentSession().delete(roleToDelete);
        logger.info("RoleEntity deleted successfully, RoleEntity Details="+roleToDelete);
    }

    @Override
    public RoleEntity getRoleById(int id) {
        RoleEntity roleReturn = (RoleEntity)this.sessionFactory.getCurrentSession().get(RoleEntity.class, id);

        logger.info("RoleEntity founded successfully, RoleEntity Details="+roleReturn);

        return roleReturn;
    }

    @Override
    public RoleEntity getRoleByName(String name) {
        RoleEntity roleReturn = 
                (RoleEntity)this.sessionFactory.getCurrentSession().createNamedQuery("from role where Name =" + name);

        logger.info("RoleEntity founded successfully, RoleEntity Details="+roleReturn);

        return roleReturn;
    }

    @SuppressWarnings({ "unchecked", "deprecation" })
    @Override
    public List<RoleEntity> getAllRole() {
        List<RoleEntity> roleList = this.sessionFactory.getCurrentSession().createQuery("from role").list();
        logger.info("List<RoleEntity> upload successfully, List<RoleEntity> Details="+roleList.toString());
        return roleList;
    }

}

RoleService.java

package com.searcher.service;

import java.util.List;

import com.searcher.entity.RoleEntity;

public interface RoleService {
    public void add(RoleEntity user);
    public void edit(RoleEntity user);
    public void deleteById(int id);
    public RoleEntity getRoleById(int id);
    public RoleEntity getRoleByName(String name);
    public List<RoleEntity> getAllRole();
}

RoleServiceImp.java

package com.searcher.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.searcher.dao.RoleDAO;
import com.searcher.entity.RoleEntity;

@Service("roleService")
public class RoleServiceImp implements RoleService {

    @Autowired
    private RoleDAO roleDAO;


    public RoleDAO getRoleDAO() {
        return roleDAO;
    }

    public void setRoleDAO(RoleDAO roleDAO) {
        this.roleDAO = roleDAO;
    }

    @Override
    @Transactional
    public void add(RoleEntity role) {

        this.roleDAO.add(role);
    }

    @Override
    @Transactional
    public void edit(RoleEntity role) {
        this.roleDAO.edit(role);
    }

    @Override
    @Transactional
    public void deleteById(int id) {
        this.roleDAO.deleteById(id);
    }

    @Override
    @Transactional
    public RoleEntity getRoleById(int id) {
        return this.roleDAO.getRoleById(id);
    }

    @Override
    @Transactional
    public RoleEntity getRoleByName(String name) {
        return this.roleDAO.getRoleByName(name);
    }

    @Override
    @Transactional
    public List<RoleEntity> getAllRole() {
        return (List<RoleEntity>)this.roleDAO.getAllRole();
    }
}

Source: java

Leave a Reply