How to pass global properties in ibatis - spring

I'm developing a Spring MVC application using ibatis for the database interaction layer. I'd like to be able to set the name of the database via a properties file in my classpath (or via the spring xml configuration) so I can change the database on the fly for a certain application and can be changed by setting the parameter and redeploying the application.
What I'm looking for is being able to set the database name on an existing database. Lets say I have a system called DB1 with databases: user, user_qa, and user_dev. I'd like to be able to parameterize the SQLs so that instead of doing:
SELECT * FROM user.Logins
I'd do
SELECT * FROM $database.user$.Logins
So I can change the database.user property and redeploy the application instead of rewriting a ton of SQL statements each time I changed the name of the databases.

Pretty simple to do in Spring. Say you have a basic conf file [database.properties]:
jdbc.username = user
jdbc.host = mydbserver.com
Then in your Spring config xml file :
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>classpath:database.properties</value>
</property>
</bean>
Now where you want those variables substitute the name in the config file:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="host"><value>${jdbc.host}</value></property>
<property name="username"><value>${jdbc.username}</value></property>
</bean>

Related

Spring JdbcTemplate , How to dynamically set username and password in Spring config XML file?

Spring JDBC: while using JdbcTemplate how to set username and password for every user ?, Currently I am Configuring datasource object as a spring bean (Spring config.xml file ) and able to login with sinlge username and password , also used properties file and placeholder for the same
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/apu"></property>
<property name="username" value="root"></property>
<property name="password" value=""></property>
</bean>
What are the ways to set username value and password value for every user who logsin ?
This is my first Spring application hence not able to find right approach ..
Generally, in a web application, each user do not use its own identity to access the database. The common pattern is to have one single database user for the application, and let the application manage the permission of its own users.
As M.Deinum said, this pattern allows the application to use a connection pool, where database connections are recycled across different requests which dramatically reduces the database load (establishment of the connection is expensive)
If you look at (almost) all the spring examples an tutorial, they consitently use that approach with one single database user for the whole web application.
If you really need that each user uses it own database identity you must use a UserCredentialsDataSourceAdapter as suggested by M. Deinum, with no database pool.

spring batch use data source instead of jdbc using batch-db2.properties

I am fairly new to spring batch. I have it working embedded inside my spring mvc web application. It is using a db2 database data store to log job information. At present my batch-db2.properties reads as...
batch.jdbc.driver=com.ibm.db2.jcc.DB2Driver
batch.jdbc.url=<<my database url>>
batch.jdbc.user=<<my database user>>
batch.jdbc.password=<<my database password>>
batch.schema=<<my database scehma>>
batch.jndi.name=jdbc/<<my jndi url>>
So I've set both jdbc properties and well as the jndi property. The jobs are running fine but my question is what type of connection is my spring batch installation using.
If both are set does it use jdbc or jndi? Also can someone point me to the spring batch documentation page where it gives more information about these settings. I could not find it.
Here is my data source configuration....
<beans profile="server">
<bean id="ePosDataSource"
class="org.springframework.jndi.JndiObjectFactoryBean"
p:jndiName="java:comp/env/jdbc/reportingManagerDataSource"
p:lookupOnStartup="false"
p:cache="true"
p:proxyInterface="javax.sql.DataSource"/>
<jee:jndi-lookup id="ePosDataSource"
jndi-name="jdbc/reportingManagerDataSource"
cache="true"
resource-ref="true"
lookup-on-startup="false"
proxy-interface="javax.sql.DataSource"/>
<bean id="custDbDataSource"
class="org.springframework.jndi.JndiObjectFactoryBean"
p:jndiName="java:comp/env/jdbc/reportingManagerCustDbDataSource"
p:lookupOnStartup="false"
p:cache="true"
p:proxyInterface="javax.sql.DataSource" />
<jee:jndi-lookup id="custDbDataSource"
jndi-name="jdbc/reportingManagerCustDbDataSource"
cache="true"
resource-ref="true"
lookup-on-startup="false"
proxy-interface="javax.sql.DataSource"/>
</beans>
thanks!

Multi-tenant webapp using Spring MVC and Hibernate 4.2.0.Final

