spring-boot integrate with mybatis

博客介绍了MyBatis的集成方法,包括添加pom依赖、使用工具生成代码、配置数据源等。还提到了两种集成方式,注解方式需添加依赖、配置及注解;XML配置方式则给出了相关配置示例,同时给出了参考资料。

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>
### 如何集成 Spring Session Data Redis 和 Redisson 或者解决相关问题 #### 背景介绍 Spring Session 是一个用于管理 HTTP 会话的框架,支持多种存储后端(如 Redis)。通过使用 `spring-session-data-redis`,可以将用户的会话数据存储到 Redis 中[^1]。而 Redisson 则是一个基于 Netty 的高性能 Java 客户端库,提供了丰富的分布式对象和服务功能。 当尝试将两者结合起来时,可能会遇到一些挑战,因为它们都依赖于 Redis 进行操作,但实现方式不同。以下是关于如何结合使用这两种技术以及可能解决方案的具体说明: --- #### 解决方案一:配置独立的 Redis 实例 如果希望同时使用 `spring-session-data-redis` 和 Redisson,则可以通过为每种工具分配不同的 Redis 数据库实例来避免冲突。例如,在 Redis 配置文件中定义多个数据库索引,并分别指定给这两个组件。 ```properties # Application properties for spring-session-data-redis spring.redis.database=0 spring.session.store-type=redis # Configuration for Redisson client pointing to different database index redisson.config.singleServerConfig.address="redis://127.0.0.1:6379" redisson.config.singleServerConfig.database=1 ``` 这种方式能够有效隔离两者的键空间,防止互相干扰[^1]。 --- #### 解决方案二:自定义命名前缀策略 另一种方法是让两个模块共享同一个 Redis 实例,但是通过设置唯一的键名前缀区分各自的数据范围。对于 `spring-session-data-redis` 来说,默认情况下它已经会对所有的 session 键附加特定前缀;而对于 Redisson 用户则可以在初始化客户端的时候手动添加类似的机制。 下面展示了一个简单的例子演示如何修改 Redisson 的默认行为以便兼容这种需求: ```java import org.redisson.Redisson; import org.redisson.api.RBucket; import org.redisson.api.RedissonClient; import org.redisson.config.Config; public class CustomizedRedissonExample { public static void main(String[] args) { Config config = new Config(); // Set custom key prefix here. String customPrefix = "myapp:"; config.useSingleServer() .setAddress("redis://127.0.0.1:6379"); RedissonClient redisson = Redisson.create(config); RBucket<String> bucket = redisson.getBucket(customPrefix + "testKey"); bucket.set("value"); System.out.println(bucket.get()); } } ``` 这样做的好处是可以减少资源消耗并简化运维流程,缺点则是增加了开发复杂度[^2]。 --- #### 方案三:利用 Redis Cluster 提供更高可用性和扩展能力 考虑到实际生产环境中的高并发场景,建议采用 Redis Cluster 架构作为底层支撑平台。在这种模式下,即使单台节点发生故障也不会影响整体服务稳定性。更重要的是,由于集群内部实现了自动分片(sharding),因此无论你是运行了多少个应用程序副本还是部署了几套业务逻辑单元,都可以轻松应对海量请求压力而不必担心性能瓶颈问题出现。 需要注意的一点在于,无论是 Spring Boot Starter Redis 还是官方推荐使用的 Jedis/Lettuce 库版本都需要满足最低要求才能正常连接至 Clustersetup 上去工作[^3]。 --- #### 总结 综上所述,针对 “How To Integrate Spring-Session-Data-Redis With Redisson Or Solve Related Issues” 这个主题给出了三种可行的技术路线图解法。具体选择哪一种取决于项目实际情况比如团队技术水平、预算成本等因素综合考量之后再做决定最为合适不过啦! ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值