Mybatis 01 环境搭建和基本使用
程序员文章站
2022-04-28 23:54:12
...
1.导包
2.配置文件
<?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://localhost:3308/mybatis" />
<property name="username" value="root" />
<property name="password" value="210374520" />
</dataSource>
</environment>
</environments>
</configuration>
3.创建实体类
package com.dhl.beyond.shiyan1;
public class User {
private int id; //用户的Id 或者是 学号
private String name; //姓名
private int age; //年龄
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
4.创建Mapper文件
<?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="com.dhl.beyond.shiyan1.userMapper">
<select id="getUser" parameterType="int" resultType="com.dhl.beyond.shiyan1.User">
select * from users where id=#{id}
</select>
</mapper>
5.注册
<mappers>
<mapper resource="com/dhl/beyond/shiyan1/userMapper.xml"/>
</mappers>
6.测试类
package com.dhl.beyond.shiyan1;
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.Reader;
public class TestUser {
public static void main(String[] args) throws IOException {
String resource = "config.xml";
//加载mybatis的配置文件(它也加载关联的映射文件)
Reader reader = Resources.getResourceAsReader(resource);
//构建sqlSession的工厂
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
//创建能执行映射文件中sql的sqlSession
SqlSession session = sessionFactory.openSession();
//映射sql的标识字符串
String statement = "com.dhl.beyond.shiyan1.userMapper.getUser";
//执行查询返回一个唯一user对象的sql
User user = session.selectOne(statement, 1);
System.out.println(user);
}
}
7.结果集
补充: 目录结构
上一篇: 大数据之Hive(二)-Hive安装运行环境搭建和Hive基本操作
下一篇: 数据分析之清洗和整理