--static_db utilise normalement le fichier de configuration XML (spring-servlet.xml) --dynamic_db génère dynamiquement SqlSessionFactory sans ** utiliser le fichier de configuration XML **
spring-servlet.xml
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://10.0.0.101:3306/static_db" />
<property name="username" value="root" />
<property name="password" value="password" />
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="sample.da.mapper" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
<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>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
Utiliser une instance DI Mapper
@Service
public class StaticDb01AccessService {
@Autowired
private UsersMapper usersMapper;
public void insert() {
Users record = new Users();
record.setNum("001");
record.setName("Ichiro Tanaka");
record.setCreated(new Date());
record.setUpdated(new Date());
usersMapper.insert(record);
}
}
Générer manuellement SqlSessionFactory et Mapper
@Service
public class DynamicDbAccessService {
//Par exemple, 10.0.0.115 dynamique_Appelé lors de la création de la base de données
public void insert(String endpoint) throws Exception {
DataSource dataSource = getDataSource(endpoint); // endpoint「10.0.0.115」
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);
config.addMapper(UsersMapper.class);
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(config);
SqlSession session = factory.openSession();
try {
UsersMapper usersMapper = session.getMapper(UsersMapper.class);
Users record = new Users();
record.setNum("001");
record.setName("Ichiro Tanaka");
record.setCreated(new Date());
record.setUpdated(new Date());
usersMapper.insert(record);
session.commit();
} catch (Exception e) {
session.rollback();
} finally {
session.close();
}
}
private DataSource getDataSource(String endpoint) {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl(String.format("jdbc:mysql://%s/dynamic_db", endpoint));
dataSource.setUsername("root");
dataSource.setPassword("password");
return dataSource;
}
}