Java Code Examples for javax.persistence.Persistence#createEntityManagerFactory()

The following examples show how to use javax.persistence.Persistence#createEntityManagerFactory() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JpaMigrator.java    From james-project with Apache License 2.0 6 votes vote down vote up
/**<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);
    }
    
}
 
Example 2
Source File: Database.java    From desktop with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void load(ConfigNode node) throws ConfigException {
    File dbFileName = new File(Config.getInstance().getConfDir() + File.separator + Constants.CONFIG_DATABASE_DIRNAME + File.separator + Constants.CONFIG_DATABASE_FILENAME);

    // Override database location with [confdir]/db/stacksync
    properties.setProperty(PersistenceUnitProperties.JDBC_URL,
            String.format(Constants.CONFIG_DATABASE_URL_FORMAT, dbFileName.getAbsolutePath()));
    
    properties.setProperty(PersistenceUnitProperties.JDBC_DRIVER,
            String.format(Constants.CONFIG_DATABASE_DRIVER, dbFileName.getAbsolutePath()));

    // Adjust generation strategy
    // - if DB folder exists, we assume the tables have been created
    // - if not, we need to create them
    if (!dbFileName.exists()) {
        properties.setProperty(PersistenceUnitProperties.DDL_GENERATION, PersistenceUnitProperties.CREATE_ONLY);
    } else {
        properties.setProperty(PersistenceUnitProperties.DDL_GENERATION, PersistenceUnitProperties.NONE);
    }

    // Override other values (if defined in config!)
    if (node != null) {
        for (ConfigNode property : node.findChildrenByXpath("property")) {
            properties.setProperty(property.getAttribute("name"), property.getAttribute("value"));
        }
    }

    //check directory
    File serviceProperties = new File(dbFileName.getAbsolutePath() + File.separator + "service.properties");
    if (!serviceProperties.exists()) {
        File databaseFolder = new File(Config.getInstance().getConfDir() + File.separator + Constants.CONFIG_DATABASE_DIRNAME);

        FileUtil.deleteRecursively(databaseFolder);
        databaseFolder.mkdirs();
    }
    
    // Load!
    entityManagerFactory = Persistence.createEntityManagerFactory(Constants.CONFIG_DATABASE_PERSISTENCE_UNIT, properties);
}
 
Example 3
Source File: UserTest.java    From testing_security_development_enterprise_systems with GNU Lesser General Public License v3.0 5 votes vote down vote up
@BeforeEach
public void init() {
    emFactory = Persistence.createEntityManagerFactory("DB");
    em = emFactory.createEntityManager();

    valFactory = Validation.buildDefaultValidatorFactory();
    validator = valFactory.getValidator();
}
 
Example 4
Source File: ContractApplicationExampleUI.java    From vaadinator with Apache License 2.0 5 votes vote down vote up
protected PresenterFactory obtainPresenterFactory(String contextPath) {
	if (presenterFactory == null) {
		ContractApplicationService contractApplicationService;
		EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("ContractApplicationExample");
		ContractApplicationDao contractApplicationDao = new ContractApplicationDaoPlain(entityManagerFactory);
		contractApplicationService = new ContractApplicationServicePlain(entityManagerFactory, contractApplicationDao);
		presenterFactory = new PresenterFactoryEx(new HashMap<String, Object>(), new VaadinViewFactoryEx(), contractApplicationService);
	}
	return presenterFactory;
}
 
Example 5
Source File: TestJpa.java    From javamelody with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateEntityManager() {
	final EntityManagerFactory emf = Persistence.createEntityManagerFactory("test-jse");
	emf.createEntityManager();
	JpaWrapper.getJpaCounter().setDisplayed(false);
	emf.createEntityManager();
	JpaWrapper.getJpaCounter().setDisplayed(true);
}
 
Example 6
Source File: Migrate.java    From BotLibre with Eclipse Public License 1.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public void migrate2() {
	EntityManagerFactory sourceFactory = Persistence.createEntityManagerFactory("migration");
	Map<String, String> properties = new HashMap<String, String>();
	properties.put(PersistenceUnitProperties.JDBC_PASSWORD, Site.DATABASEPASSWORD);
	properties.put(PersistenceUnitProperties.DDL_GENERATION, PersistenceUnitProperties.DROP_AND_CREATE);
	properties.put(PersistenceUnitProperties.LOGGING_LEVEL, "fine");
	EntityManagerFactory targetFactory = Persistence.createEntityManagerFactory("botlibre", properties);
	EntityManager source = sourceFactory.createEntityManager();
	EntityManager target = targetFactory.createEntityManager();
	target.getTransaction().begin();
	try {
		Domain domain = new Domain(Site.DOMAIN);
		target.persist(domain);
		
		List<Tag> tags = source.createQuery("Select t from Tag t").getResultList();
		for (Tag tag : tags) {
			tag.setDomain(domain);
			target.persist(tag);
		}
		
		List<User> users = source.createQuery("Select t from User t").getResultList();
		for (User user : users) {
			if (user.getCreationDate() == null) {
				user.setCreationDate(new Date());
			}
			target.persist(user);
		}
		
		List<AvatarImage> avatars = source.createQuery("Select t from AvatarImage t").getResultList();
		for (AvatarImage avatar : avatars) {
			avatar.setDomain(domain);
			target.persist(avatar);
		}
		
		List<BotInstance> instances = source.createQuery("Select p from BotInstance p").getResultList();
		for (BotInstance instance : instances) {
			if (instance.getCreationDate() == null) {
				instance.setCreationDate(new Date());
			}
			instance.setDomain(domain);
			target.persist(instance);
		}
		
		target.getTransaction().commit();
		target.getTransaction().begin();
		Query query = target.createNativeQuery("Update Tag t set count = (Select count(p) from BotInstance p join PANODRAINSTANCE_TAGS pt on (pt.BotInstance_id = p.id) join Tag t2 on (pt.tags_id = t2.id) where p.domain_id = ? and t2.id = t.id) where t.domain_id = ?");
		query.setParameter(1, domain.getId());
		query.setParameter(2, domain.getId());
		query.executeUpdate();
		query = target.createQuery("Delete from Tag t where t.count = 0 and t.domain = :domain");
		query.setParameter("domain", domain);
		query.executeUpdate();
		target.getTransaction().commit();
		
	} catch (Exception exception) {
		exception.printStackTrace();
	} finally {
		if (target.getTransaction().isActive()) {
			target.getTransaction().rollback();
		}
		source.close();
		target.close();
		sourceFactory.close();
		targetFactory.close();
	}
}
 
Example 7
Source File: IdHandlingTest.java    From testing_security_development_enterprise_systems with GNU Lesser General Public License v3.0 4 votes vote down vote up
@BeforeEach
public void init() {
    factory = Persistence.createEntityManagerFactory("DB");
    em = factory.createEntityManager();
}
 
Example 8
Source File: TestCoreJavaSuite.java    From jadira with Apache License 2.0 4 votes vote down vote up
@BeforeClass
public static void setup() {
    factory = Persistence.createEntityManagerFactory("test1");
}
 
Example 9
Source File: TestPersistentDayOfWeekAsInteger.java    From jadira with Apache License 2.0 4 votes vote down vote up
@BeforeClass
public static void setup() {
    factory = Persistence.createEntityManagerFactory("test1");
}
 
Example 10
Source File: HibernatePluginTest.java    From HotswapAgent with GNU General Public License v2.0 4 votes vote down vote up
@BeforeClass
public static void setup() throws Exception {
    entityManagerFactory = Persistence.createEntityManagerFactory("TestPU");
}
 
Example 11
Source File: TestInheritance.java    From HibernateTips with MIT License 4 votes vote down vote up
@Before
public void init() {
	emf = Persistence.createEntityManagerFactory("my-persistence-unit");
}
 
Example 12
Source File: TestUnidirectionalOneToOne.java    From HibernateTips with MIT License 4 votes vote down vote up
@Before
public void init() {
	emf = Persistence.createEntityManagerFactory("my-persistence-unit");
}
 
Example 13
Source File: TestInheritance.java    From HibernateTips with MIT License 4 votes vote down vote up
@Before
public void init() {
	emf = Persistence.createEntityManagerFactory("my-persistence-unit");
}
 
Example 14
Source File: TestPersistentZoneOffsetAsString.java    From jadira with Apache License 2.0 4 votes vote down vote up
@BeforeClass
public static void setup() {
    factory = Persistence.createEntityManagerFactory("test1");
}
 
Example 15
Source File: TestUUIDPrimaryKey.java    From HibernateTips with MIT License 4 votes vote down vote up
@Before
public void init() {
	emf = Persistence.createEntityManagerFactory("my-persistence-unit");
}
 
Example 16
Source File: TestGeneratedColumn.java    From HibernateTips with MIT License 4 votes vote down vote up
@Before
public void init() {
	emf = Persistence.createEntityManagerFactory("my-persistence-unit");
}
 
Example 17
Source File: TestQueryTimeout.java    From HibernateTips with MIT License 4 votes vote down vote up
@Before
public void init() {
	emf = Persistence.createEntityManagerFactory("my-persistence-unit");
}
 
Example 18
Source File: HibernateJpaServlet.java    From appengine-cloudsql-native-mysql-hibernate-jpa-demo-java with Apache License 2.0 4 votes vote down vote up
public void doGet(HttpServletRequest req, HttpServletResponse res)
    throws IOException {
  res.setContentType("text/plain");

  Map<String, String> properties = new HashMap();
  if (SystemProperty.environment.value() ==
        SystemProperty.Environment.Value.Production) {
    properties.put("javax.persistence.jdbc.driver",
        "com.mysql.jdbc.GoogleDriver");
    properties.put("javax.persistence.jdbc.url",
        System.getProperty("cloudsql.url"));
  } else {
    properties.put("javax.persistence.jdbc.driver",
        "com.mysql.jdbc.Driver");
    properties.put("javax.persistence.jdbc.url",
        System.getProperty("cloudsql.url.dev"));
  }

  EntityManagerFactory emf = Persistence.createEntityManagerFactory(
      "Demo", properties);

  // Insert a few rows.
  EntityManager em = emf.createEntityManager();
  em.getTransaction().begin();
  em.persist(new Greeting("user", new Date(), "Hello!"));
  em.persist(new Greeting("user", new Date(), "Hi!"));
  em.getTransaction().commit();
  em.close();

  // List all the rows.
  em = emf.createEntityManager();
  em.getTransaction().begin();
  List<Greeting> result = em
      .createQuery("FROM Greeting", Greeting.class)
      .getResultList();
  for (Greeting g : result) {
    res.getWriter().println(
        g.getId() + " " +
        g.getAuthor() + "(" + g.getDate() + "): " +
        g.getContent());
  }
  em.getTransaction().commit();
  em.close();

}
 
Example 19
Source File: TestPersistentLocalTimeAsString.java    From jadira with Apache License 2.0 4 votes vote down vote up
@BeforeClass
public static void setup() {
    factory = Persistence.createEntityManagerFactory("test1");
}
 
Example 20
Source File: Test2ndLevelCache.java    From HibernateTips with MIT License 4 votes vote down vote up
@Before
public void init() {
	emf = Persistence.createEntityManagerFactory("my-persistence-unit");
}