1.在该项目中的pom.xml,添加相关依赖,导入相关jar包
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
2.在resources中建一个mybatis-config.xml配置文件,连接相关数据库语句
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/bb?useSSL=false&useUnicode=true&characterEncoding=utf-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
3.编写实体类 4.编写相关接口userMapper.java、以及UserMapper.xml
<mapper namespace="dao.UserMapper"><!-- 对应的接口-->
<select id="getUserByLimit" parameterType="map" resultType="user">
select * from product limit #{startindex},#{pagesize}
</select>
id为该方法的名字,paramaterType为传递参数的属性,resultType为返回类型 5.编写测试类 ``mybatis是通过sqlSessionFactory–>Sqlsession–>执行sql语句
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {//获取sqlsessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession(){
SqlSession sqlSession = sqlSessionFactory.openSession();
return sqlSession;
}
---------
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> userlist = userMapper.getUserlist();
|