spring-boot integrate with mybatis

Add below pom dependency

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <artifactId>1.0.14</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.2.8</version>
</dependency>
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.2.2</version>
</dependency>

We can use below tool to generate the mybatis code
https://github.com/spawpaw/mybatis-generator-gui-extension

Configure the datasource

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource  
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/flux?useUnicode=true&characterEncoding=utf-8&useOldAliasMetadataBehavior=true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

druid.spring.datasource.initialSize=5  
druid.spring.datasource.minIdle=5  
druid.spring.datasource.maxActive=20  
druid.spring.datasource.maxWait=60000  
druid.spring.datasource.timeBetweenEvictionRunsMillis=60000  
druid.spring.datasource.minEvictableIdleTimeMillis=300000  
druid.spring.datasource.validationQuery=SELECT 1 FROM DUAL  
druid.spring.datasource.testWhileIdle=true  
druid.spring.datasource.testOnBorrow=false  
druid.spring.datasource.testOnReturn=false  
druid.spring.datasource.poolPreparedStatements=false  
druid.spring.datasource.maxPoolPreparedStatementPerConnectionSize=20  
druid.spring.datasource.filters=stat,wall,log4j  
druid.spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
@Configuration
@MapperScan(basePackages="<the mapper interface class package path>")
public class MyBatisConfigure {

	// you can use this env to get the properties from application.properties
	// e.g. dbUrl : env.getProperty("spring.datasource.url");
    @AutoWried
    private Environment env;
	// configure datasource
	@Bean
	public DataSource dataSource() throws Exception {
			DruidDataSource datasource = new DruidDataSource();
			datasource.setUrl(dbUrl);
			datasource.setUsername(username);
			datasource.setPassword(password);
			datasource.setDriverClassName(driverClassName);
			// configuration
			datasource.setInitialSize(initialSize);
			datasource.setMinIdle(minIdle);
			datasource.setMaxActive(maxActive);
			datasource.setMaxWait(maxWait);
			datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
			datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
			datasource.setValidationQuery(validationQuery);
			datasource.setTestWhileIdle(testWhileIdle);
			datasource.setTestOnBorrow(testOnBorrow);
			datasource.setTestOnReturn(testOnReturn);
			datasource.setPoolPreparedStatements(poolPreparedStatements);
		    datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
			datasource.setFilters(filters);
			datasource.setConnectionProperties(connectionProperties);
			return datasource;
		}
	// configure SqlSessionFactory
	@Bean
	public SqlSessionFactory sqlSessionFactory(DataSrouce ds) throws Exception {
	    SqlSessionFactory fb = new SqlSessionFactoryBean();
	    fb.setDataSrouce(ds);
	    fb.setTypeAliasesPackage("<the domain model POJO package path>");
	    fb.setMapperLocations(new PathMatchingResourcesPatternResolver().getResources("classpath:<path>/*.xml"));
	    return fb.getObject();
	}
}

##Configure another datasource

public enum DatabaseType {
    DRUID_DS1,DRUID_DS2
}
public class DatabaseContextHolder {
    // each thread holds its own specific datasource
    private static final ThreadLocal<DatabaseType> contextHolder = new ThreadLocal<>();
    
    public static void setDatabaseType(DatabaseType type) {
        contextHolder.set(type);
    }

    public static DatabaseType getDatabaseType() {
        return contextHolder.get();
    }
}
public class DynamicDataSource extends AbstractRoutingDataSource() {
    protected Object determineCurrentLookupKey() {
        return DatabaseContextHolder.getDatasourceType();
    }
}

Refactor the MyBatisConfigure

@Bean
public DataSource druidDataSource1() throws Exception {
    // TODO
}
@Bean
public DataSource druidDataSource2() throws Exception {
    // TODO
}
@Bean
@Primary
public DynamicDataSource dataSource(@Qualifier("druidDataSource1") DataSource druidDataSource1,@Qualifier("druidDataSource2") DataSource druidDataSource2) {
    Map<Object, Object> targetDataSource = new HashMap<>();
    targetDataSource.put(DatabaseType.DRUID_DS1, druidDataSource1);
    targetDataSource.put(DatabaseType.DRUID_DS2, druidDataSource2);
    DynamicDataSource dataSource = new DynamicDataSource();
    dataSource.setTargetDataSources(targetDataSource);
    dataSource.setDefaultTargetDataSource(druidDataSource1);
    return dataSource;
}
@Bean
public SqlSessionFactory sqlSessionFactory(DynamicDataSource ds) throws Exception {
    // TODO
}

If you want use druidDataSource2 to query data, you need write the code like below:

@Repository
public class UserDAO {
    @Autowired
    private UserMapper userMapper;
    public List<User> selectById(long uid) {
        // choose the data source before query
        DatabaseContextHolder.setDatabaseType(DatabaseType.DRUID_DS2);
        // TODO
    }
}

or create an aspect class to set the datasource:

