Example usage for javax.persistence Persistence createEntityManagerFactory

List of usage examples for javax.persistence Persistence createEntityManagerFactory

Introduction

In this page you can find the example usage for javax.persistence Persistence createEntityManagerFactory.

Prototype

public static EntityManagerFactory createEntityManagerFactory(String persistenceUnitName) 

Source Link

Document

Create and return an EntityManagerFactory for the named persistence unit.

Usage

From source file:example.springdata.jpa.basics.BasicSample.java

/**
 * Sets up a {@link SimpleJpaRepository} instance.
 *//*from   w w w .  j  a v  a 2 s.  c  o m*/
@Before
public void setUp() {

    EntityManagerFactory factory = Persistence.createEntityManagerFactory("jpa.sample.plain");
    em = factory.createEntityManager();

    userRepository = new SimpleJpaRepository<User, Long>(User.class, em);

    em.getTransaction().begin();
}

From source file:eu.xipi.bro4xipi.PersistenceManager.java

protected void createEntityManagerFactory() {

    this.emf = Persistence.createEntityManagerFactory("bro4xipipers");
    logger.info("n*** Persistence started at " + new java.util.Date());
}

From source file:org.kuali.rice.krad.data.jpa.JpaMetadataProviderTest.java

@BeforeClass
public static void setUpBeforeClass() throws Exception {
    metadataProvider = new EclipseLinkJpaMetadataProviderImpl();
    EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("krad-data-unit-test");
    metadataProvider.setEntityManager(entityManagerFactory.createEntityManager());
}

From source file:edu.harvard.i2b2.fhirserver.ejb.AuthTokenBean.java

@PostConstruct
public void init() {
    try {//  w ww .  ja v  a 2  s.  c om
        EntityManagerFactory factory = Persistence.createEntityManagerFactory("testPer");
        em = factory.createEntityManager();
        Random r = new Random();
        String rs = Integer.toString(r.nextInt());
        createAuthToken(rs, rs, rs, rs, rs, rs, rs, rs);
        logger.info("total:" + totalCount());
        // createAuthToken("clientId232" + r.nextInt());
    } catch (Exception ex) {
        logger.error("", ex);
    }
}

From source file:es.uvigo.ei.sing.rubioseq.gui.util.DBInitializer.java

/**
 * This method is responsible for the initializacion of the BD, that is:
 * - Creating the default RUbioSeqConfiguration.
 * - Creating the default users.//from ww w . j a  v  a  2  s  . c om
 * - Creating a datastore pointing to "/" for the admin user.
 * 
 * This method also plays a key role in the deployment of the application 
 * since it prints the message "[DBInitializer] DB initialized." which is
 * triggered by the launch-rubioseq-gui.sh in order to know that the app. is
 * deployed and launch a browser.
 * 
 * @author hlfernandez
 */
static void initDatabase() {
    System.out.println("[DBInitializer] Initializing DB ...");

    EntityManagerFactory emf = Persistence.createEntityManagerFactory("rubioseq-database");
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = null;
    try {
        /*
         * Store Global Configuration
         */
        if (em.createQuery("SELECT u FROM RUbioSeqConfiguration u").getResultList().size() == 0) {
            RUbioSeqConfiguration config = new RUbioSeqConfiguration();
            config.setRubioseqCommand("/opt/RUbioSeq3.7/RUbioSeq.pl");
            config.setPrivateDatastoresRootDirectory("/path/to/private/datastores/root");
            config.setCreatePrivateDatastoresOnUserRegistration(false);

            tx = em.getTransaction();
            try {
                tx.begin();
                em.persist(config);
                tx.commit();
            } finally {
                if (tx != null && tx.isActive()) {
                    tx.rollback();
                }
            }
        }
        /*
         * Create Default Users
         */
        if (em.createQuery("SELECT u FROM User u").getResultList().size() == 0) {
            User user = new User();
            user.setUsername("rubiosequser");
            user.setPassword(DigestUtils.md5Hex("rubioseqpass"));
            user.setAdmin(false);
            user.setEmail("rubiosequser@rubioseg.org");

            tx = em.getTransaction();
            try {
                tx.begin();
                em.persist(user);
                tx.commit();
            } finally {
                if (tx != null && tx.isActive()) {
                    tx.rollback();
                }
            }

            user = new User();
            user.setUsername("admin");
            user.setPassword(DigestUtils.md5Hex("admin"));
            user.setAdmin(true);
            user.setEmail("rubiosequser@rubioseg.org");

            tx = em.getTransaction();
            try {
                tx.begin();
                em.persist(user);
                tx.commit();
            } finally {
                if (tx != null && tx.isActive()) {
                    tx.rollback();
                }
            }
        }
        /*
         * Create Default Datastores
         */
        boolean createDefaultAdminDatastore = true;
        List<User> adminUsers = getAdminUsers(em);
        @SuppressWarnings("unchecked")
        List<DataStore> datastores = (List<DataStore>) em.createQuery("SELECT d FROM DataStore d")
                .getResultList();
        for (User adminUser : adminUsers) {
            if (datastores.size() == 0) {
                createDefaultAdminDatastore = true;
            } else {
                for (DataStore d : datastores) {
                    if (d.getUser() != null && d.getUser().equals(adminUser) && d.getPath().equals("/")) {
                        createDefaultAdminDatastore = false;
                    }
                }
            }
            if (createDefaultAdminDatastore) {
                DataStore adminDS = new DataStore();
                adminDS.setUser(adminUser);
                adminDS.setPath("/");
                adminDS.setMode(DataStoreMode.Private);
                adminDS.setType(DataStoreType.Input_Output);
                adminDS.setName(adminUser.getUsername() + "_default");

                tx = em.getTransaction();
                try {
                    tx.begin();
                    em.persist(adminDS);
                    tx.commit();
                } finally {
                    if (tx != null && tx.isActive()) {
                        tx.rollback();
                    }
                }
            }
        }
    } finally {
        em.close();
    }

    System.out.println("[DBInitializer] DB initialized.");
}

