[JAVA] I want to issue a connection when a database is created using Spring and MyBatis

What you want to do

--Each server has MySQL and you can access each from the app

Realization method

--static_db normally uses XML configuration file (spring-servlet.xml) --dynamic_db dynamically generates SqlSessionFactory without ** using XML config file **


Various versions

Setting static_db connection information


  <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://" />
    <property name="username" value="root" />
    <property name="password" value="password" />

  <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="sample.da.mapper" />
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>

  <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" name="sqlSessionFactory">
    <property name="dataSource" ref="dataSource"></property>
    <property name="mapperLocations" value="classpath*:sample/da/mapper/*.xml"/>

  <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/>
  <tx:annotation-driven transaction-manager="transactionManager"/>

Access to static_db

Use DI Mapper instance

public class StaticDb01AccessService {

	private UsersMapper usersMapper;
	public void insert() {
		Users record = new Users();
		record.setName("Ichiro Tanaka");
		record.setCreated(new Date());
		record.setUpdated(new Date());

Access to dynamic_db

Manually generate SqlSessionFactory and Mapper

public class DynamicDbAccessService {

	//For example, dynamic_Called when db was created
	public void insert(String endpoint) throws Exception {
		DataSource dataSource = getDataSource(endpoint); // endpoint「」
		TransactionFactory trxFactory = new JdbcTransactionFactory();
		Environment env = new Environment("dynamic_db", trxFactory, dataSource);
		Configuration config = new Configuration(env);
		TypeAliasRegistry aliases = config.getTypeAliasRegistry();
		aliases.registerAlias("user", Users.class);
		SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(config);
		SqlSession session = factory.openSession();
		try {
			UsersMapper usersMapper = session.getMapper(UsersMapper.class);
			Users record = new Users();
			record.setName("Ichiro Tanaka");
			record.setCreated(new Date());
			record.setUpdated(new Date());
		} catch (Exception e) {
		} finally {

	private DataSource getDataSource(String endpoint) {
		BasicDataSource dataSource = new BasicDataSource();
		dataSource.setUrl(String.format("jdbc:mysql://%s/dynamic_db", endpoint));
		return dataSource;

Recommended Posts

I want to issue a connection when a database is created using Spring and MyBatis
When internationalizing is supported by Spring Boot, a specific locale is not translated and I am addicted to it
I tried using a database connection in Android development
I want to find a relative path in a situation using Path
I want to make a list with kotlin and java!
I want to call a method and count the number
I want to make a function with kotlin and java!
When JDBC connection pooling is created
ProxyFactory is convenient when you want to test AOP in Spring!
I tried using Spring + Mybatis + DbUnit
Things to consider when running a specified job using Spring Batch
I wanted to animate a row when using realm and RecyclerView on Android, but I gave up
I want to download a file on the Internet using Ruby and save it locally (with caution)
I summarized the points to note when using resources and resources in combination
When I ran a jar created using WildFly Swarm, I got an InvocationTargetException.
A story I was addicted to when testing the API using MockMVC
I want to display images with REST Controller of Java and Spring!
I want to summarize Apache Wicket 8 because it is a good idea
I want to display an error message when registering in the database
"Teacher, I want to implement a login function in Spring" ① Hello World
I want to develop a web application!
I want to write a nice build.gradle
I want to write a unit test!
When I defined a session scope bean in Spring Boot, it behaved strangely and needed to be adjusted.
Let's create a TODO application in Java 2 I want to create a template with Spring Initializr and make a Hello world
[Java] I installed JDBC and tried to connect with servlet + MySQL. (There is a version using DAO / Bean)
What to do when you want to delete a migration file that is "NO FILE"
Corresponds to a property whose type is an array when empty using JsonDeserializer
A story when I tried to make a video by linking Processing and Resolume
I want to be able to read a file using refile with administrate [rails6]
[Java] I tried to connect using a connection pool with Servlet (tomcat) & MySQL & Java
When you want to notify an error somewhere when using graphql-spring-boot in Spring Boot
I want to recursively get the superclass and interface of a certain class
Introducing what I made when I wanted to add a header and footer to RecyclerView
[Ruby] I want to do a method jump!
A memo when fumbling and developing using JavaFX
I want to simply write a repeating string
I want to design a structured exception handling
I tried to link JavaFX and Spring Framework.
I tried to implement a server using Netty
Rspec: I want to test the post-execution state when I set a method on subject
I tried to create a shopping site administrator function / screen with Java and Spring
[MyBatis] I want to map a query query to a table that has a one-to-many relationship to a nested bean
What I was addicted to when developing a Spring Boot application with VS Code
A memo that I was addicted to when making batch processing with Spring Boot
When making a personal app, I was wondering whether to make it using haml
I tried using Wercker to create and publish a Docker image that launches GlassFish 5.
A site that was easy to understand when I was a beginner when I started learning Spring Boot
I want to use PowerMock in a class that combines parameterized tests and ordinary tests
A story that stumbled when deploying a web application created with Spring Boot to EC2
A story I was addicted to when getting a key that was automatically tried on MyBatis
I want to implement it additionally while using kotlin on a site running Java
Create a portfolio app using Java and Spring Boot
I want to call a method of another class
I want to judge the range using the monthly degree
I want to use a little icon in Rails
A memorandum when trying to create a GUI using JavaFX
I want to monitor a specific file with WatchService
I made a Restful server and client in Spring.
I want to define a function in Rails Console
[Introduction to Spring Boot] Submit a form using thymeleaf