下面列出了javax.persistence.EntityManagerFactory#createEntityManager ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void jpa_with_parent() {
final MockSpan parent = mockTracer.buildSpan("parent").start();
try (Scope ignored = mockTracer.activateSpan(parent)) {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("jpa");
EntityManager entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
entityManager.persist(new Employee());
entityManager.persist(new Employee());
entityManager.getTransaction().commit();
entityManager.close();
entityManagerFactory.close();
}
parent.finish();
List<MockSpan> spans = mockTracer.finishedSpans();
assertEquals(12, spans.size());
checkSameTrace(spans);
assertNull(mockTracer.activeSpan());
}
/**
*
*/
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();
}
}
private static Statistics verifyFindCountryByNaturalId(EntityManagerFactory emf, String callingCode, String expectedName) {
Statistics stats = getStatistics(emf);
EntityManager em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
final Session session = em.unwrap(Session.class);
final NaturalIdLoadAccess<Country> loader = session.byNaturalId(Country.class);
loader.using("callingCode", callingCode);
Country country = loader.load();
if (!country.getName().equals(expectedName))
throw new RuntimeException("Incorrect citizen: " + country.getName() + ", expected: " + expectedName);
transaction.commit();
em.close();
return stats;
}
/**<p>Executes the database migration for the provided JIRAs numbers.
* For example, for the https://issues.apache.org/jira/browse/IMAP-165 JIRA, simply invoke
* with IMAP165 as parameter.
* You can also invoke with many JIRA at once. They will be all serially executed.</p>
*
* TODO Extract the SQL in JAVA classes to XML file.
*
* @param jiras the JIRAs numbers
* @throws JpaMigrateException
*/
public static void main(String[] jiras) throws JpaMigrateException {
try {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("JamesMigrator");
EntityManager em = factory.createEntityManager();
for (String jira: jiras) {
JpaMigrateCommand jiraJpaMigratable = (JpaMigrateCommand) Class.forName(JPA_MIGRATION_COMMAND_PACKAGE + "." + jira.toUpperCase(Locale.US) + JpaMigrateCommand.class.getSimpleName()).newInstance();
LOGGER.info("Now executing {} migration", jira);
em.getTransaction().begin();
jiraJpaMigratable.migrate(em);
em.getTransaction().commit();
LOGGER.info("{} migration is successfully achieved", jira);
}
} catch (Throwable t) {
throw new JpaMigrateException(t);
}
}
@Test
public void testQuiz(){
Quiz quiz = new Quiz();
quiz.setQuestion("Will this test pass?");
quiz.setFirstAnswer("Yes");
quiz.setSecondAnswer("No");
quiz.setThirdAnswer("Maybe");
quiz.setFourthAnswer("No idea");
quiz.setIndexOfCorrectAnswer(0);
EntityManagerFactory factory = Persistence.createEntityManagerFactory("DB");
EntityManager em = factory.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(quiz);
tx.commit();
}
void init(final PersistenceUnitInfo info, final BeanManager bm) {
final PersistenceProvider provider;
try {
provider = PersistenceProvider.class.cast(
Thread.currentThread().getContextClassLoader().loadClass(info.getPersistenceProviderClassName()).newInstance());
} catch (final InstantiationException | IllegalAccessException | ClassNotFoundException e) {
throw new IllegalArgumentException("Bad provider: " + info.getPersistenceProviderClassName());
}
final EntityManagerFactory factory = provider.createContainerEntityManagerFactory(info, new HashMap() {{
put("javax.persistence.bean.manager", bm);
if (ValidationMode.NONE != info.getValidationMode()) {
ofNullable(findValidatorFactory(bm)).ifPresent(factory -> put("javax.persistence.validation.factory", factory));
}
}});
instanceFactory = synchronization == SynchronizationType.SYNCHRONIZED ? factory::createEntityManager : () -> factory.createEntityManager(synchronization);
}
@Test
public void testQuiz(){
Quiz quiz = new Quiz();
quiz.setQuestion("Will this test pass?");
quiz.setFirstAnswer("Yes");
quiz.setSecondAnswer("No");
quiz.setThirdAnswer("Maybe");
quiz.setFourthAnswer("No idea");
quiz.setIndexOfCorrectAnswer(0);
EntityManagerFactory factory = Persistence.createEntityManagerFactory("DB");
EntityManager em = factory.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(quiz);
tx.commit();
}
private static void deleteAll(final EntityManagerFactory emf) {
EntityManager em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
em.createNativeQuery("Delete from Person").executeUpdate();
em.createNativeQuery("Delete from Item").executeUpdate();
em.createNativeQuery("Delete from Citizen").executeUpdate();
em.createNativeQuery("Delete from Country").executeUpdate();
em.createNativeQuery("Delete from Pokemon").executeUpdate();
em.createNativeQuery("Delete from Trainer").executeUpdate();
transaction.commit();
em.close();
}
@Test
public void testSequences_AnnotationAtFieldLevel_MappedSuperClass() throws Exception {
EntityManagerFactory factory = (EntityManagerFactory) context.getBean("entityManagerFactory");
assertNotNull(factory);
TestEntity5 testEntity1 = new TestEntity5();
testEntity1.setName("MyAwesomeTestEntity1");
// number in this case is generated from a sequence
assertNull(testEntity1.getNumber());
EntityManager entityManager = factory.createEntityManager();
try {
entityManager.persist(testEntity1);
assertNotNull(testEntity1.getNumber());
} finally {
entityManager.close();
}
TestEntity5 testEntity2 = new TestEntity5();
testEntity2.setName("MyAwesomeTestEntity2");
assertNull(testEntity2.getNumber());
entityManager = factory.createEntityManager();
try {
// try merge here and make sure it works with that as well
testEntity2 = entityManager.merge(testEntity2);
assertNotNull(testEntity2.getNumber());
assertEquals(Integer.valueOf(Integer.valueOf(testEntity1.getNumber()).intValue() + 1), Integer.valueOf(
testEntity2.getNumber()));
} finally {
entityManager.close();
}
}
@Test
public void testQueryCustomizerMatch() throws Exception {
EntityManagerFactory factory = (EntityManagerFactory) context.getBean("entityManagerFactory");
assertNotNull(factory);
TestEntity6 testEntity1 = new TestEntity6();
testEntity1.setName("MyAwesomeTestEntity1");
TestRelatedExtension extension = new TestRelatedExtension();
extension.setAccountTypeCode("TS");
EntityManager entityManager = factory.createEntityManager();
try {
testEntity1 = new TestEntity6();
testEntity1.setName("MyCustomFilter");
entityManager.persist(testEntity1);
extension.setNumber(testEntity1.getNumber());
entityManager.persist(extension);
entityManager.flush();
} finally {
entityManager.close();
}
//Now confirm that the entity fetch found travel extension
try {
entityManager = factory.createEntityManager();
testEntity1 = entityManager.find(TestEntity6.class, testEntity1.getNumber());
assertTrue("Match found for base entity", testEntity1 != null && StringUtils.equals("MyCustomFilter",
testEntity1.getName()));
assertTrue("Found matching travel extension that matches", testEntity1.getAccountExtension() != null);
} finally {
entityManager.close();
}
}
/**
* Return the Entity Manager
*
* @return The Entity Manager
*/
public EntityManager getEM( )
{
EntityManagerFactory emf = getEntityManagerFactory( );
if ( TransactionSynchronizationManager.isSynchronizationActive( ) )
{
// first, get Spring entitymanager (if available)
try
{
EntityManager em = EntityManagerFactoryUtils.getTransactionalEntityManager( emf );
if ( em == null )
{
LOG.error( "getEM( ) : no EntityManager found. Will use native entity manager factory [Transaction will not be supported]" );
}
else
{
LOG.debug( "EntityManager found for the current transaction : " + em.toString( ) + " - using Factory : " + emf.toString( ) );
return em;
}
}
catch( DataAccessResourceFailureException ex )
{
LOG.error( ex );
}
}
LOG.error( "getEM( ) : no EntityManager found. Will use native entity manager factory [Transaction will not be supported]" );
if ( _defaultEM == null )
{
_defaultEM = emf.createEntityManager( );
}
return _defaultEM;
}
private static Statistics verifyFindByIdPersons(final EntityManagerFactory emf) {
Statistics stats = getStatistics(emf);
EntityManager em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
findByIdPersons(em);
transaction.commit();
em.close();
return stats;
}
@Test
public void testCreateEntityManager() {
final EntityManagerFactory emf = Persistence.createEntityManagerFactory("test-jse");
emf.createEntityManager();
JpaWrapper.getJpaCounter().setDisplayed(false);
emf.createEntityManager();
JpaWrapper.getJpaCounter().setDisplayed(true);
}
@Test
public void testQueryCustomizerValueClass() throws Exception {
EntityManagerFactory factory = (EntityManagerFactory) context.getBean("entityManagerFactory");
assertNotNull(factory);
TestEntity8 testEntity1 = new TestEntity8();
testEntity1.setName("MyAwesomeTestEntity1");
TestRelatedExtension extension = new TestRelatedExtension();
extension.setAccountTypeCode("NM");
EntityManager entityManager = factory.createEntityManager();
try {
testEntity1 = new TestEntity8();
testEntity1.setName("MyCustomFilter");
entityManager.persist(testEntity1);
extension.setNumber(testEntity1.getNumber());
entityManager.persist(extension);
entityManager.flush();
} finally {
entityManager.close();
}
//Now confirm that the entity fetch found travel extension
try {
entityManager = factory.createEntityManager();
testEntity1 = entityManager.find(TestEntity8.class, testEntity1.getNumber());
assertTrue("Matched found for base entity", testEntity1 != null && StringUtils.equals("MyCustomFilter",
testEntity1.getName()));
assertTrue("Matching travel extension", testEntity1.getAccountExtension() == null);
} finally {
entityManager.close();
}
}
@Test
public void testApplicationManagedEntityManagerWithTransaction() throws Exception {
Object testEntity = new Object();
EntityTransaction mockTx = mock(EntityTransaction.class);
// This one's for the tx (shared)
EntityManager sharedEm = mock(EntityManager.class);
given(sharedEm.getTransaction()).willReturn(new NoOpEntityTransaction());
// This is the application-specific one
EntityManager mockEm = mock(EntityManager.class);
given(mockEm.getTransaction()).willReturn(mockTx);
given(mockEmf.createEntityManager()).willReturn(sharedEm, mockEm);
LocalContainerEntityManagerFactoryBean cefb = parseValidPersistenceUnit();
JpaTransactionManager jpatm = new JpaTransactionManager();
jpatm.setEntityManagerFactory(cefb.getObject());
TransactionStatus txStatus = jpatm.getTransaction(new DefaultTransactionAttribute());
EntityManagerFactory emf = cefb.getObject();
assertSame("EntityManagerFactory reference must be cached after init", emf, cefb.getObject());
assertNotSame("EMF must be proxied", mockEmf, emf);
EntityManager em = emf.createEntityManager();
em.joinTransaction();
assertFalse(em.contains(testEntity));
jpatm.commit(txStatus);
cefb.destroy();
verify(mockTx).begin();
verify(mockTx).commit();
verify(mockEm).contains(testEntity);
verify(mockEmf).close();
}
private static void storeTestPersons(final EntityManagerFactory emf) {
EntityManager em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
persistNewPerson(em, "Gizmo");
persistNewPerson(em, "Quarkus");
persistNewPerson(em, "Hibernate ORM");
transaction.commit();
em.close();
}
private void persistTestData(EntityManagerFactory entityManagerFactory, Editor editor) throws Exception {
TransactionManager transactionManager = com.arjuna.ats.jta.TransactionManager.transactionManager();
EntityManager entityManager;
transactionManager.begin();
entityManager = entityManagerFactory.createEntityManager();
entityManager.persist(editor);
entityManager.close();
transactionManager.commit();
}
@Test
public void testIdPersistence(){
EntityManagerFactory factory = Persistence.createEntityManagerFactory("DB");//same name as in persistence.xml
EntityManager em = factory.createEntityManager();//it works as a cache/buffer until we commit a transaction
User01 user01 = new User01();
user01.setName("AName");
user01.setSurname("ASurname");
// by default, no id, until data committed to the database
assertNull(user01.getId());
//committing data to database needs to be inside a transaction
EntityTransaction tx = em.getTransaction();
tx.begin();
try{
/*
The following is actually executing this SQL statement:
insert into User01 (name, surname, id) values (?, ?, ?)
*/
em.persist(user01);
//there can be several operations on the "cache" EntityManager before we actually commit the transaction
tx.commit();
} catch (Exception e){
//abort the transaction if there was any exception
tx.rollback();
fail();//fail the test
} finally {
//in any case, make sure to close the opened resources
em.close();
factory.close();
}
//id should have now be set
assertNotNull(user01.getId());
System.out.println("GENERATED ID: "+user01.getId());
}
/**
* Function Import implementation for getting customer reviews created
*
* @param productId
* productId of the reviewed product
* @param firstName
* firstname of the reviewer
* @param lastName
* lastname of the reviewer
* @param rating
* rating for the product
* @param creationDate
* date of creation of the review
* @param comment
* comments for the review
* @return customer entity.
* @throws ODataException
* @throws ParseException
*/
@SuppressWarnings("unchecked")
@EdmFunctionImport(name = "CreateCustomerReview", entitySet = "CustomerReviews", returnType = @ReturnType(type = Type.ENTITY, isCollection = false))
public CustomerReview createCustomerReview(@EdmFunctionImportParameter(name = "ProductId") String productId,
@EdmFunctionImportParameter(name = "FirstName") String firstName,
@EdmFunctionImportParameter(name = "LastName") String lastName,
@EdmFunctionImportParameter(name = "Rating") String rating,
@EdmFunctionImportParameter(name = "CreationDate") String creationDate,
@EdmFunctionImportParameter(name = "Comment") String comment) throws ODataException, ParseException {
EntityManagerFactory emf = Utility.getEntityManagerFactory();
EntityManager em = emf.createEntityManager();
Product prod = null;
CustomerReview customerReview = null;
try {
em.getTransaction().begin();
prod = em.find(Product.class, productId);
try {
customerReview = new CustomerReview();
customerReview.setComment(comment);
Calendar cal = Calendar.getInstance();
cal.setTime(new Date(Long.parseLong(creationDate)));
customerReview.setCreationDate(cal);
customerReview.setFirstName(firstName);
customerReview.setLastName(lastName);
customerReview.setRating(Integer.parseInt(rating));
customerReview.setProductId(productId);
customerReview.setProduct(prod);
em.persist(customerReview);
if (prod != null) {
prod.addReview(customerReview);
}
em.getTransaction().commit();
return customerReview;
} catch (NoResultException e) {
throw new ODataApplicationException("Error creating customer review:", Locale.ENGLISH,
HttpStatusCodes.BAD_REQUEST, e);
}
} finally {
em.close();
}
}
@Bean
public EntityManager entityManager(EntityManagerFactory entityManagerFactory) {
return entityManagerFactory.createEntityManager();
}