类javax.persistence.Persistence源码实例Demo

下面列出了怎么用javax.persistence.Persistence的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: vaadinator   文件: AddressbookExampleUIEx.java
@Override
protected PresenterFactory obtainPresenterFactory(String contextPath) {
	if (presenterFactory == null) {
		// simple, overwrite method for e.g. Spring / CDI / ...
		// Entity-Manager NUR Thread-Safe, wenn er injected wird wie hier
		AddressService addressService;
		TeamService teamService;
		EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("AddressbookExample");
		AddressDaoPlain addressDaoPlain = new AddressDaoPlain(entityManagerFactory);
		addressService = new AddressServicePlain(entityManagerFactory, addressDaoPlain);
		TeamDaoPlain teamDaoPlain = new TeamDaoPlain(entityManagerFactory);
		teamService = new TeamServicePlain(entityManagerFactory, teamDaoPlain);
		VaadinViewFactoryEx viewFactory = new VaadinViewFactoryEx();
		presenterFactory = new PresenterFactoryEx(new HashMap<String, Object>(), viewFactory, addressService,
				teamService);
		viewFactory.setPresenterFactory(presenterFactory);
	}
	return presenterFactory;
}
 
源代码2 项目: bookapp-cqrs   文件: ReadIT.java
@Test
public void test() {

	EntityManager em = Persistence.createEntityManagerFactory(
			"ch.bfh.swos.bookapp.book.domain").createEntityManager();

	Query q = em.createQuery("select a from Author a");
	@SuppressWarnings("unchecked")
	List<Author> foundAuthors = q.getResultList();
	Author firstAuthor = foundAuthors.get(0);
	Assert.assertTrue(firstAuthor.getLastname().equals("Tolkien"));

	List<Book> foundBooks = new ArrayList<Book>(firstAuthor.getBooks());
	Book firstBook = foundBooks.get(0);
	Assert.assertTrue(firstBook.getTitle().startsWith("Der Herr der Ringe"));
}
 
源代码3 项目: james-project   文件: JPAEntityManagerModule.java
@Provides
@Singleton
public EntityManagerFactory provideEntityManagerFactory(JPAConfiguration jpaConfiguration) {
    HashMap<String, String> properties = new HashMap<>();
    
    properties.put("openjpa.ConnectionDriverName", jpaConfiguration.getDriverName());
    properties.put("openjpa.ConnectionURL", jpaConfiguration.getDriverURL());
    jpaConfiguration.getCredential()
        .ifPresent(credential -> {
            properties.put("openjpa.ConnectionUserName", credential.getUsername());
            properties.put("openjpa.ConnectionPassword", credential.getPassword());
        });

    List<String> connectionFactoryProperties = new ArrayList<>();
    connectionFactoryProperties.add("TestOnBorrow=" + jpaConfiguration.isTestOnBorrow());
    jpaConfiguration.getValidationQueryTimeoutSec()
        .ifPresent(timeoutSecond -> connectionFactoryProperties.add("ValidationTimeout=" + timeoutSecond * 1000));
    jpaConfiguration.getValidationQuery()
        .ifPresent(validationQuery -> connectionFactoryProperties.add("ValidationSQL='" + validationQuery + "'"));

    properties.put("openjpa.ConnectionFactoryProperties", Joiner.on(", ").join(connectionFactoryProperties));

    return Persistence.createEntityManagerFactory("Global", properties);
}
 
源代码4 项目: tomee   文件: InfoBean.java
@PostConstruct
protected void showWelcomeMessage() {
    String versionString = ClassUtils.getJarVersion(InfoBean.class);

    if (versionString != null) {
        this.applicationMessageVersionInfo = " (v" + versionString + ")";
    }

    this.beanValidationVersion =
            ClassUtils.getJarVersion(Validation.buildDefaultValidatorFactory().getValidator().getClass());

    this.jpaVersion =
            ClassUtils.getJarVersion(Persistence.createEntityManagerFactory("demoApplicationPU").getClass());

    if (!ProjectStage.IntegrationTest.equals(this.projectStage)) {
        this.messageContext.message().text("{msgWelcome}").add();
    }
}
 
