Connect J2EE application with two different databases - mysql

I am developping J2EE application with appfuse that have default settings with mySQL
<!-- Database settings -->
<dbunit.dataTypeFactoryName>org.dbunit.ext.mysql.MySqlDataTypeFactory</dbunit.dataTypeFactoryName>
<dbunit.operation.type>CLEAN_INSERT</dbunit.operation.type>
<hibernate.dialect>org.hibernate.dialect.MySQL5InnoDBDialect</hibernate.dialect>
<jdbc.groupId>mysql</jdbc.groupId>
<jdbc.artifactId>mysql-connector-java</jdbc.artifactId>
<jdbc.version>5.1.27</jdbc.version>
<jdbc.driverClassName>com.mysql.jdbc.Driver</jdbc.driverClassName>
<jdbc.url>jdbc:mysql://localhost/${db.name}?createDatabaseIfNotExist=true&amp;useUnicode=true&amp;characterEncoding=utf-8&amp;autoReconnect=true</jdbc.url>
<jdbc.username>root</jdbc.username>
<jdbc.password></jdbc.password>
<jdbc.validationQuery>SELECT 1 + 1</jdbc.validationQuery>
But i need to connect my application with external database (SQL QERVER)to retreive some data.
I need help to configure maven to use two different database (mysql +sql server)

maven will help you out with loading of the driver jar files. You would be creating two data source / session factory to achieve this.

I think this can be achieved quite easily in a brief guideline as follows:
Create a second "dataSource" bean definition in applicationContext-resources.xml with MSSQL specific values such as driver class, url etc. Give it a different bean id, "dataSourceMSSQL" perhaps. Bind them up to different properties file if you don't want to hard coded property values. For simplicity you can just hard coded it (not recommended). If you chose otherwise, you need to create another properties file to store mssql connection properties, perhaps jdbc-mssql.properties and add it into propertyConfigurer list. This also require you to make changes to your pom file to include custom settings under <!-- Database settings --> section. This can be a bit complicated.
Create another "sessionFactory" bean definition in applicationContext-dao.xml with MSSQL specific values such as hibernate dialect etc. and binds it to "dataSourceMSSQL" as dataSource property ref. Give it a different bean id perhaps, "sessionFactoryMSSQL".
Wire your DAOs which require the new sessionFactory i.e.:
#Autowired private SessionFactory sessionFactoryMSSQL;
Hope that will work for you.

Related

guice return set of instances with custom annotation

I have very simple scenario where class A registers instances for types.
A.register(T1.class, new H1());
A.register(T2.class, new H2());
this is fairly simple configuration when done by hand but guice injection doesn't work when I create instances outside the guice framework.
I try to figure out how to create and configure A with all instance with custom annotation using guice.
I have found something like this Scan the classpath for classes with custom annotation but it is not using guice.
thanks
so I guess code.google.com/p/google-guice/wiki/Multibindings is the only option so far that works, but it is not as nice as I would expect since you need to connect everything by hand.

Unity and lifetime management configuration - always transient lifetime manager

