在mybatis-config.xml配置文件中添加上对应的mapper配置
新建mapper包,并在其下新建UserMapper.java类
User模块Mapper层:UserMapper.java
package mapper;
public interface UserMapper {
/**
* 通过用户id查询用户名称
*
* @param id 用户id
* @return 用户名称
*/
String selectUsernameById(Integer id);
}
有了方法定义后,我们再通过注解为该方法添加上对应的SQL语句
@Select(“SELECT username FROM user WHERE id = #{id}”)
User模块测试类:UserTest.java
@SuppressWarnings({“Duplicates”})
public class UserTest {
public static void main(String[] args) throws IOException, SQLException {
// 读取配置文件
InputStream configuration = Resources.getResourceAsStream(“mybatis-config.xml”);
// 得到 SqlSessionFactory 核心类
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
// 开始一个 sql 会话
SqlSession session = sqlSessionFactory.openSession();
// 得到 mapper
UserMapper mapper = session.getMapper(UserMapper.class);
// 调用注解的SQL
String username = mapper.selectUsernameById(1);
System.out.println("username: " + username);
// 关闭会话
session.close();
}
}