View Javadoc
1   /*
2    *    Copyright 2009-2023 the original author or authors.
3    *
4    *    Licensed under the Apache License, Version 2.0 (the "License");
5    *    you may not use this file except in compliance with the License.
6    *    You may obtain a copy of the License at
7    *
8    *       https://www.apache.org/licenses/LICENSE-2.0
9    *
10   *    Unless required by applicable law or agreed to in writing, software
11   *    distributed under the License is distributed on an "AS IS" BASIS,
12   *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *    See the License for the specific language governing permissions and
14   *    limitations under the License.
15   */
16  package org.mybatis.guice.mappers;
17  
18  import jakarta.inject.Inject;
19  import jakarta.inject.Provider;
20  
21  import java.util.Objects;
22  
23  import org.apache.ibatis.session.SqlSessionManager;
24  
25  /**
26   * A generic MyBatis mapper provider.
27   */
28  public final class MapperProvider<T> implements Provider<T> {
29  
30    private final Class<T> mapperType;
31  
32    @Inject
33    private SqlSessionManager sqlSessionManager;
34  
35    public MapperProvider(Class<T> mapperType) {
36      this.mapperType = mapperType;
37    }
38  
39    public void setSqlSessionManager(SqlSessionManager sqlSessionManager) {
40      this.sqlSessionManager = sqlSessionManager;
41    }
42  
43    @Override
44    public T get() {
45      return this.sqlSessionManager.getMapper(mapperType);
46    }
47  
48    @Override
49    public int hashCode() {
50      return Objects.hashCode(this.mapperType);
51    }
52  
53    @Override
54    public boolean equals(Object obj) {
55      if (obj == null) {
56        return false;
57      }
58      if (this.getClass() != obj.getClass()) {
59        return false;
60      }
61      MapperProvider other = (MapperProvider) obj;
62      return Objects.equals(this.mapperType, other.mapperType);
63    }
64  }