对于多租户应用程序,我有以下内容:
public class MultiTenantTransactionManager extends JpaTransactionManager {
private static final Logger LOGGER = LoggerFactory.getLogger(MultiTenantTransactionManager.class);
private static final long serialVersionUID = 1L;
@Inject
private DefaultCurrentTenantResolver tenantResolver;
@Override
protected void doBegin(final Object transaction, final TransactionDefinition definition) {
super.doBegin(transaction, definition);
final EntityManagerHolder emHolder = (EntityManagerHolder) TransactionSynchronizationManager.getResource(getEntityManagerFactory());
final EntityManager em = emHolder.getEntityManager();
LOGGER.debug("Getting tenant-id");
final Serializable tenantId = tenantResolver.getCurrentTenantId();
if (tenantId != null) {
em.setProperty("tenant-id", tenantId);
} else {
System.out.println("tenant-id is null");
}
}
}
注册为:
@Bean
public JpaTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new MultiTenantTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory()
.getObject());
return transactionManager;
}
当我这样做初始化一些测试数据时,会调用doBegin方法:
@PostConstruct
@Transactional
private void createDefaultUsers() {
LOGGER.debug("Creating test users");
Tenant tenant1 = new Tenant("Tenant 1");
tenantRepository.saveAndFlush(tenant1);
Tenant tenant2 = new Tenant("Tenant 2");
tenantRepository.saveAndFlush(tenant2);
User user1 = new User("username1", "User description", "admin");
user1.setTenant(tenant1);
User user2 = new User("username2", "User description", "admin");
user2.setTenant(tenant2);
userRepository.saveAndFlush(user1);
userRepository.saveAndFlush(user2);
}
但是,当调用以下Web服务时,它不是
@RequestMapping(value = "/security/listUsers/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<User>> listAllUserv(@PathVariable("id") String id,
@RequestHeader(value = "user_id", required = true) String user_uuid,
@RequestHeader(value = "tenant_id", required = true) String tenant_uuid,
@RequestHeader(value = "api_key", required = false) String apiKey, HttpServletRequest request,
HttpSession httpSession) {
if (tenant_uuid == null) {
throw new UnauthorizedUserException();
}
TenantContext.setTenant(tenant_uuid);
User user = userService.find(user_uuid);
List<User> users = userService.findAll();
if (users.isEmpty()) {
return new ResponseEntity<List<User>>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<List<User>>(users, HttpStatus.OK);
}
服务守则:
@Service("userService")
public class UserServiceImpl implements UserService {
@Resource
private UserRepository repository;
@Override
public User find(String uuid) {
return repository.find(uuid);
}
@Override
public void create(User user) {
repository.saveAndFlush(user);
return;
}
@Override
@Transactional
public List<User> findAll() {
return repository.findAll();
}
}
我不明白在服务器启动时初始化数据和通过Web服务调用findAll()方法之间的区别是什么。一个设置实体管理器的租户ID,另一个设置。两者都使用相同的存储库等
非常感谢任何指导