源代码5 项目: crushpaper   文件: JpaDb.java
/**
 * Create a JPA entity manager factory which is used to create entity
 * managers which are used to query and commit to the DB.
 */
private synchronized void buildEntityManagerFactory() {
	if (entityManagerFactory != null) {
		return;
	}

	registerShutdownHook(this);

	Map<String, Object> configOverrides = new HashMap<String, Object>();
	String dbPath = dbDirectory.getAbsolutePath();
	configOverrides.put("hibernate.search.default.indexBase", dbPath);
	configOverrides.put("hibernate.connection.url", "jdbc:h2:" + dbPath
			+ File.separator + "db" +
			// Make sure that transactions are fully isolated.
			";LOCK_MODE=1" +
			// Make sure the database is not closed if all of the entity
			// managers are closed.
			";DB_CLOSE_DELAY=-1");

	// This string has to match what is in persistence.xml.
	entityManagerFactory = Persistence.createEntityManagerFactory(
			"manager", configOverrides);
}
 
源代码6 项目: bookapp-cqrs   文件: DeleteIT.java
@Test
public void test() {

	EntityManager em = Persistence.createEntityManagerFactory(
			"ch.bfh.swos.bookapp.book.domain").createEntityManager();

	Query q = em.createQuery("select a from Author a");
	@SuppressWarnings("unchecked")
	List<Author> foundAuthors = q.getResultList();
	Author firstAuthor = foundAuthors.get(0);

	// Write access needs a transaction
	em.getTransaction().begin();
	em.remove(firstAuthor);
	em.getTransaction().commit();
}
 
源代码7 项目: BotLibre   文件: Migrate.java
public void migrate3() {
	Map<String, String> properties = new HashMap<String, String>();
	properties.put(PersistenceUnitProperties.JDBC_PASSWORD, Site.DATABASEPASSWORD);
	properties.put(PersistenceUnitProperties.LOGGING_LEVEL, "fine");
	EntityManagerFactory factory = Persistence.createEntityManagerFactory("botlibre", properties);
	EntityManager em = factory.createEntityManager();
	em.getTransaction().begin();
	try {
		em.createNativeQuery("Update ChatChannel set creator_userid = (Select t2.admins_userid from CHAT_ADMINS t2 where t2.chatchannel_id = id)").executeUpdate();
		em.createNativeQuery("Update Forum set creator_userid = (Select t2.admins_userid from forum_ADMINS t2 where t2.forum_id = id)").executeUpdate();
		em.createNativeQuery("Update BotInstance set creator_userid = (Select t2.admins_userid from PANODRAINSTANCE_ADMINS t2 where t2.instances_id = id)").executeUpdate();
		em.getTransaction().commit();
	} catch (Exception exception) {
		exception.printStackTrace();
	} finally {
		if (em.getTransaction().isActive()) {
			em.getTransaction().rollback();
		}
		em.close();
		factory.close();
	}
}
 
源代码8 项目: AIDR   文件: TestMiscResourceFacadeImp.java
@BeforeClass
public static void setUpBeforeClass() {
	
	miscResourceFacadeImp = new MiscResourceFacadeImp();
	documentNominalLabelResourceFacadeImp = new DocumentNominalLabelResourceFacadeImp();
	documentResourceFacadeImp = new DocumentResourceFacadeImp();
	modelFamilyResourceFacadeImp = new ModelFamilyResourceFacadeImp();
	crisisResourceFacadeImp = new CollectionResourceFacadeImp();
	crisisTypeResourceFacadeImp = new CrisisTypeResourceFacadeImp();
	nominalAttributeResourceFacadeImp = new NominalAttributeResourceFacadeImp();
	userResourceFacadeImp = new UsersResourceFacadeImp();
	nominalLabelResourceFacadeImp = new NominalLabelResourceFacadeImp();
	entityManager = Persistence.createEntityManagerFactory(
			"ProjectDBManagerTest-ejbPU").createEntityManager();
	
	miscResourceFacadeImp.setEntityManager(entityManager);
	modelFamilyResourceFacadeImp.setEntityManager(entityManager);
	crisisResourceFacadeImp.setEntityManager(entityManager);
	crisisTypeResourceFacadeImp.setEntityManager(entityManager);
	userResourceFacadeImp.setEntityManager(entityManager);
	nominalAttributeResourceFacadeImp.setEntityManager(entityManager);
	documentResourceFacadeImp.setEntityManager(entityManager);
	documentNominalLabelResourceFacadeImp.setEntityManager(entityManager);
	nominalLabelResourceFacadeImp.setEntityManager(entityManager);
}
 