@Aspect
@Component
public class DataSourceAspect() {
    @Before("execution(* <DAO package path>.*.*(..))")
    public void setDataSourceKey(JoinPoint point) {
        if (point.getTarget() instanceof UserDAO) {
             DatabaseContextHolder.setDatabaseType(DatabaseType.DRUID_DS2);
        }
    }
}

Reference

《Java微服务实战》- 赵计刚

Another way to integrate with mybatis

Annotation way

add below dependency to pom.xml

<dependency>
	<groupId>org.mybatis.spring.boot</groupId>
	<artifactId>mybatis-spring-boot-starter</artifactId>
	<version>1.3.2</version>
</dependency>
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
</dependency>

add below configuration to application.properties

mybatis.type-aliases-package=com.mh.entity
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/wms?useUnicode=true&characterEncoding=utf-8
spring.datasource.username = root
spring.datasource.password = 

add @MapperScan annotation to the springboot application entry calss, or you can directly add @Mapper annotation to the Mapper interface class.

//org.mybatis.spring.annotation.MapperScan
@MapperScan("com.xx.mapper")
//org.apache.ibatis.annotations.Mapper
@Mapper

some userful annotion used in Mapper interface

@Select("select username,password from t_user")
@Results({
	@Result(property="username",column="username",javaType=String.class),
	@Result(property="password",column="password",javaType=String.class)
})
List<User> getAll();

@Select("select username,password from t_user where username = #{username}")
@Results({
	@Result(property="username",column="username",javaType=String.class),
	@Result(property="password",column="password",javaType=String.class)
})
User getOne(String username);

@Insert("insert into t_user(username,password) values(#{username},#{password})")
void insert(User user);

@Update("update t_user set password=#{password} where username=#{username}")
void update(User user)

@Delete("delete from t_user where username=#{username}")
void delete(String username)

XML configuration way

add below configuration to application.properties

mybatis.type-aliases-package = com.geekplus.springboot.apollo.fiyta.entity
mybatis.config-location=classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/wms?useUnicode=true&characterEncoding=utf-8
spring.datasource.username = root
spring.datasource.password = 

sample for mybatis-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
	<typeAliases>
		<typeAlias alias="Integer" type="java.lang.Integer" />
		<typeAlias alias="Long" type="java.lang.Long" />
		<typeAlias alias="HashMap" type="java.util.HashMap" />
		<typeAlias alias="LinkedHashMap"
			type="java.util.LinkedHashMap" />
		<typeAlias alias="ArrayList" type="java.util.ArrayList" />
		<typeAlias alias="LinkedList" type="java.util.LinkedList" />
	</typeAliases>
</configuration>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot provides easy integration with the Spring Integration framework for implementing messaging and integration patterns. Spring Integration provides support for various messaging protocols, including MQTT, a lightweight publish/subscribe messaging protocol. To integrate Spring Integration with MQTT in Spring Boot, follow these steps: 1. Add the following dependencies to your `pom.xml` file: ``` <dependency> <groupId>org.springframework.integration</groupId> <artifactId>spring-integration-core</artifactId> </dependency> <dependency> <groupId>org.springframework.integration</groupId> <artifactId>spring-integration-mqtt</artifactId> </dependency> ``` 2. Create a configuration class for MQTT integration: ``` @Configuration @EnableIntegration public class MqttIntegrationConfig { @Value("${mqtt.broker.url}") private String brokerUrl; @Value("${mqtt.client.id}") private String clientId; @Bean public MessageChannel mqttInputChannel() { return new DirectChannel(); } @Bean public MqttPahoClientFactory mqttClientFactory() { DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory(); MqttConnectOptions options = new MqttConnectOptions(); options.setServerURIs(new String[] { brokerUrl }); factory.setConnectionOptions(options); return factory; } @Bean public MessageProducer inbound() { MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter( clientId, mqttClientFactory(), "topic1", "topic2"); adapter.setCompletionTimeout(5000); adapter.setConverter(new DefaultPahoMessageConverter()); adapter.setQos(1); return adapter; } @Bean public MessageHandler mqttMessageHandler() { return new MessageHandler() { @Override public void handleMessage(Message<?> message) throws MessagingException { System.out.println("Received MQTT message: " + message.getPayload()); } }; } @Bean public IntegrationFlow mqttInFlow() { return IntegrationFlows.from(inbound()) .handle(mqttMessageHandler()) .channel(mqttInputChannel()) .get(); } } ``` 3. Configure the MQTT broker URL and client ID in your application properties file: ``` mqtt.broker.url=tcp://localhost:1883 mqtt.client.id=myClientId ``` 4. Use the `mqttInputChannel` channel to send messages to the MQTT broker. For example: ``` @Autowired private MessageChannel mqttInputChannel; public void sendMqttMessage(String payload) { mqttInputChannel.send(MessageBuilder.withPayload(payload).build()); } ``` With these steps, you can easily integrate MQTT messaging with your Spring Boot application using Spring Integration.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值