在工程下的pop.xml文件中,引入依赖
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
</dependencies>
中间<version>标签里的内容可更改,指的是版本
因为要连接数据库,所以接下来引入mysql的驱动
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
junit单元测试
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
在resources文件里新建文件:mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!--数据库连接信息-->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///mybatis?useSSL=false"/><!--连接数据库地址-->
<property name="username" value="root"/><!--mysql的用户名-->
<property name="password" value="x5"/><!--mysql的密码-->
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="UserMapper.xml"/><!--指定映射文件的路径-->
</mappers>
</configuration>
在resources文件里新建文件:UserMapper.xml(不一定非要是User,与实体类对应)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace名称空间-->
<mapper namespace="test">
<select id="selectAll" resultType="Pojo.User">
select * from tb_user
</select>
</mapper>
实体类的属性与数据库对应
?
?测试类MyBatisDemo.java
import Pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class MyBatisDemo {
public static void main(String[] args) throws IOException {
//加载核心配置,获取SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//获取 SqlSession,用它执行sql
SqlSession sqlSession=sqlSessionFactory.openSession();
//执行sql语句
List<User> users=sqlSession.selectList("test.selectAll");
System.out.println(users);
//释放资源
sqlSession.close();
}
}
运行
官方文档:mybatis – MyBatis 3 | Getting started
|