源代码9 项目: bookapp-cqrs   文件: UpdateIT.java
@Test
public void test() {

	EntityManager em = Persistence.createEntityManagerFactory(
			"ch.bfh.swos.bookapp.book.domain").createEntityManager();

	Query q = em.createQuery("select a from Author a");
	@SuppressWarnings("unchecked")
	List<Author> foundAuthors = q.getResultList();
	Author firstAuthor = foundAuthors.get(0);

	// Write access needs a transaction
	em.getTransaction().begin();
	firstAuthor.setLastname("OtherName");
	em.getTransaction().commit();
	// Entity is persisted automatically after commit because it is managed
	// by jpa.

	@SuppressWarnings("unchecked")
	List<Author> updatedAuthors = q.getResultList();
	Author updatedAuthor = updatedAuthors.get(0);
	Assert.assertTrue(updatedAuthor.getLastname().equals("OtherName"));
}
 
源代码10 项目: database-rider   文件: EntityManagerProvider.java
private void init(String unitName) {
    if (emf == null) {
        log.debug("creating emf for unit {}", unitName);
        Map<String,String> dbConfig = getDbPropertyConfig();
        log.debug("using dbConfig '{}' to create emf", dbConfig);
        emf = dbConfig == null ? Persistence.createEntityManagerFactory(unitName) : Persistence.createEntityManagerFactory(unitName, dbConfig);
        em =  emf.createEntityManager();
        tx = em.getTransaction();
        if (isHibernateOnClasspath() && em.getDelegate() instanceof Session) {
            conn = ((SessionImpl) em.unwrap(Session.class)).connection();
        } else{
            /**
             * see here:http://wiki.eclipse.org/EclipseLink/Examples/JPA/EMAPI#Getting_a_JDBC_Connection_from_an_EntityManager
             */
            tx.begin();
            conn = em.unwrap(Connection.class);
            tx.commit();
        }

    }
    emf.getCache().evictAll();
}
 
源代码11 项目: database-rider   文件: EntityManagerProvider.java
private void init(String unitName) {
    if (emf == null) {
        log.debug("creating emf for unit {}", unitName);
        Map<String,String> dbConfig = getDbPropertyConfig();
        log.debug("using dbConfig '{}' to create emf", dbConfig);
        emf = dbConfig == null ? Persistence.createEntityManagerFactory(unitName) : Persistence.createEntityManagerFactory(unitName, dbConfig);
        em =  emf.createEntityManager();
        tx = em.getTransaction();
        if (isHibernateOnClasspath() && em.getDelegate() instanceof Session) {
            conn = ((SessionImpl) em.unwrap(Session.class)).connection();
        } else{
            /**
             * see here:http://wiki.eclipse.org/EclipseLink/Examples/JPA/EMAPI#Getting_a_JDBC_Connection_from_an_EntityManager
             */
            tx.begin();
            conn = em.unwrap(Connection.class);
            tx.commit();
        }

    }
    emf.getCache().evictAll();
}
 
源代码12 项目: hyperjaxb3   文件: JAXBAndJPATest.java
public void setUp() throws Exception {

		objectFactory = new ObjectFactory();

		final Properties persistenceProperties = new Properties();
		InputStream is = null;
		try {
			is = getClass().getClassLoader().getResourceAsStream(
					"persistence.properties");
			persistenceProperties.load(is);
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException ignored) {

				}
			}
		}

		entityManagerFactory = Persistence.createEntityManagerFactory(
				"generated", persistenceProperties);

		context = JAXBContext.newInstance("generated");
	}
 
