1.Mybatis的第一个例子

MyBatis 官方文档:   http://www.mybatis.org/mybatis-3/index.html

下载 MyBatis ,当前版本 3.5.2: https://github.com/mybatis/mybatis-3/releases

1.使用数据库脚本创建数据库

/*
SQLyog Ultimate v11.24 (32 bit)
MySQL - 5.6.39 : Database - af_example
*********************************************************************
*/


/*!40101 SET NAMES utf8 */;

/*!40101 SET SQL_MODE=''*/;

/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`af_example` /*!40100 DEFAULT CHARACTER SET utf8 */;

USE `af_example`;

/*Table structure for table `student` */

DROP TABLE IF EXISTS `student`;

CREATE TABLE `student` (
  `id` int(11) NOT NULL COMMENT '学号',
  `name` varchar(32) NOT NULL COMMENT '姓名',
  `sex` tinyint(1) DEFAULT NULL COMMENT '性别',
  `cellphone` varchar(16) DEFAULT '13800000000' COMMENT '手机号',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

/*Data for the table `student` */

insert  into `student`(`id`,`name`,`sex`,`cellphone`) values (20190001,'莫凡',1,'14099000892'),(20190002,'穆宁雪',0,'12823999991'),(20190003,'叶心夏',0,'13691243355'),(20190004,'赵满延',1,'13234344352'),(20190005,'穆白',1,'13699292899'),(20190006,'张小候',1,'13819289890'),(20190007,'炎姬',0,'13800000000'),(20190008,'阿帕丝',0,'13410012908'),(20190009,'斩空',1,'13509890090'),(20190010,'唐月',0,'18799891829'),(20190011,'华展鸿',0,'13882938990');

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

表结构:

原始数据:

2.导入包及修改配置文件

导入数据库驱动和mybatis的包

加入 mybatis-config.xml

- 将此 xml文件拷贝到 src 根目录下 ( 请拷贝粘贴,不要手写)

- 检查修改四项的值 driver,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.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://127.0.0.1/af_example?useUnicode=true&amp;characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="a1b2c3"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <mapper resource="mybatis-mapper.xml"/>
  </mappers>
</configuration>

加入 mybatis-mapper.xml

- 将此 xml文件拷贝到 src 根目录下 ( 请拷贝粘贴,不要手写)

<?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="af.test">
  <select id="getStudent" resultType="my.Student">
    select * from student where id = #{id}
  </select>
</mapper>

添加类 my.Student

- 类的属性,与数据库表中的字段一致

package my;

public class Student
{
	public Integer id;
	public String name;
	public Boolean sex;
	public String cellphone;

	public Integer getId()
	{
		return id;
	}

	public void setId(Integer id)
	{
		this.id = id;
	}

	public String getName()
	{
		return name;
	}

	public void setName(String name)
	{
		this.name = name;
	}

	public Boolean getSex()
	{
		return sex;
	}

	public void setSex(Boolean sex)
	{
		this.sex = sex;
	}

	public String getCellphone()
	{
		return cellphone;
	}

	public void setCellphone(String cellphone)
	{
		this.cellphone = cellphone;
	}

}

在Test.java里面测试

package my;

import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class Test
{
	public static void main(String[] args) throws Exception
	{
		// 创建 SqlSessionFactory
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

		// 获取 Session
		SqlSession session = sqlSessionFactory.openSession();

		// 执行查询
		try
		{
			Student row = session.selectOne("af.test.getStudent", 20190001);
			if (row != null)
				System.out.println(row.id + "," + row.name + "," + row.sex + "," + row.cellphone);
		} finally
		{
			session.close();
		}
		System.out.println("Exit");
	}

}

测试的结果:

测试类的解释(mybatis的使用)

(1) 创建工厂类 SqlSessionFactory

(2) 从工厂中获取会话 SqlSession

- 相当于从c3p0连接池中获取一个Connnection

(3) 在会话中执行查询 session.selectOne()

- 从 mapper里找到相应的配置项 af.test.getStudent

<mapper namespace="af.test">

    <select id="getStudent" resultType="my.Student">

           select * from student where id = #{id}

    </select>

</mapper>

 - 找到相应的SQL语句

select * from student where id = #{id}

 - 替换参数

 select * from student where id = 20190001

 - 查询,并将查询的结果转成 my.Student对象

    <mapper namespace="af.test">

  <select id="getStudent" resultType="my.Student">

        select * from student where id = #{id}

  </select>

</mapper>

其中,resultType指定了转换的类型,使用反射机制即可以完成上述转换。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值