在MyBatis中使用接口映射是一种基于Java接口而非XML映射文件的方式来绑定SQL查询和操作。这种方法使用注解来指定SQL语句,并将其直接关联到接口方法上。通过这种方式,可以省去编写XML映射文件的工作,而且使得SQL语句和Java代码的关系更直观。
首先,定义一个接口来表示你的数据库操作。例如,如果你有一个User表,你可以创建一个UserMapper接口:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public interface UserMapper { @Select("SELECT * FROM users WHERE id = #{id}") User getUserById(Integer id);
@Insert("INSERT INTO users(name, email) VALUES(#{name}, #{email})") @Options(useGeneratedKeys = true, keyProperty = "id") void insertUser(User user);
@Update("UPDATE users SET name=#{name}, email=#{email} WHERE id=#{id}") void updateUser(User user);
@Delete("DELETE FROM users WHERE id=#{id}") void deleteUser(Integer id); } |
这个接口定义了基本的增删改查操作,并通过注解@Select、@Insert、@Update、@Delete与SQL语句相关联。
接下来,在MyBatis配置文件中指定你的接口。你无需指定XML文件,因为你用注解定义了SQL语句。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<configuration> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/> <property name="username" value="root"/> <property name="password" value="password"/> </dataSource> </environment> </environments>
<mappers> <mapper class="org.example.mapper.UserMapper"/> </mappers> </configuration> |
创建SqlSessionFactory和SqlSession,然后通过SqlSession获取Mapper接口的实例。
1 2 3 4 5 6 7 8 9 |
try (SqlSession session = sqlSessionFactory.openSession()) { UserMapper mapper = session.getMapper(UserMapper.class);
// 使用mapper操作数据库 User user = mapper.getUserById(1); System.out.println(user.getName());
// 更多的数据库操作... } |
在MyBatis初始化过程中,当你调用getMapper(Class<T> type)方法时,MyBatis内部使用了JDK动态代理来创建Mapper接口的实现。
1 2 3 |
public <T> T getMapper(Class<T> type) { return configuration.<T>getMapper(type, this); } |
在Configuration类中,getMapper方法会调用mapperRegistry中的getMapper方法,该方法最终调用了MapperProxyFactory来创建Mapper代理:
1 2 3 4 5 6 7 8 9 10 11 |
public <T> T getMapper(Class<T> type, SqlSession sqlSession) { final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type); if (mapperProxyFactory == null) { throw new BindingException("Type " + type + " is not known to the MapperRegistry."); } try { return mapperProxyFactory.newInstance(sqlSession); } catch (Exception e) { throw new BindingException("Error getting mapper instance. Cause: " + e, e); } } |
MapperProxyFactory创建代理对象:
1 2 3 4 5 6 7 8 |
public T newInstance(SqlSession sqlSession) { final MapperProxy<T> mapperProxy = new MapperProxy<>(sqlSession, mapperInterface, methodCache); return newInstance(mapperProxy); }
protected T newInstance(MapperProxy<T> mapperProxy) { return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[]{mapperInterface}, mapperProxy); } |
MapperProxy是实际的代理类,它实现了InvocationHandler接口。每当你调用一个Mapper接口的方法时,都会调用invoke方法。在这个方法中,MyBatis会判断该调用是否对应一个SQL操作,并执行相应的SQL语句:
1 2 3 4 5 6 7 8 |
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (Object.class.equals(method.getDeclaringClass())) { return method.invoke(this, args); } else { final MapperMethod mapperMethod = cachedMapperMethod(method); return mapperMethod.execute(sqlSession, args); } } |
通过以上步骤和解析,你可以在MyBatis中成功地使用接口映射,以简洁和直观的方式进行数据库操作。