@BeforeClass
public static void setUpClass() {
	entityManager = Persistence.createEntityManagerFactory(
			"ProjectDBManagerTest-ejbPU").createEntityManager();
	userResourceFacadeImp = new UsersResourceFacadeImp();
	crisisResourceFacadeImp = new CollectionResourceFacadeImp();
	crisisTypeResourceFacadeImp = new CrisisTypeResourceFacadeImp();
	userResourceFacadeImp.setEntityManager(entityManager);
	nominalAttributeResourceFacadeImp = new NominalAttributeResourceFacadeImp();
	crisisResourceFacadeImp.setEntityManager(entityManager);
	crisisTypeResourceFacadeImp.setEntityManager(entityManager);
	nominalAttributeResourceFacadeImp.setEntityManager(entityManager);

	user = new UsersDTO("userDBTest"+new Date(), "normal"+new Date());
	entityManager.getTransaction().begin();
	user = userResourceFacadeImp.addUser(user);
	entityManager.getTransaction().commit();
}
 
源代码14 项目: jasperreports   文件: EjbqlApp.java
/**
 *
 */
public void fill() throws JRException
{
	long start = System.currentTimeMillis();
	// create entity manager factory for connection with database
	EntityManagerFactory emf = Persistence.createEntityManagerFactory("pu1", new HashMap<Object, Object>());
	EntityManager em = emf.createEntityManager();

	try
	{
		Map<String, Object> parameters = getParameters(em);
		
		JasperFillManager.fillReportToFile("build/reports/JRMDbReport.jasper", parameters);

		em.close();
		
		System.err.println("Filling time : " + (System.currentTimeMillis() - start));
	}
	finally
	{
		if (em.isOpen())
			em.close();
		if (emf.isOpen())
			emf.close();
	}
}
 
@Test
public void testPersistTwiceInNewFactory() {
    User02 user02 = new User02();
    user02.setId(1L);

    boolean persisted = persistInATransaction(user02);
    assertTrue(persisted);

    em.close();
    factory.close();
    factory = Persistence.createEntityManagerFactory("DB");
    em = factory.createEntityManager();

    persisted = persistInATransaction(user02);
    assertTrue(persisted);
    /*
        Here we managed to commit, because createEntityManagerFactory does
        create a new database, as we used "create-drop" in the persisten.xml file
     */
}
 
@SuppressWarnings({
        "unchecked", "rawtypes"
})
@Before
public void prepareMocks() {
    mockStatic(Persistence.class);
    when(Persistence.createEntityManagerFactory(eq(UNIT_NAME), eq(PERSISTENCE_PROPERTIES))).thenReturn(factory);

    when(invocation.getContext()).thenReturn(ctx);
    when(invocation.getTestClass()).thenReturn((Class) getClass());
    when(ctx.getDescriptor()).thenReturn(descriptor);
    when(descriptor.getUnitName()).thenReturn(UNIT_NAME);
    when(descriptor.getProperties()).thenReturn(PERSISTENCE_PROPERTIES);
}
 
/**
 *
 * @param persistenceUnit
 * @return
 */
public static EntityManagerFactory createEntityManagerFactory(String persistenceUnit) {
    return Persistence.createEntityManagerFactory(persistenceUnit, new HashMap<Object,Object>() {{
        put( "datanucleus.primaryClassLoader",
             DataNucleusEntityManagerFactory.class.getClassLoader());
        put( "datanucleus.plugin.pluginRegistryClassName",
             OSGiPluginRegistry.class.getName());
    }});
}
 
源代码18 项目: rhpam-7-openshift-image   文件: Library.java
synchronized Library init() {
    if (emf == null) {
        emf = Persistence.createEntityManagerFactory("library");
        new Init(emf).transact();
    }
    return this;
}
 
