一、搭建环境及工具准备
1.java 开发环境:JDK1.8 及以上
2.java 开发工具:eclipse
3.数据库服务器:MySQL
4数据库管理工具:navcat
二、搭建详细步骤
?
2.添加MyBatis核心配置文件
新建一个和src类型的resource文件用于存放MyBatis核心配置文件
?
?
?需修改成自己的数据库信息 url、username、password
<?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.cj.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mybatis" />
<property name="username" value="root" />
<property name="password" value="123456" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="UserMapper.xml" />
</mappers>
</configuration>
3.创建实体类
这里数据库表的属性需要与实体类的属性一致!!!
package user;
public class User {
private int age;
private String name;
private String passwordString;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPasswordString() {
return passwordString;
}
public void setPasswordString(String passwordString) {
this.passwordString = passwordString;
}
}
4创建SQL映射文件
id属性:表示该SQL语句的唯一标识符
resultType属性:填写全类名,表示SQL语句返回值类型,此处通过SQL语句查询数据,将数据直接映射到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">
<mapper namespace="/">
<!-- SQL映射写在这里 -->
<select id="findAllUser" resultType="domain.User">
select * from user
</select>
</mapper>
5.创建Junit,代码测试,输出结果
?创建TestUser类
package test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
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 org.junit.*;
import domain.User;
public class UserTest {
@Test
public void findUser() throws IOException {
//1.加载mybatis核心配置文件
InputStream inputStream = Resources.getResourceAsStream("mybatis_config.xml");
//2.获取SqlSessionFactory对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//3.得到执行sql的对象SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//4.执行sql语句
List<User> list = sqlSession.selectList("findAllUser");
//5.处理结果
for (User user: list) {
System.out.println("用户名:"+user.getName()+",密码:"+user.getPassword()+"年纪:"+user.getAge());
}
//6.关闭数据库会话
sqlSession.close();
}
}
?
|