@fernandopaiva escreveu:
Criei um projeto Swing com JPA que esta funcionando bem. Agora quero retirar o arquivo persistence.xml e usar o EntityManager programaticamente. Para isso, estou tentando criar o EntityManagerFactory mas nao esta funcionando, sempre retorna nulo. Como resolver esse problema ?
Estou tentando assim.
public class JPAUtils { private static EntityManagerFactory emf; /** retorna o EntityManagerFactory */ public static EntityManagerFactory getEntityManagerFactory(){ if(emf == null){ PersistenceProvider pp = new PersistenceProvider(); Map<String, Object> properties = new HashMap<String, Object>(); properties.put(PersistenceUnitProperties.TRANSACTION_TYPE, PersistenceUnitTransactionType.RESOURCE_LOCAL.name()); properties.put(PersistenceUnitProperties.JDBC_DRIVER, "com.mysql.jdbc.Driver"); properties.put(PersistenceUnitProperties.JDBC_URL, "jdbc:mysql://localhost:3306/iguanaauto_db?createDatabaseIfNotExist=true"); properties.put(PersistenceUnitProperties.JDBC_USER, "root"); properties.put(PersistenceUnitProperties.JDBC_PASSWORD, ""); properties.put(PersistenceUnitProperties.DDL_GENERATION, PersistenceUnitProperties.CREATE_OR_EXTEND); properties.put(PersistenceUnitProperties.DDL_GENERATION_MODE, PersistenceUnitProperties.DDL_DATABASE_GENERATION); properties.put(PersistenceUnitProperties.LOGGING_LEVEL, Level.FINE); emf = pp.createEntityManagerFactory("default", properties); } return emf; } }
Aqui o GenericDAO
public class GenericDAO<T> implements IPersistence<T>{ private EntityManager em; public GenericDAO() { em = JPAUtils.getEntityManagerFactory().createEntityManager(); } @Override public void insert(T obj) { try{ em.getTransaction().begin(); em.persist(obj); em.getTransaction().commit(); }catch(PersistenceException e){ JOptionPane.showMessageDialog(null, e.getLocalizedMessage(), "Erro de insert", JOptionPane.ERROR_MESSAGE); } } @Override public void update(T obj) { try{ em.getTransaction().begin(); em.merge(obj); em.getTransaction().commit(); }catch(Exception e){ JOptionPane.showMessageDialog(null, e.getLocalizedMessage(), "Erro de update", JOptionPane.ERROR_MESSAGE); } } @Override public void delete(T obj) { try{ em.getTransaction().begin(); em.remove(obj); em.getTransaction().commit(); }catch(Exception e){ JOptionPane.showMessageDialog(null, e.getLocalizedMessage(), "Erro de delete", JOptionPane.ERROR_MESSAGE); } } @Override public EntityManager getSession() { return em; } }
Mensagens: 1
Participantes: 1