源代码19 项目: quarkus   文件: JPAConfig.java
EntityManagerFactory get() {
    if (value == null) {
        synchronized (this) {
            if (closed) {
                throw new IllegalStateException("Persistence unit is closed");
            }
            if (value == null) {
                value = Persistence.createEntityManagerFactory(name);
            }
        }
    }
    return value;
}
 
源代码20 项目: apiman   文件: EntityManagerFactoryAccessor.java
@PostConstruct
public void postConstruct() {
    Map<String, String> properties = new HashMap<>();

    // Get properties from apiman.properties
    Map<String, String> cp = jpaProperties.getAllHibernateProperties();
    if (cp != null) {
        properties.putAll(cp);
    }

    // Get two specific properties from the System (for backward compatibility only)
    String s = properties.get("hibernate.hbm2ddl.auto"); //$NON-NLS-1$
    if (s == null) {
        s = "validate"; //$NON-NLS-1$
    }
    String autoValue = System.getProperty("apiman.hibernate.hbm2ddl.auto", s); //$NON-NLS-1$
    s = properties.get("hibernate.dialect"); //$NON-NLS-1$
    if (s == null) {
        s = "org.hibernate.dialect.H2Dialect"; //$NON-NLS-1$
    }
    String dialect = System.getProperty("apiman.hibernate.dialect", s); //$NON-NLS-1$
    properties.put("hibernate.hbm2ddl.auto", autoValue); //$NON-NLS-1$
    properties.put("hibernate.dialect", dialect); //$NON-NLS-1$

    // First try using standard JPA to load the persistence unit.  If that fails, then
    // try using hibernate directly in a couple ways (depends on hibernate version and
    // platform we're running on).
    try {
        emf = Persistence.createEntityManagerFactory("apiman-manager-api-jpa", properties); //$NON-NLS-1$
    } catch (Throwable t1) {
        try {
            emf = new HibernatePersistenceProvider().createEntityManagerFactory("apiman-manager-api-jpa", properties); //$NON-NLS-1$
        } catch (Throwable t3) {
            throw t1;
        }
    }
}
 
源代码21 项目: tutorials   文件: EditorUnitTest.java
@Test
public void givenNeo4j_WhenEntitiesCreated_thenCanBeRetrieved() throws Exception {
    EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("ogm-neo4j");
    Editor editor = generateTestData();
    persistTestData(entityManagerFactory, editor);
    loadAndVerifyTestData(entityManagerFactory, editor);
}
 
源代码22 项目: tutorials   文件: GetReferenceMySQLManualTest.java
@BeforeAll
public static void setup() {
    // close some specific loggers so that we can clearly see Hibernate: SQL queries
    ((Logger) LoggerFactory.getLogger("org.hibernate.SQL")).setLevel(Level.OFF);
    ((Logger) LoggerFactory.getLogger("org.hibernate.type.descriptor.sql")).setLevel(Level.OFF);
    ((Logger) LoggerFactory.getLogger("org.hibernate.stat")).setLevel(Level.OFF);

    entityManagerFactory = Persistence.createEntityManagerFactory("com.baeldung.hibernate.entitymanager.game_player_mysql");
}
 
@BeforeAll
public static void setup() {
    // close some specific loggers so that we can clearly see Hibernate: SQL queries
    ((Logger) LoggerFactory.getLogger("org.hibernate.SQL")).setLevel(Level.OFF);
    ((Logger) LoggerFactory.getLogger("org.hibernate.type.descriptor.sql")).setLevel(Level.OFF);
    ((Logger) LoggerFactory.getLogger("org.hibernate.stat")).setLevel(Level.OFF);

    entityManagerFactory = Persistence.createEntityManagerFactory("com.baeldung.hibernate.entitymanager.game_player_postgresql");
}
 
@BeforeEach
public void init() {
    emFactory = Persistence.createEntityManagerFactory("DB");
    em = emFactory.createEntityManager();

    valFactory = Validation.buildDefaultValidatorFactory();
    validator = valFactory.getValidator();
}
 
