- 创建项目
- 配置mybatis
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>3.3.1</version>
</dependency>
3.测试
(1)实体类
public class User {
private Integer id;
private String name;
private String pass;
创建mybatis-config.xml
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<!-- 此处的test为自己设计的数据库名 -->
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="root" />
<property name="password" value="x5" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="User.xml"/>
</mappers>
</configuration>
(4)映射文件配置
在resource下建立User.xml (或者建立mapper文件夹专门存放映射文件,我跳过了此步骤,没有影响但习惯不好)
<mapper namespace="com.jc.pojo.User">
<select id="select" parameterType="int" resultType="com.dym.pojo.User">
select * from t_student where id=#{id}
</select>
</mapper>
(5)编写测试类
在java文件夹下编写测试类Test.java
public class Test {
public static void main(String[] args) {
//定义读取文件名
String resources = "mybatis-config.xml";
//创建流
Reader reader = null;
try {
//读取mybatis-config.xml文件到reader对象中
reader= Resources.getResourceAsReader(resources);
} catch (IOException e) {
e.printStackTrace();
}
//初始化mybatis,创建SqlSessionFactory类的实例
SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);
//创建session实例
SqlSession session = sqlMapper.openSession();
//传入参数查询,返回结果
User user = session.selectOne("select",1);
//输出结果
System.out.println(user.getName());
//关闭session
session.close();
}
}