I have developed a small webapp using and SpringMVC(3.1.3.RELEASE) and Hibernate 4.2.0.Final.
I'm trying to convert it to be a multi-tenant application.
Similar topics have been covered in other threads, but I couldn't find a definitive solution to my problem.
What I am trying to achieve is to design a web app which is able to:
Read a datasource configuration at startup (an XML file containing multiple datasource definitions, which is placed outside the WAR file and it's not the application-context or hibernate configuration file)
Create a session factory for each one of them (considering that each datasource is a database with a different schema).
How can i set my session factory scope as session? ( OR Can i reuse the same session factory ?) .
Example:
Url for client a - URL: http://project.com/a/login.html
Url for client b - URL: http://project.com/b/login.html
If client "a" make request,read the datasource configuration file and Create a session factory using that XML file for the client "a".
This same process will be repeating if the client "b" will send a request.
What I am looking, how to implement datasource creation upon customer subscription without editing the Spring configuration file. It needs to be automated.
Here is my code ,that i have done so far.
Please anyone tell me,What modifications i need to be made?
Please give an answer with some example code..I am quite new in spring and hibernate world.
Spring.xml
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}"
p:username="${jdbc.username}" p:password="${jdbc.password}" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
JDBC.properties File
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.dialect=org.hibernate.dialect.MySQLDialect
jdbc.databaseurl=jdbc:mysql://localhost:3306/Logistics
jdbc.username=root
jdbc.password=rot#pspl#12
hibernate.cfg.xml File
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<mapping class="pepper.logis.organizations.model.Organizaions" />
<mapping class="pepper.logis.assets.model.Assets" />
</session-factory>
</hibernate-configuration>
Thanks,
First create a table for Tenant with tenant_id and associate it with all users.Now, you can fetch this details while the user logs in and set it in session.
We are using AbstractRoutingDataSource to switch DataSource for every request on Spring Boot. I think it is Hot Swapable targets/datasource mentioned by #bhantol above.
It solves our problems but I don't think it is sound solution. I guess JNDI could be a better one than AbstractRoutingDataSource.
Wondering what you ended up with.
Here are some ideas for you.
Option 1) Single Application Instance.
It is somewhat ambitious to to this using what you are actually trying to achieve.
The gist is to simply deploy the same exact application with different context root on the same JVM. You can still tune the JVM as a whole like you would have if you had a truely multi-tenant application. But this comes at the expense of duplication of classes, contexts, local caching, start up times etc.
But as of today the Spring Framework 4.0 does not provide much of an multi-tenancy support (other than Hot Swapable targets/datasource) etc. I am looking for a good framework but it may be a wash to move away from Spring at this time for me.
Option 2) Multiple deployments of same application (more practical as of today)
Just have your same exact application deploy to the same application server JVM instance or even different.
If you use the same instance you may now need to bootstrap your app to pickup a DataSource based on what the instance should serve e.g. client=a property would be enough to pickup a **a**DataSource" or **b**DataSource I myself ended up going this approach.
If you have a different application server instance you could just configure a different JNDI path and treat things generically. No need for client="a" property because you have liberty to define your datasource differently with the same name.

Spring and connecting to AS400

I am trying to connect to AS400 using spring but I am having no luck.
I was wondering is it possible to set the default schema in spring using the class AS400JDBCConnectionPoolDataSource?
here is the spring configuration I am using
<bean id="DataSource" class="com.ibm.as400.access.AS400JDBCConnectionPoolDataSource">
<property name="serverName"><value>tradingdev.url.com</value></property>
<property name="user"><value>user</value></property>
<property name="password"><value>password</value></property>
<property name="dataTruncation"><value>false</value></property>
<property name="naming"><value>sql</value></property>
<property name="errors"><value>full</value></property>
<property name="trace"><value>false</value></property>
</bean>
Thanks
Damien
It is not a Spring issue, but here's how to specify the default schema:
You must set the libraries property to the default library (libraires can be see as schemas in as400 terminology). This works in 2 ways with as400, depending on how the naming property is set. If naming is set to 'sql' (as in your config), the libraries value only takes one value and is considered as the default schema. If you set the naming property to 'system', then you can specify a comma separated library list: tables and other objects names are resolved in the order specified in the list.

external config based on context path

I would like to deploy multiple independent copies of a particular web-app on the same tomcat server under different context paths. Each web-app will need different configuration settings (database name, password, etc), but I would like to keep the wars exactly identical.
My plan was to have the app figure out its context path on startup, then read a specific .properties file outside of tomcat identified by the context path. For example, if a war was deployed to {tomcat path}/webapps/pineapple, then I would want to read /config/pineapple.properties
I've been trying to find a way to inject an instance of ServletContext via spring (3), but all the advice I've seen so far use the deprecated ServletContextFactoryBean.
Is there a better way to get the context path injected or better way to load external files based on the context path?
With the help of ServletContextAttributeFactoryBean and Spring EL, you can reference ServletContext init parameters (<context-param> in web.xml) like that:
#{contextAttributes.myKey}
This allows you to use PropertyPlaceHolderConfigurer and load property files from arbitrary, user-defined locations:
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="#{contextParameters.APP_HOME}/conf/app.properties"/>
</bean>
The corresponding definition of the ServletContext init parameter in Tomcat's context.xml:
<Parameter name="APP_HOME" value="file:/test" override="false"/>
Or in your app's web.xml:
<context-param>
<param-name>APP_HOME</param-name>
<param-value>file:/test</param-value>
</context-param>
This should be the solution.
<bean name="envConfig" class="EnvironmentConfiguration">
<property name="locations">
<list>
<value>file:///#{servletContext.contextPath}.properties</value>
</list>
</property>
<property name="ignoreUnresolvablePlaceholders" value="true" />
</bean>
Extend Propertyplaceholderconfigurer to use DB to pick up the values. Example here
Load the actual values of the settings (database name, password etc) to the db as part of seed data
When your web-app's app ctx is being initialized, the properties are resolved from the DB
This is the approach we have been following and works great. If you can switch to Spring 3.1 then it has support for Environment Profiles which may be useful for you.

Resources