Need information about JPA based transaction for dynamic SQL table - sql

Firstly, I would like to state our environment details.
We are trying to use EJB-hibernate with sql Azure to create apps on Azure cloud using Eclipse.
We needed to create and transact on databases dynamically. We are able to create databases dynamically. However, on trying to transact on these we are getting an error:
"java.sql.SQLException: No suitable driver found for connection url"
When we tried statically transacting using jpa was not a problem. However, dynamic transactions cannot be done. The entitymanager object is created but not able to connect database.
Could someone help us and explain how we can handle transactions using JPA for dynamically created databases.
Thanks,
Saugata
[edit] We are using the following persistence.xml:
>org.hibernate.ejb.HibernatePersistence
java:jboss/EDS</jta-data-source> -->
net.oauth.database.Co
net.oauth.database.Cr
value="org.hibernate.transaction.JTATransactionFactory" />
value="org.hibernate.transaction.JBossTransactionManagerLookup" />
Our code to connect to the db is as follows:
Map configOverrides = new HashMap();
configOverrides.put("hibernate.connection.password", "");
configOverrides.put("hibernate.connection.username", "");
configOverrides.put("hibernate.connection.driver_class","com.microsoft.sqlserver.jdbc.SQLServerDriver");
configOverrides.put("hibernate.connection.url", "jdbc:sqlsever://;" + "databaseName=;user=;password=");
EntityManagerFactory factory = Persistence.createEntityManagerFactory(ENTERPRISE_UNIT_NAME, configOverrides);
Please note that we are trying to create and connect to db dynamically and hence to do not the db created statically.
For this we are getting the error:
"java.sql.SQLException: No suitable driver found for connection url"

Create a persistence.xml with a persistence unit and put everything there which is static (eg database dialect, logging parameters, etc.)
Then use the following method to create the entity manager:
javax.persistence.Persistence.createEntityManagerFactory(String persistenceUnitName, Map properties);
Supply the variable parameters in the map, like this:
properties.put("hibernate.connection.url", "jdbc:postgresql://127.0.0.1/test");
properties.put("hibernate.connection.username", "joe");
properties.put("hibernate.connection.password", "pass");

Related

ClientCacheConfiguration is not saved to table

Was using CacheConfiguration in Ignite until I stuck with issue on how to authenticate.
Because of that I was starting to change the CacheConfiguration to clientCacheConfiguration. However after converting it to CacheConfiguration I started to notice that it
does not able to save into table because it lack of method setIndexedTypes eg.
Before
CacheConfiguration<String, IgniteParRate> cacheCfg = new CacheConfiguration<>();
cacheCfg.setName(APIConstants.CACHE_PARRATES);
cacheCfg.setIndexedTypes(String.class, IgniteParRate.class);
New
ClientCacheConfiguration cacheCfg = new ClientCacheConfiguration();
cacheCfg.setName(APIConstants.CACHE_PARRATES);
//cacheCfg.setIndexedTypes(String.class, IgniteParRate.class); --> this is not provided
I still need the table to be populated so it easier for us to verify ( using Client IDE like DBeaver)
Any way to solve this issue?
If you need to create tables/cache dynamically using the thin-client, you'll need to use the setQueryEntities() method to define the columns available to SQL "manually". (Passing in the classes with annotations is basically a shortcut for defining the query entities.) I'm not sure why setIndexedTypes() isn't available in the thin-client; maybe a question for the developer mailing list.
Alternatively, you can define your caches/tables in advance using a thick client. They'll still be available when using the thin-client.
To add to existing answer, you can also try to use cache templates for that.
https://apacheignite.readme.io/docs/cache-template
Pre-configure templates, use them when creating caches from thin client.

How to create script using Liquibase without providing the db details like url, user-name, password and driver?

I created the ddl scripts using liquibase by providing the input data base change log.
The code looks like this
private void toSQL(DatabaseChangeLog d)
throws DatabaseException, LiquibaseException, UnsupportedEncodingException, IOException {
FileSystemResourceAccessor fsOpener = new FileSystemResourceAccessor();
CommandLineResourceAccessor clOpener = new CommandLineResourceAccessor(this.getClass().getClassLoader());
CompositeResourceAccessor fileOpener = new CompositeResourceAccessor(new ResourceAccessor[] { fsOpener, clOpener });
Database database = CommandLineUtils.createDatabaseObject(fileOpener, this.url, this.username, this.password, this.driver,
this.defaultCatalogName, this.defaultSchemaName, Boolean.parseBoolean(this.outputDefaultCatalog),
Boolean.parseBoolean(this.outputDefaultSchema), this.databaseClass,
this.driverPropertiesFile, this.propertyProviderClass, this.liquibaseCatalogName,
this.liquibaseSchemaName, this.databaseChangeLogTableName, this.databaseChangeLogLockTableName);
Liquibase liquibase=new Liquibase(d, null, database);
liquibase.update(new Contexts(this.contexts), new LabelExpression(this.labels), getOutputWriter());
}
and my liquibase.properties goes like this
url=jdbc\:sqlserver\://server\:1433;databaseName\=test
username=test
password=test#123
driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
referenceUrl=hibernate:spring:br.com.company.vacation.domain?dialect=org.hibernate.dialect.SQLServer2008Dialect
As you can see, Liquibase is expecting a lot of db parameters such as url,username,password,driver, which I will not be able to provide.
How can I achieve this without providing any of the parameters. Is it possible?
No, it is not possible. If you want liquibase to interact with a database, you have to tell it how to connect to that database.
I investigated a little about the liquibase operation in offline mode. It goes like this.
Running in offline mode only supports updateSql, rollbackSQL, tag, and tagExists. It does not support direct update, diff, or preconditions as there is nothing to actually update or state to check.
An offline database is “connected” to using a url syntax of offline:DATABASE_TYPE?param1=value1&aparam2=value2.
The following code will suffice
this.url=offline:postgres?param1=value1&aparam2=value2;
this.driver=null;
this.username=null;
this.password=null;
Hence not providing the db details. Offline url can be made up from the store type.

