SessionFactory或EntityManager是否与jpa存储库一起使用?

时间:2018-08-09 10:31:23

标签: spring spring-boot entitymanager sessionfactory hibernate-entitymanager

我对SessionFactoryEntityManagerJpaRepository感到困惑。我与SessionFactory一起工作,当多个请求why need to make sessionfactory到来时,它有助于减轻服务器的负担。为此,我使用了DaoImpl类。

DaoImpl类

@Repository
public class StudentDaoImpl implements StudentDao{

    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public void saveOrUpdate(Student student) {
        sessionFactory.getCurrentSession().saveOrUpdate(student);       
    }
}

现在,我尝试将 SpringBoot 2 jpa存储库一起使用。以下代码可以正常工作。

StudentRepository界面

@Repository
public interface StudentRepository extends JpaRepository<Student, Integer>{     

}

StudentService界面

public interface StudentService {
    void save(Student student)
}

StudentServiceImpl类

@Service
@Transactional
public class StudentServiceImpl implements StudentService {

    @Autowired
    StudentRepository studentRepository;

    @Override
    public void save(Student student) {
        studentRepository.save(student);        
    }
}

很少有引用说如果我们使用EntityManager Why use an entity manager会更好。如果我要使用EntityManager,希望代码如下

@PersistenceContext
protected EntityManager entityManager;

public void save(Student student){    
    em.getTransaction().begin();
    if (!em.contains(student)) {
        em.persist(student);
        em.flush();
    }
    em.getTransaction().commit();
}

我的问题是,由于我不将SessionFactory或EntityManager与jpa存储库一起使用,因此它完美地将数据存储在数据库中。我需要使用实体管理器吗?我不能使用Sessionfactory吗?如果同时有多个请求,jpa存储库会处理吗?有什么好的做法?

谢谢。

0 个答案:

没有答案
相关问题