public static void main(String[] args) { // Start EntityManagerFactory EntityManagerFactory emf = Persistence.createEntityManagerFactory("black", new DBConnector().mysql); // First unit of work EntityManager em = emf.createEntityManager(); EntityTransaction tx = em.getTransaction(); tx.begin(); // Persist data MessageHibModel MessageHib = new MessageHibModel("Hello World with JPA and JTA"); em.persist(MessageHib); // Commit & close tx.commit(); em.close(); // Second unit of work EntityManager newEm = emf.createEntityManager(); EntityTransaction newTx = newEm.getTransaction(); newTx.begin(); MessageHibModel m = new MessageHibModel(); m.setText("Hello World with JPA and JTA"); @SuppressWarnings("unchecked") List<EntityManager> MessageHibs = newEm .createQuery( "select m from MessageHibModel m where m.text like :sText order by m.text asc") .setParameter("sText", m.getText()) .setFlushMode(FlushModeType.COMMIT) // .setHint("org.hibernate.cacheMode",org.hibernate.CacheMode.IGNORE) .setHint("org.hibernate.cacheable", true) .setHint("org.hibernate.readOnly", true) .setHint("org.hibernate.comment", "My Comment...") .setFirstResult(1) // .getSingleResult() .setMaxResults(20) .getResultList(); System.out.println(MessageHibs.size() + " Message(s) found:"); for (Object m1 : MessageHibs) { MessageHibModel loadedMsg = (MessageHibModel) m1; System.out.println(loadedMsg.getText()); } newTx.commit(); newEm.close(); // Shutting down the application emf.close(); }
/** * Get the EntityManager for the specified persistence unit name. * * @param name The persistence unit name */ public EntityManager em(String name) { EntityManagerFactory emf = emfs.get(name); if (emf == null) { return null; } return emf.createEntityManager(); }
@Test public void test() { EntityManagerFactory emf = Persistence.createEntityManagerFactory("FormationJPA"); assertNotNull(emf); EntityManager em = emf.createEntityManager(); assertNotNull(em); }
public static void main(String[] args) { try { EntityManagerFactory f = Persistence.createEntityManagerFactory("DemoPU"); EntityManager manager = f.createEntityManager(); Scanner in = new Scanner(System.in); System.out.print("Enter id to modify"); int id = in.nextInt(); in.nextLine(); Emp e = manager.find(Emp.class, id); System.out.println("current details are"); System.out.println(e.getEname() + "\t" + e.getJob() + "\t" + e.getSalary()); System.out.println("Enter name to update"); String n = in.nextLine(); System.out.println("Enter job to update"); String j = in.nextLine(); System.out.println("Enter salary to update"); int s = in.nextInt(); EntityTransaction t = manager.getTransaction(); t.begin(); e.setEname(n); e.setJob(j); e.setSalary(s); t.commit(); manager.close(); System.out.println("updated"); } catch (Exception e) { System.out.println(e); } }
public EntityManager getEntityManager() { if (emf == null) { emf = Persistence.createEntityManagerFactory("BolaoPU"); } // if (em == null) { // em = emf.createEntityManager(); // } return emf.createEntityManager(); }
public static void main(String[] args) throws ParseException { EntityManagerFactory emf = Persistence.createEntityManagerFactory("meujpa"); EntityManager em = emf.createEntityManager(); SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); Date d = sdf.parse("15/08/2015"); Date e = sdf.parse("25/09/2015"); Funcionario f1 = new Funcionario(null, "Pedro", "Porteiro"); Cliente c1 = new Cliente(null, "João", "3225448"); Cliente c2 = new Cliente(null, "Maria", "96685421"); Cliente c3 = new Cliente(null, "José", "87787451"); Veiculo v1 = new Veiculo(null, "NGK9246", c1); Veiculo v2 = new Veiculo(null, "UTC1234", c2); Veiculo v3 = new Veiculo(null, "MMM6666", c3); Veiculo v4 = new Veiculo(null, "TNT4444", c1); TipoLocacao tipo1 = new TipoLocacao(null, "Horista", new BigDecimal(5.00)); TipoLocacao tipo3 = new TipoLocacao(null, "Mensal", new BigDecimal(2.00)); Vaga vg1 = new Vaga(null, 1, true); Vaga vg2 = new Vaga(null, 2, true); Vaga vg3 = new Vaga(null, 3, false); Locacao loc1 = new Locacao(null, d, f1, v4, vg2, c1, tipo1); Locacao loc2 = new Locacao(null, e, f1, v3, vg1, c3, tipo3); loc1.consultarValorPagar(); em.getTransaction().begin(); em.persist(f1); em.persist(c1); em.persist(c2); em.persist(c3); em.persist(v1); em.persist(v2); em.persist(v3); em.persist(v4); em.persist(tipo1); em.persist(tipo3); em.persist(vg1); em.persist(vg2); em.persist(vg3); em.persist(loc1); em.persist(loc2); em.getTransaction().commit(); em.close(); emf.close(); }
public static void initialiseSubscriptions( EntityManagerFactory entityManagerFactory, Long immediateFrequency) { EntityManager badSubsEm = entityManagerFactory.createEntityManager(); TypedQuery<Subscription> badSubsQuery = badSubsEm.createNamedQuery("subscription.unInitialised", Subscription.class); List<Subscription> uninitialisedSubscriptions = badSubsQuery.getResultList(); badSubsEm.close(); if (uninitialisedSubscriptions.size() > 0) { logger.debug("Initialising {} subscriptions", uninitialisedSubscriptions.size()); for (Subscription s : uninitialisedSubscriptions) { logger.debug( "Scheduling new run for {} subscription {}", s.getSubscriber().emailAddress, s.getId()); EntityManager schedEm = entityManagerFactory.createEntityManager(); schedEm.getTransaction().begin(); s.calculateNextScheduledRun(immediateFrequency); schedEm.merge(s); schedEm.getTransaction().commit(); schedEm.close(); } } }
@SuppressWarnings("unchecked") List<Object> listagem() { EntityManagerFactory factory = Persistence.createEntityManagerFactory("trendsoftwareDB"); EntityManager em = factory.createEntityManager(); String sql = "select b from Banco b"; Query q = em.createQuery(sql); List<Object> listBanco = q.getResultList(); return listBanco; }
/** @param args */ public static void main(String[] args) { EntityManagerFactory emf = null; EntityManager em = null; Map<String, String> properties = new HashMap<String, String>(); properties.put(DDL_GENERATION, DROP_AND_CREATE); properties.put(DDL_GENERATION_MODE, DDL_BOTH_GENERATION); properties.put(TARGET_DATABASE, TargetDatabase.Oracle); emf = PersistenceService.createEMF(properties, true, new EclipseLinkServiceFactory(), true); em = emf.createEntityManager(); em.close(); emf.close(); }
@Before public void setUp() throws Exception { try { Class.forName("org.hsqldb.jdbcDriver"); connection = DriverManager.getConnection("jdbc:hsqldb:mem:unit-testing-jpa", "sa", ""); } catch (Exception ex) { ex.printStackTrace(); fail("Exception during HSQL database startup."); } try { emFactory = Persistence.createEntityManagerFactory("MyPersistence"); em = emFactory.createEntityManager(); } catch (Exception ex) { ex.printStackTrace(); fail("Exception during JPA EntityManager instanciation."); } }
public static void main(String args[]) { EntityManagerFactory factory = Persistence.createEntityManagerFactory("testdbproj", System.getProperties()); EntityManager em = factory.createEntityManager(); em.getTransaction().begin(); Link l = (Link) em.find(Link.class, 1); l.setLink("cnn.com"); em.getTransaction().commit(); em.close(); System.out.println("Done."); }
public static void main(String[] args) throws Exception { HashMap map = new HashMap(); // map.put("hibernate.show_sql", "true"); EntityManagerFactory factory = Persistence.createEntityManagerFactory("titan", map); EntityManager entityManager = factory.createEntityManager(); entityManager.getTransaction().begin(); try { System.out.println("Initialize DB"); InitializeDB.initialize(entityManager); System.out.println(); System.out.println(); System.out.println("Find Bill Burke by named parameter"); Customer cust = findCustomerByNamedParameter(entityManager, "Bill", "Burke"); System.out.println("Bill Burke's cust id: " + cust.getId()); System.out.println(); System.out.println(); System.out.println("Find Gavin King by indexed parameter"); cust = findCustomerByIndexedParameter(entityManager, "Gavin", "King"); System.out.println("Gavin King's cust id: " + cust.getId()); System.out.println(); System.out.println(); System.out.println("Output all customers via paging"); List results; int first = 0; int max = 2; do { results = getCustomers(entityManager, max, first); Iterator it = results.iterator(); while (it.hasNext()) { Customer c = (Customer) it.next(); System.out.println(c.getFirstName() + " " + c.getLastName()); } entityManager.clear(); first = first + results.size(); } while (results.size() > 0); } finally { entityManager.getTransaction().commit(); entityManager.close(); factory.close(); } }
/** @param args */ public static void main(String[] args) { // TODO Auto-generated method stub EntityManagerFactory emf = Persistence.createEntityManagerFactory("hello"); EntityManager em = emf.createEntityManager(); EmployeeService service = new EmployeeService(em); em.getTransaction().begin(); Department dept1 = service.createDepartment(1, "Timepass"); Department dept2 = service.createDepartment(2, "Housekeeping"); WorkStation ws1 = service.createWorkStation(1, "Unit-0"); WorkStation ws2 = service.createWorkStation(2, "Unit-1"); WorkStation ws3 = service.createWorkStation(3, "Unit-0"); Employee emp = service.createEmployee(50948, "Sagar", 60000, dept1, ws1); em.getTransaction().commit(); System.out.println("Persisted " + emp); emp = service.findEmployee(50948); System.out.println("Found " + emp); em.getTransaction().begin(); emp = service.raiseEmployeeSalary(50948, 20000); em.getTransaction().commit(); System.out.println("Updated " + emp); em.getTransaction().begin(); service.createEmployee(50949, "Renu", 90000, dept1, ws2); service.createEmployee(50950, "Mrudula", 80000, dept2, ws3); em.getTransaction().commit(); List<Employee> emps = service.findAllEmployees(); for (Employee e : emps) { System.out.println("All employees :: " + e); } em.close(); emf.close(); }
protected void transactional(Consumer<EntityManager> consumer) { EntityManager em = emf.createEntityManager(); EntityTransaction tx = em.getTransaction(); boolean success = false; try { tx.begin(); consumer.accept(em); success = true; } finally { try { if (success) { tx.commit(); } else { tx.rollback(); } } finally { em.close(); } } }
public static void main(String[] args) { EntityManager em = emf.createEntityManager(); try { // 开启事务 em.getTransaction().begin(); List result = em.createQuery( "select p.name , address.detail" + " from Person as p" + " join p.addresses address") .setFirstResult(3) .setMaxResults(2) .getResultList(); for (int i = 0; i < result.size(); i++) { Object[] row = (Object[]) result.get(i); System.out.println(java.util.Arrays.toString(row)); } // 提交事务 em.getTransaction().commit(); } finally { em.close(); } }
public static void initializeEntityManagerFactory(EntityManagerFactory entityManagerFactory) { BaseDAO.entityManagerFactory = entityManagerFactory; entityManager = entityManagerFactory.createEntityManager(); }
public ProdutoRepository() { factory = Persistence.createEntityManagerFactory("ProjetoJPA"); manager = factory.createEntityManager(); }
public void importColumns() throws Exception { LOGGER.info("List of objects for source: " + stageSourceCode); EntityManagerFactory emf = Persistence.createEntityManagerFactory("OpenBIStage"); EntityManager em = emf.createEntityManager(); Query query; // get source query = em.createQuery("SELECT x FROM StageSource x WHERE x.etlStageSourceCode = ?1"); query.setParameter(1, stageSourceCode); List<StageSource> sources = query.getResultList(); // get source objects and dbs List<StageObject> objects = sources.get(0).getStageObject(); List<StageSourceDb> sourcedbs = sources.get(0).getStageSourceDb(); // load properties from property file String dbpropertyfile = "datasources/" + sourcedbs.get(0).getEtlStageSourceDbJdbcname() + ".properties"; Properties dbproperties = new Properties(); dbproperties.load(new FileInputStream(dbpropertyfile)); // Configure db connection org.opendatakraken.core.db.DBConnection sourceConnectionBean = new org.opendatakraken.core.db.DBConnection(); sourceConnectionBean.setPropertyFile(dbproperties.getProperty("srcconnaddpropertyfile")); sourceConnectionBean.setDatabaseDriver(dbproperties.getProperty("srcdbdriverclass")); sourceConnectionBean.setConnectionURL(dbproperties.getProperty("srcdbconnectionurl")); sourceConnectionBean.setUserName(dbproperties.getProperty("srcdbusername")); sourceConnectionBean.setPassWord(dbproperties.getProperty("srcdbpassword")); sourceConnectionBean.openConnection(); DictionaryExtractor dataDict = new DictionaryExtractor(); dataDict.setSourceConnection(sourceConnectionBean); // For each object String sourceIdentifier; for (StageObject object : objects) { // Dermine source identifier sourceIdentifier = object.getEtlStageObjectName(); if (!(sourcedbs.get(0).getEtlStageSourceOwner().equals("")) && sourcedbs.get(0).getEtlStageSourceOwner() != null) { sourceIdentifier = sourcedbs.get(0).getEtlStageSourceOwner() + "." + sourceIdentifier; } dataDict.setSourceTable(sourceIdentifier); dataDict.retrieveColumns(); String[] colNames = dataDict.getColumnNames(); String[] colDefs = dataDict.getColumnDefinition(); String[] colOriginalDefs = dataDict.getColumnDefinition(); int[] colPkPos = dataDict.getColumnPkPositions(); em.getTransaction().begin(); for (int i = 0; i < colNames.length; i++) { query = em.createQuery( "SELECT x FROM StageColumn x WHERE x.etlStageObjectId = ?1 AND x.etlStageColumnName = ?2"); query.setParameter(1, object.getEtlStageObjectId()); query.setParameter(2, colNames[i]); List<StageColumn> columns = query.getResultList(); StageColumn column; if (columns.size() == 0) { column = new StageColumn(); column.setEtlStageObjectId(BigDecimal.valueOf(object.getEtlStageObjectId())); column.setEtlStageColumnPos(BigDecimal.valueOf(i + 1)); column.setEtlStageColumnName(colNames[i]); column.setEtlStageColumnDef(colDefs[i]); column.setEtlStageColumnDefSrc(colOriginalDefs[i]); column.setEtlStageColumnEdwhFlag(BigDecimal.valueOf(1)); if (colPkPos[i] > 0) { column.setEtlStageColumnNkPos(BigDecimal.valueOf(colPkPos[i])); object.setEtlStageSourceNkFlag(BigDecimal.valueOf(1)); } em.persist(column); } else { column = columns.get(0); column.setEtlStageColumnPos(BigDecimal.valueOf(i + 1)); column.setEtlStageColumnDef(colDefs[i]); column.setEtlStageColumnDefSrc(colOriginalDefs[i]); if (colPkPos[i] > 0) { column.setEtlStageColumnNkPos(BigDecimal.valueOf(colPkPos[i])); object.setEtlStageSourceNkFlag(BigDecimal.valueOf(1)); } } } em.getTransaction().commit(); } }
private EntityManager getEntityManager() { return emf.createEntityManager(); }
public EntityManager getEntityManager() { if (this.manager == null) { this.manager = factory.createEntityManager(); } return manager; }
public AutomóvelRepositórioImpl() { EntityManagerFactory factory; factory = Persistence.createEntityManagerFactory("mysql-local"); entityManager = factory.createEntityManager(); }
public BookService() { EntityManagerFactory emf = Persistence.createEntityManagerFactory("BookPersistenceUnit"); em = emf.createEntityManager(); }
public ProdutoDAO() { // Ler o persistence.xml emf = Persistence.createEntityManagerFactory("lm_bemcasadoPU"); // Criano EntityManager em = emf.createEntityManager(); }
public EntityManager getEntityManager() { return emf.createEntityManager(); }
private DB() { emfConfig = Persistence.createEntityManagerFactory("$objectdb/db/config.odb"); emConfig = emfConfig.createEntityManager(); }
public EntityManager getEntityManager() { return factory.createEntityManager(); }