第一步:导入 jar
第二步:全局配置文件内容
第三步:创建sql语句文件
第四步:测试连接
1.导入jar
驱动包这里导入的是mysql数据库,导入对应的数据库j驱动ar包;
2.全局配置文件内容(编写 JDBC 四个变量)
创建一个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>
<!-- default 引用 environment 的 id,当前所使用的环境 -->
<environments default="default">
<!-- 声明可以使用的环境 -->
<environment id="default">
<!-- 使用原生 JDBC 事务 -->
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<!-- 驱动 -->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<!-- 连接数据 ssm数据库名称-->
<property name="url" value="jdbc:mysql://localhost:3306/ssm"/>
<!-- 连接账号 -->
<property name="username" value="root"/>
<!-- 连接密码 -->
<property name="password" value="scott"/>
</dataSource>
</environment>
</environments>
<mappers>
<!-- 创建sql语句连接-->
<mapper resource="com/gx/mapper/FlowerMapper.xml"/>
</mappers>
</configuration>
3.创建sql语句文件
创建xml文件,用于编写需要执行的SQL命令(常用命名规则:实体类名+Mapper.xml)
<?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="SqlStatement.sql">
<!--resultType 返回类型,返回多列数据 -->
<select id="selectYG" resultType="com.gx.pojo.Y_YuangGong">
select * from y_yuangong
</select>
<!--resultType 返回类型 为int型-->
<select id="selectByid" resultType="int">
select count(*) count from y_yuangong
</select>
<select id="selectName" resultType="Map">
select YuanGongMC from y_yuangong
</select>
<!--parameterType 参数类型 :一般有两种形式:Map 集合和实体类进行参数传递-->
<!--#{pageStart} 如果是参数类型是Map集合,表示该pageStart键的值,如果是实体类表示获取类中对应的成员变量 -->
<select id="selectYGByPage" resultType="Y_YuangGong" parameterType="Map">
select * from y_yuangong limit #{pageStart},#{pageSize}
</select>
</mapper>
第四步:测试连接
public static void main(String[] args) throws IOException {
//读取连接属性
InputStream isInputStream=Resources.getResourceAsStream("GlobalConfiguration.xml");
//创建数据库连接(使用工厂模式)
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(isInputStream);
//打开数据库(生产SqlSession)
SqlSession session=factory.openSession();
//调用SQL
//查询多条数据 -----------------------------SqlStatement.sql.selectYG= 类名.id
List<Y_YuangGong> list=session.selectList("SqlStatement.sql.selectYG");
//遍历数据
for (Y_YuangGong y_YuangGong : list) {
System.out.println(y_YuangGong.getYuanGongMC()+" " +y_YuangGong.getYuanGongBiaoHao());
}
//关闭数据库连接
session.close();
}
补充部分:
//查询第一种 多条数据
List<Y_YuangGong> list=session.selectList("SqlStatement.sql.selectYG");
//查询第二种 返回一个值,或者一条数据
Integer count=session.selectOne("SqlStatement.sql.selectByid");
//查询第三种 返回键值对形式
//设置 YuanGongMC 为key值,sql查询的是value值 输出格式:啊哈={YuanGongMC=啊哈}
Map<Object, Object> map=session.selectMap("SqlStatement.sql.selectName", "YuanGongMC");
变量输出内容: