下面列出了怎么用javax.persistence.Persistence的API类实例代码及写法,或者点击链接到github查看源代码。
@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;
}
@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"));
}
@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);
}
@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();
}
}
/**
* 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);
}
@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();
}
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();
}
}
@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);
}
@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"));
}
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();
}
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();
}
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();
}
/**
*
*/
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());
}});
}
synchronized Library init() {
if (emf == null) {
emf = Persistence.createEntityManagerFactory("library");
new Init(emf).transact();
}
return this;
}
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;
}
@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;
}
}
}
@Test
public void givenNeo4j_WhenEntitiesCreated_thenCanBeRetrieved() throws Exception {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("ogm-neo4j");
Editor editor = generateTestData();
persistTestData(entityManagerFactory, editor);
loadAndVerifyTestData(entityManagerFactory, editor);
}
@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();
}
@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 );
}
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();
}
}
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);
}
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;
}
@ApplicationScoped
@Produces
@Specializes
public EntityManager create() {
return Persistence
.createEntityManagerFactory("pu-test")
.createEntityManager();
}
@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");
}