adding new document to CouchDb using ArmChair throws exception Object reference not set to an instance of an object

Iam using couch-db version 2.2.0
and I want to make crud operations on couchdb database using .Net
so I installed Armchair.Core Nuget Package version 0.11.2
and in order to add d a new document I, followed the code that is mentioned in
not finished wiki yet
https://bitbucket.org/dboneslabs/arm-chair/wiki/main-api/session-api.md
Database mydatabase = new Database("TestDb",newConnection("http://localhost:5984"));
using (var session = mydatabase.CreateSession())
{
var author = new Person("Jone");
session.Add(author);// NOTE: If no Id has been assigned before the instance is added to the Session, then ArmChair will assign it. After the object is committed to the database, the revision will then be set onto the instance
session.Commit();
}
but I still getting the error
Object reference not set to an instance of an object.
also mydatabase variable mentioned in previous code has values null for Connection and DataBase Parameters even though i passed them in the constructor as it doesn't connect to couchdb database at all and never tries to create database TestDb
any help please ,are there any wrong calls in my code
ArmChair connects to an existing database and does not create one.
if you want to create a database, have a look a look at the sample application, in the Autofac registration there is a method which ensures that there is a database created.
https://bitbucket.org/dboneslabs/arm-chair/src/bd4e70d6c51d8b45cfb89eb65ecf81a4ecefb691/samples/todo/Todo.Service/Infrastructure/Modules/DataAccessModule.cs#lines-62
its not the pretty-est of code but works.

how to get the prepared statement query after binding

I am using the prepared statement like this
PreparedStatement pstmt = getConnection().prepareStatement(INSERT_QUERY);
pstmt.setInt(1,userDetails.getUsersId());
log.debug("SQL for inserting child transactions " + pstmt.toString());
I want to log the exact SQL statement after binding into the log file but this thing is not working. It is logging it something like SQLServerPreparedStatement:7. I searched on internet but did not get the satisfactory answer. Any help will be appreciated.
You can try to enable the JDBC internal logging by setting a PrintWriter on the DriverManager. Log4j2 provides an IO Streams module so you can include the output in your normal log file. Sample code:
PrintWriter logger = IoBuilder.forLogger(DriverManager.class)
.setLevel(Level.DEBUG)
.buildPrintWriter();
DriverManager.setLogWriter(logger);
In addition, individual JDBC drivers often provide proprietary logging mechanisms, usually enabled with a system property. You will need to consult the documentation for your specific driver for the details.
You can write a utility function which will replace the '?' with the bind variables.

Fluent NHibernate - Empty Schema SQL Files

I am still quite confused about NHibernate schema export and creation. What I want to achieve is to export schema drop-create sql file AND/OR recreate database schema depending on the application configuration.
Obviously I started with
private void BuildSchema(NHConf.Configuration cfg){
var schema = new SchemaExport(cfg);
schema.SetOutputFile(filename);
schema.Create(true, true);
schema.Drop(true, true);
}
But recently I have figured out, that what actually causes my schema to recreate is NHConf.Environment.Hbm2ddlAuto set to 'create' and SchemaExport has nothing to it.
Also the files with exported SQL schema exists but they are all empty (0KB), which is my main issue, as I manage schema recreation by Hbm2ddlAuto property.
Any ideas?
EDIT:
The BuildSchema method is called just before cfg.BuildSessionFactory()
I use FluentNHibernate with NH 3.1 and Oracle 11g
in your method you execute drop-create and then drop and also enabled writing to database.
this is enough to create the files, make sure you set filename correctly
new SchemaExport(config)
.SetDelimiter(";")
.SetOutputFile(filename)
.Create(false, false);
to create it in database, this works for me
new SchemaExport(config).Create(false, true);
If you are using Fluent configuration, check your mapping file for:
SchemaAction.None();
In my case I commented this line and schema export to file now works!
This post moved me in the right direction: http://lostechies.com/rodpaddock/2010/06/29/using-fluent-nhibernate-with-legacy-databases/
SchemaAction.None();
The next interesting feature is SchemaAction.None(). When developing our applications I have an integration test that is used to build all our default schema. I DONT want these table to be generated in our schema, they are external. SchemaAction.None() tells NHibernate not to create this entity in the database.