I have an configuration error with Unity.
I am trying to implement http://unitymvc3.codeplex.com/, but i am stucked right now, because of this:
In my unity configuration I have this settings:
<register type="IMainDbContext" mapTo="WorkflowContext">
<lifetime type="hierarchical" />
<constructor></constructor>
</register>
But at the time of creating unity, (my simple code is here:)
UnityConfigurationSection section = ConfigurationManager.GetSection("unity") as UnityConfigurationSection;
if (section != null)
{
section.Configure(container);
}
this.container = container;
everything is configured great, except of registration "IManDbContext" which has LifetimeManagerType = {Name = "TransientLifetimeManager" FullName = "Microsoft.Practices.Unity.TransientLifetimeManager"}, but it should be hierarchical lifetime manager
Have you got any ideas how tell unity (in configuration, not in code) i want hierarchical lifetime manager?
Thanks for any tips.
My error was caused by this error:
I have multiple DbContext, but they was badly configured:
<register type="IMainDbContext" mapTo="WorkflowContext">
<lifetime type="hierarchical" />
<constructor></constructor>
</register>
<register type="IReportDbContext" mapTo="SomeBadContext">
<lifetime type="hierarchical" />
<constructor></constructor>
</register>
When I was using this configuration, which was bad, unity simple don`t configure any lifetime manager. After I set these context right, unity used my lifetime manager configurations just right.
I don't think you can. If you're specifying the lifetime type you need to either supply "singleton" or "external" (external being a custom lifetime).
Link to Unity Schema Documentation
In fairness, unless you're using multiple Unity containers I don't see the value of having a hierarchical lifetime manager, as this is designed to ensure that you only have one instance of your type instantiated in the main unity container and any child containers you generate from it.
So, unless you're planning on generating child containers and want a separate instance of your IMainDbContext inplmenting object, you might as well just using "singleton" lifetime manager.

Change Entity Framework database schema map after using code first

I've finished building my blog using EF and Code First.
EF was running against my local SQL Express instance, with [DBO] schema.
Now i want to publish the blog, and i have done the following :
Generetade the scripts for the tables and all objects from SQL Express and change [dbo] to my [administrator] schema from my server.
Ran the scripts against the server. No issues, all objects were created an populated just fine.
I have modified Webconfig and added my BlogContext connection string to point to the server not local sql express.
Published the site.
The error i am getting is : Invalid object name 'dbo.Articles'. - where Articles is one of my entities. It resides on my sql server, [Administrator].Articles.
As far as i can tell EF still thinks im using the DBO schema. Although i have added the connection string to point to administrator user.
How can i change the schema that EF thinks it should use?
EF will use dbo schema if you didn't configure the schema explicitly through data annotations or fluent API.
[Table("MyTable", "MySchema")]
public class MyEntity
{
}
Or
modelBuidler.Entity<MyEntity>().ToTable("MyTable", "MySchema");
Just for searchers: I am just working with EF5 .NET4.5, and
[Table("MyTable", "MySchema")]
does not work. Even if VS2012 shows there is an overload which takes 2 parameters, on build it gives the error: 'System.ComponentModel.DataAnnotations.Schema.TableAttribute' does not contain a constructor that takes 2 arguments.
But the code mapping works just fine.

entity framework code first and database user

We're running into a small problem deploying a web application to another environment.
We created the application's db using Entity Framework Code First approach (db automatic created from Model).
In this development environment, we are using integrated security and the tables are created under the dbo user. The tables are like
[dbo].[myTable]
For our other environment, we are using username/password authentication for the DB.
We scripted the tables and created them on the DB. So they are now named like
[myDbUser].[myTable]
When running the application, we encounter always the problem
Invalid object name 'dbo.myTable'.
Seems like the code is still trying to look for a dbo table, which is not present and thus fails.
Can anyone shed some light on this problem? Where does Entity Framework gets this dbo prefix from?
Thanks
Specify schema explicitly:
[Table("Users", Schema = "dbo")]
public class User { .. }
Or specify default db schema for your user - 'dbo'
To specify schema in fluent
protected override void OnModelCreating(DbModelBuilder modelBuilder)
modelBuilder.Entity<ClassName>().ToTable("TableName", "SchemaName");
I ran into this issue recently as well as we support several different schemas with the same model. What I basically came up with was the passing the schema name to the classes/methods that map the model. So for example, EntityTypeConfiguration subclasses take the schema name as a constructor argument, and pass it along with the hard-coded string to ToTable().
See here for a more detailed explanation: https://stackoverflow.com/a/14782001/243607

Entity Framework 4 Code First - Prevent DB Drop/Create

I've written an ASP.Net MVC 3 application using the Code First paradigm whereby when I make a change to the model the Entity Framework automatically attempts to re-create the underlying SQL Server Database via DROP and CREATE statements. The problem is the application is hosted on a 3rd party remote server which limits the number of databases I can have and does not seem to allow me to programmatically execute "CREATE DATABASE..." statements as I gather from this error message:
CREATE DATABASE permission denied in database 'master'.
Is there any way to stop the Entity Framework from dropping and attempting to re-create the whole database and instead make it simply drop the tables and re-create them?
After creating the database manually and running the application I also get the following error I guess as the Entity Framework tries to modify the database:
Model compatibility cannot be checked because the database does not contain model metadata. Ensure that IncludeMetadataConvention has been added to the DbModelBuilder conventions.
UPDATE: Found this gem through google, it sounds like its exactly what you need: http://nuget.org/Tags/IDatabaseInitializer
You can use a different database initializer. Lets say your context is called SampleContext then your constructor would look like this:
public SampleContext()
{
System.Data.Entity.Database.SetInitializer(new CreateDatabaseIfNotExists<SampleContext>());
}
Note that the above is the default initializer. You will probably need to create your own custom initializer by implementing IDatabaseInitializer. Theres some good info here: http://sankarsan.wordpress.com/2010/10/14/entity-framework-ctp-4-0-database-initialization/
Using EF 4.3 with Migrations you do not get this behavior - at least I have not seen it. But I also have this set in my code -
public sealed class DbConfiguration : DbMigrationsConfiguration<DatabaseContext>
{
public DbConfiguration()
{
AutomaticMigrationsEnabled = false;
}
}