JPA EntityManager 获取session

@Service
public class TestDaoImpl implements TestDao {
    private static final Logger logger = LoggerFactory.getLogger(TestDaoImpl.class);

    protected EntityManager entityManager = null;


    @PersistenceContext
    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    @Override
    public void save(TestEntity entity) {
        entityManager.persist(entity);
    }

    public void clear(){
        try {
            HibernateEntityManager hEntityManager = (HibernateEntityManager)entityManager;
            Session session = hEntityManager.getSession();
            Query query = session.createSQLQuery("delete from test");
            query.executeUpdate();
        }catch (Exception e){
            logger.error(e.getMessage(),e);
        }
    }

}
 
  
 
  

当然,别忘了,在service层,得加上@Transactional注解(因为hibernate默认,autocommit=false)

你可能感兴趣的:(Java)