I have to develop a WAR-Application in Netbeans. As a Webserver I use the built-in Jetty to test the WAR, because the release version should also use Jetty.
In Netbeans I have a setup to redeploy the WAR after saving a file.
And there I have the problem that after a redeploy (the first deploy works fine) at connecting to the Firebird database again, the Application is stopping at the first output of:
Hibernate: create table HT_mytable (myid numeric(18,0) not null, hib_sess_id CHAR(36))
This my code for creating the EntityManager
protected EntityManager createEntityManager(String databaseName) {
String user = this.settingsService.getValue("user", "database");
String password = this.settingsService.getValue("password", "database");
Properties properties = new Properties();
properties.put("hibernate.show_sql", true);
properties.put("javax.persistence.jdbc.url", this.createUrlForDatabase(databaseName));
properties.put("javax.persistence.jdbc.user", user);
properties.put("javax.persistence.jdbc.password", password);
properties.put("javax.persistence.jdbc.driver", "org.firebirdsql.jdbc.FBDriver");
try {
EntityManagerFactory emf = Persistence.createEntityManagerFactory(UNITNAME_PREFIX + databaseName, properties);
return emf.createEntityManager();
} catch(PersistenceException ex) {
Logger.getLogger(EntityService.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
Thanks :)
Related
I'm trying to modify existing Java app (WildFly, Jboss, oracle) which currently working fine as using persistence-unit and EntityManager connect to Oracle database(using standalone.xml and persistence.xml). However, I need to create every time new connection to database for the user which calls new GET API Endpoint using credentials from the HttpHeaders. Currently, I'm creating new entitymanager object which session is commit, rollback nad close. Unfortunately time response for every call become higher and higher. There is warning about "PersistenceUnitUser" being already registered and memory usage constantly growing. So that is bad solution.
Is there any proper way to do it, which works witout any harms ?
P.S.
Currently app using standalone.xml and persistence.xml. And that is working fine. I'm calling java api endpoint using entity manager being connected as Admin user/pass but I need to create new connection using user/pass from the httpHeaders and call one sql statement to see proper results as ORACLE uses reserved word such us: 'user'. For instance : select * from table where create_usr = user. When done 'Main EntityManager will use data from it to continue some process.
Please see code example below :
#GET
#Path("/todo-list-enriched")
#Produces(MediaType.APPLICATION_JSON)
public Response getToDoListEnriched(#Context HttpHeaders httpHeaders, #QueryParam("skip") int elementNumber, #QueryParam("take") int pageSize, #QueryParam("orderby") String orderBy)
{
String userName = httpHeaders.getHeaderString(X_USER_NAME);
String userName = httpHeaders.getHeaderString(X_PASSWORD);
EntityManager entityManager = null;
try {
Map<String, String> persistenceMap = new HashMap<String, String>();
persistenceMap.put("hibernate.dialect","org.hibernate.dialect.Oracle8iDialect");
persistenceMap.put("hibernate.connection.username", asUserName);
persistenceMap.put("hibernate.connection.password", asPassword);
EntityManagerFactory emf = Persistence.createEntityManagerFactory("PersistenceUnitUser", persistenceMap);
entityManager = emf.createEntityManager();
if (!entityManager.getTransaction().isActive()) {
entityManager.getTransaction().begin();
}
-- Do some works as select, update, select
-- and after that
if (entityManager.getTransaction().isActive()) {
entityManager.getTransaction().commit();
}
}
catch (Exception ex)
{
if (entityManager != null && entityManager.getTransaction().isActive()) {
entityManager.getTransaction().rollback();
}
}
finally {
if (entityManager != null && entityManager.isOpen()) {
entityManager.close();
}
}
}
}
``
Best Regards
Marcin
You should define a connection pool and a datasource in the standalone.xml (cf. https://docs.wildfly.org/26.1/Admin_Guide.html#DataSource) and then use it in your persistence.xml and inject the EntitytManager in your rest service class (cf. https://docs.wildfly.org/26.1/Developer_Guide.html#entity-manager).
You may look at this example application: https://github.com/wildfly/quickstart/tree/main/todo-backend
i have an application Java + Jersey + Hibernate. Have too an .ini file, i want to get this access url to database when i start the server. I tried one option, but it makes persistence.xml alter every requisition and turns all of them extremely slow. The slow solution is:
public static EntityManager getEntityManager() {
String url = "jdbc:firebirdsql:xxx.xxx.xx.xxx/3040:c:\\database\\database.FDB";
EntityManager em = null;
Map properties = new HashMap();
properties.put("hibernate.connection.url", url);
try {
emf = Persistence.createEntityManagerFactory("aplication", properties);
} catch (Exception e) {
e.printStackTrace();
}
return em = (EntityManager) emf.createEntityManager();
}
Is there another way to alter persistence.xml url to database one time and no more? I need a performer solution, dont want very slow solutions.
NOTE: The motive i need this is because i have a configuration application in phyton who alters the ini file for each new customer. My application in Java reads this ini file.
You have to create the EntityManagerFactory a single time and cache it.
Here you create it at each time you create an EntityManager instance.
You could create the EntityManagerFactory in a listener or hook method that is invoked as your application is started and fully initialized :
private static EntityManagerFactory emf; // share emf
public void init() {
String url = "jdbc:firebirdsql:xxx.xxx.xx.xxx/3040:c:\\database\\database.FDB";
Map properties = new HashMap();
properties.put("hibernate.connection.url", url);
try {
emf = Persistence.createEntityManagerFactory("aplication", properties);
} catch (Exception e) {
e.printStackTrace();
}
}
Then use the cached EntityManagerFactory in getEntityManager() :
public static EntityManager getEntityManager() {
return (EntityManager) emf.createEntityManager();
}
I am starting H2 db in embedded mode. By default h2 db file is getting created in users directory. I have requirement of creating in a custom location. The custom location should be read from environment variable ( Example %MY_HOME%= C:\TEST).
The database file should be created in c:\TEST. What changes should I make in web.xml to do the same?
Thanks in advance
You can add you custom location by setting db.url property of H2.
for example :
If your database name is DBNAME then you can set db.url in web.xml with your custom location in following manner :
jdbc:h2:file:C:\\Test\\DBNAME
If you are using Hibernate in your application then you can build session factory for H2 database in following manner :
private static SessionFactory buildSessionFactory()
{
String methodName = "buildSessionFactory -->";
_logger.debug(methodName + Constants.CALLED);
try
{
// Create the SessionFactory from hibernate.cfg.xml
Configuration configuration = new Configuration();
URL resourceURL = HibernateUtil.class.getClassLoader().getResource("hibernate.cfg.xml");
_logger.debug(resourceURL);
configuration = configuration.configure(resourceURL);
//Here you can set your custom url for H2 database.
String url = "jdbc:h2:file:C:\\Test\\DBNAME;MV_STORE=FALSE;MVCC=TRUE;DB_CLOSE_ON_EXIT=TRUE;FILE_LOCK=NO";
_logger.debug("Database URL " + url);
_logger.debug("Build Session Factory URL: " + url);
configuration = configuration.setProperty("hibernate.connection.url", url);
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
_logger.debug("Session factory built");
_logger.debug(Constants.END);
return configuration.buildSessionFactory(serviceRegistry);
}
catch (Throwable ex)
{
_logger.debug("Failed to create session factory");
_logger.error("Initial SessionFactory creation failed.", ex);
ex.printStackTrace();
throw new ExceptionInInitializerError(ex);
}
}
I got an answer for my query. We can set init parameters in two ways.
1) web.xml, Generally everyone uses.
2) contextInitialized will be method called as call back method while tomcat is getting started. In that method you can set the init parameters by using instance of servletContext clas.
I want my H2 database to be stored into a file, so that once I close the application and open it again, all the data that was previously written to the database is still there, but for some reason, at the moment whenever I start the application, the database is completely empty. Any suggestions?
#Bean
public DataSource dataSource() {
File f = new File(".");
JdbcDataSource ds = new JdbcDataSource();
ds.setURL("jdbc:h2:file:" + f.getAbsolutePath() + "/db/aurinko");
ds.setUser("");
ds.setPassword("");
return ds;
}
private Properties getHibernateProperties() {
Properties prop = new Properties();
prop.put("hibernate.format_sql", "true");
prop.put("hibernate.show_sql", "false");
prop.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
prop.put("hibernate.hbm2ddl.auto", "update");
return prop;
}
#Bean
public SessionFactory sessionFactory() throws IOException {
LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(dataSource());
builder.scanPackages("io.aurinko.server.jpa").addProperties(getHibernateProperties());
SessionFactory result = builder.buildSessionFactory();
return result;
}
I was using spring-boot. Turns out that spring-boot generates its own H2 database. That means that I had two separate databases, one of which I was trying to use and the second one (only the in-memory one) that I was actually using.
May be try setting auto commit to true in the config/ property file. It may work
I'm using a web application and, sometimes, I have MySql connection problems.
Using the testConnectionOnCheckout and preferredTestQuery options in the Hibernate configuration file, I resolved the problem and my application is ok now.
But, for better performance, I'd like to obtain the effects of this option only when a particular event occurs in my application. For example:
try {
...........
}
catch(Exception e) {
// java code to obtain the same effect as
// testConnectionOnCheckout option with "Select 1" query
}
What Java code do I have to use?
The best way to answer such a question is to look it up in the source. So I encourage you to get the source of Hibernate and find the code that tests the connection.
but anyway, here's something simple
public static boolean checkConnection(String jdbcUrl, String user, String password){
boolean result = false;
try {
Configuration config = new AnnotationConfiguration().configure();
config.setProperty("hibernate.connection.url", jdbcUrl);
config.setProperty("hibernate.connection.username", user);
config.setProperty("hibernate.connection.password", password);
sessionFactory = config.buildSessionFactory();
Session session = sessionFactory.openSession();
Assert.assertFalse(sesssion.connection.isReadOnly());
result = true;
} catch(Throwable ex) {
return = false;
}
return result;
}