From source file:io.dacopancm.oraclesp.MainApp.java

public void insertConferencia(int idx, Date dateInicio, Date dateFin, String name) {
    try {/*from   w ww. j ava  2 s.  c om*/
        EntityManagerFactory emf = Persistence
                .createEntityManagerFactory("io.dacopancm_oracleSP_jar_1.0-SNAPSHOTPU");
        ConferenciaJpaController conferenciaCtl = new ConferenciaJpaController(emf);

        //taremos todas las conferencias
        List<Conferencia> conferencias = conferenciaCtl.findConferenciaEntities();

        //recorremos para probar si esa fecha esta o no en conflicto
        for (Conferencia c : conferencias) {
            if (Helper.overlapDate(c.getCfrInicio(), c.getCfrFin(), dateInicio, dateFin)) {
                log.error("ya existe una confernecia en esas horas");
                log.error(c);
                return;
            }
        }
        Conferencia c = new Conferencia();
        c.setCfrId(new BigDecimal(idx));
        c.setCfrInicio(dateInicio);
        c.setCfrFin(dateFin);
        c.setCfrNombre(name);

        conferenciaCtl.create(c);
        //conferenciaCtl.destroy(c.getCfrId());
    } catch (Exception ex) {
        log.error(ex);
    }
}

From source file:ro.allevo.fintpws.security.CustomUserDetailsService.java

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

    EntityManagerFactory configEntityManagerFactory = Persistence
            .createEntityManagerFactory(ApiResource.PERSISTENCE_UNITNAME_CONFIG);
    EntityManager emc = configEntityManagerFactory.createEntityManager();

    final TypedQuery<UserEntity> query = emc.createNamedQuery("UserEntity.findByUsername", UserEntity.class);

    final java.util.List<UserEntity> results = query.setParameter("username", username).getResultList();

    if (!results.isEmpty()) {
        return results.get(0);
    }/*from   w w  w . j ava  2s .c  o  m*/
    return null;

}

From source file:fr.natoine.servletTag.ServletTag.java

/**
  * @see HttpServlet#HttpServlet()//w  ww. j av a  2  s .  c  o  m
  */
public ServletTag() {
    super();
    emf_annotation = Persistence.createEntityManagerFactory("annotation");
    daoTag = new DAOTag(emf_annotation);
}

From source file:facades.PersonFacadeDB.java

@Override
public Person addPerson(String json) {
    //make person from Json
    Person p = gson.fromJson(json, Person.class);

    EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceFileName);
    EntityManager em = emf.createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    transaction.begin();/*from w  w w  .jav a 2s .co m*/

    try {
        em.persist(p);
        transaction.commit();
    } catch (Exception e) {
        transaction.rollback();
    } finally {
        em.close();
    }
    return p;
}

From source file:cz.PA165.vozovyPark.dao.ServiceIntervalDAOTest.java

/**
 *
 * @throws ParseException/*from  w w  w. j  a v  a  2  s .  c o  m*/
 */
@Before
public void setUp() throws ParseException {

    emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
    em = emf.createEntityManager();

    VehicleDAOImpl vehicleDaoImpl = new VehicleDAOImpl(em);
    ServiceIntervalDAOImpl serviceIntervalDaoImpl = new ServiceIntervalDAOImpl(em);
    this.vehicleDao = vehicleDaoImpl;
    this.serviceIntervalDAO = serviceIntervalDaoImpl;

    //cleaning
    List<ServiceInterval> allServiceIntervals = serviceIntervalDAO.findAll();
    for (ServiceInterval si : allServiceIntervals) {
        em.getTransaction().begin();
        serviceIntervalDAO.removeSI(si);
        em.getTransaction().commit();
    }
    Collection<Vehicle> allVehicles = vehicleDao.findAll();
    for (Vehicle v : allVehicles) {
        em.getTransaction().begin();
        vehicleDao.removeVehicle(v);
        em.getTransaction().commit();
    }

}