JPA EntityManager 獲取session
阿新 • • 發佈:2018-12-30
@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)