源代码25 项目: jerseyoauth2   文件: PersistenceProvider.java
@SuppressWarnings({ "rawtypes", "unchecked" })
public PersistenceProvider()
{
	Map params = new HashMap();
	params.put("hibernate.hbm2ddl.auto","create-drop");
	params.put("hibernate.cache.use_second_level_cache","false");
	params.put("hibernate.dialect","org.hibernate.dialect.DerbyTenSevenDialect");
	
	emf = Persistence.createEntityManagerFactory("authsrv", params );
}
 
源代码26 项目: BotLibre   文件: Migrate.java
public void migrate7() {
	Map<String, String> properties = new HashMap<String, String>();
	properties.put(PersistenceUnitProperties.JDBC_PASSWORD, Site.DATABASEPASSWORD);
	properties.put(PersistenceUnitProperties.LOGGING_LEVEL, "fine");
	EntityManagerFactory factory = Persistence.createEntityManagerFactory(Site.PERSISTENCE_UNIT, properties);
	EntityManager em = factory.createEntityManager();
	em.getTransaction().begin();
	try {
		em.createNativeQuery("Update ChatChannel set alias = name").executeUpdate();
		em.createNativeQuery("Update Forum set alias = name").executeUpdate();
		em.createNativeQuery("Update BotInstance set alias = name").executeUpdate();
		em.createNativeQuery("Update Graphic set alias = name").executeUpdate();
		em.createNativeQuery("Update Domain set alias = name").executeUpdate();
		em.createNativeQuery("Update IssueTracker set alias = name").executeUpdate();
		em.createNativeQuery("Update Analytic set alias = name").executeUpdate();
		em.createNativeQuery("Update Script set alias = name").executeUpdate();
		em.createNativeQuery("Update Avatar set alias = name").executeUpdate();
		em.getTransaction().commit();
	} catch (Exception exception) {
		exception.printStackTrace();
	} finally {
		if (em.getTransaction().isActive()) {
			em.getTransaction().rollback();
		}
		em.close();
		factory.close();
	}
}
 
源代码27 项目: mycore   文件: MCRJPABootstrapper.java
public static void initializeJPA(String persistenceUnitName, Map<?, ?> properties) {
    EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory(
        Optional.ofNullable(persistenceUnitName).orElse(PERSISTENCE_UNIT_NAME),
        properties);
    checkFactory(entityManagerFactory);
    MCREntityManagerProvider.init(entityManagerFactory);
}
 
源代码28 项目: testfun   文件: SingletonEntityManager.java
private synchronized EntityManager getEntityManager() {
    if (entityManager == null) {
        Map<String, DataSource> config = new HashMap<>();
        config.put(AvailableSettings.DATASOURCE, SingletonDataSource.getDataSource());

        EntityManagerFactory emf = Persistence.createEntityManagerFactory(PersistenceXml.getInstnace().getPersistenceUnitName(), config);
        entityManager = emf.createEntityManager();
    }

    return entityManager;
}
 
源代码29 项目: tutorials   文件: TestEntityManagerProducer.java
@ApplicationScoped
@Produces
@Specializes
public EntityManager create() {
    return Persistence
      .createEntityManagerFactory("pu-test")
      .createEntityManager();
}
 
源代码30 项目: jqm   文件: App.java
@Override
public void start()
{
    log.info("Starting payload");
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("marsu-pu");
    EntityManager em = emf.createEntityManager();

    log.info("Running query");
    em.createQuery("SELECT e from Entity e");

    if (this.getParameters().size() == 0)
    {
        // We use non-standard datasource names during tests
        Properties p = new Properties();
        String dbName = System.getenv("DB");
        dbName = (dbName == null ? "hsqldb" : dbName);
        p.put("javax.persistence.nonJtaDataSource", "jdbc/" + dbName);
        JqmClientFactory.setProperties(p);
        // End of datasource name change

        log.info("Queuing again - with parameter and through the full API");
        JobRequest jd = new JobRequest("jqm-test-em", "marsu");
        jd.addParameter("stop", "1");
        JqmClientFactory.getClient().enqueue(jd);
    }
    log.info("End of payload");
}
 
 类所在包
 同包方法