这是在mybatis-spring的帮助下做你需要的简单方法。
除非您已经使用 mybatis-spring,否则第一步是更改项目的配置,以便获得mybatis-spring 提供的SqlSessionFactory
使用。org.mybatis.spring.SqlSessionFactoryBean
下一步是设置/重置连接的用户角色的实现。在 mybatis 中,连接生命周期由实现org.apache.ibatis.transaction.Transaction
接口的类控制。查询执行器使用此类的实例来获取连接。
简而言之,您需要创建自己的此类实现并配置 mybatis 以使用它。
您的实现可以基于SpringManagedTransaction
mybatis-spring ,看起来像:
import org.springframework.security.core.Authentication;
class UserRoleAwareSpringManagedTransaction extends SpringManagedTransaction {
public UserRoleAwareSpringManagedTransaction(DataSource dataSource) {
super(dataSource);
}
@Override
public Connection getConnection() throws SQLException {
Connection connection = getCurrentConnection();
setUserRole(connection);
return connection;
}
private Connection getCurrentConnection() {
return super.getConnection();
}
@Override
public void close() throws SQLException {
resetUserRole(getCurrentConnection());
super.close();
}
private void setUserRole(Connection connection) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String username = authentication.getName();
Statement statement = connection.createStatement();
try {
// note that this direct usage of usernmae is a subject for SQL injection
// so you need to use the suggestion from
// https://stackoverflow.com/questions/2998597/switch-role-after-connecting-to-database
// about encoding of the username
statement.execute("set role '" + username + "'");
} finally {
statement.close();
}
}
private void resetUserRole(Connection connection) {
Statement statement = connection.createStatement();
try {
statement.execute("reset role");
} finally {
statement.close();
}
}
}
现在你需要配置 mybatis 来使用你的Transaction
实现。为此,您需要实现TransactionFactory
类似于mybatis-springorg.mybatis.spring.transaction.SpringManagedTransactionFactory
提供的功能:
public class UserRoleAwareSpringManagedTransactionFactory implements TransactionFactory {
@Override
public Transaction newTransaction(DataSource dataSource, TransactionIsolationLevel level, boolean autoCommit) {
return new UserRoleAwareSpringManagedTransaction(dataSource);
}
@Override
public Transaction newTransaction(Connection conn) {
throw new UnsupportedOperationException("New Spring transactions require a DataSource");
}
@Override
public void setProperties(Properties props) {
}
}
然后在你的 spring 上下文中定义一个类型的 beanUserRoleAwareSpringManagedTransactionFactory
并将其注入到你的 spring 上下文中transactionFactory
的属性中SqlSessionFactoryBeen
。
现在mybatis每次获取一个Connection
实现Transaction
都会设置当前spring security用户来设置角色。