Mybatis之Mybatis入门程序(3)

该系列博客是传智播客Mybatis视频学习笔记,自己有补充。

一、准备环境

1、Mybatis运行环境

从github上下载Mybatis-3.2.3


Lib下:依赖包

Mybatis-3.2.3.jar:Mybatis核心包
Mybatis-3.2.3.pdf:操作指南


2、Mybatis的依赖包:


3、加入mysql的驱动包:


4、执行下面的脚本,生成数据库:

/*
SQLyog v10.2 
MySQL - 5.1.33-community : Database - mybatis
*********************************************************************
*/


/*!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*/`mybatis` /*!40100 DEFAULT CHARACTER SET utf8 */;

USE `mybatis`;

/*Table structure for table `items` */

DROP TABLE IF EXISTS `items`;

CREATE TABLE `items` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `item_name` varchar(32) NOT NULL COMMENT '商品名称',
  `item_price` float(6,1) NOT NULL COMMENT '商品价格',
  `item_detail` text COMMENT '商品描述',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

/*Data for the table `items` */

insert  into `items`(`id`,`item_name`,`item_price`,`item_detail`) values (1,'台式机',3000.0,'该电脑质量非常好!!!!'),(2,'笔记本',6000.0,'笔记本性能好,质量好!!!!!'),(3,'背包',200.0,'名牌背包,容量大质量好!!!!');

/*Table structure for table `orderdetail` */

DROP TABLE IF EXISTS `orderdetail`;

CREATE TABLE `orderdetail` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `orders_id` int(32) DEFAULT NULL COMMENT '订单号',
  `item_id` int(32) DEFAULT NULL COMMENT '商品id',
  `item_num` int(3) DEFAULT NULL COMMENT '商品数量',
  `item_price` float(6,1) DEFAULT NULL COMMENT '商品价格',
  PRIMARY KEY (`id`),
  KEY `FK_orderdetail_1` (`orders_id`),
  KEY `FK_orderdetail_2` (`item_id`),
  CONSTRAINT `FK_orderdetail_1` FOREIGN KEY (`orders_id`) REFERENCES `orders` (`id`),
  CONSTRAINT `FK_orderdetail_2` FOREIGN KEY (`item_id`) REFERENCES `items` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

/*Data for the table `orderdetail` */

insert  into `orderdetail`(`id`,`orders_id`,`item_id`,`item_num`,`item_price`) values (1,1,1,2,3000.0),(2,1,2,1,6000.0),(3,1,3,3,200.0),(4,2,2,2,6000.0);

/*Table structure for table `orders` */

DROP TABLE IF EXISTS `orders`;

CREATE TABLE `orders` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(32) NOT NULL,
  `order_number` varchar(20) NOT NULL COMMENT '订单号',
  PRIMARY KEY (`id`),
  KEY `FK_orders_1` (`user_id`),
  CONSTRAINT `FK_orders_1` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

/*Data for the table `orders` */

insert  into `orders`(`id`,`user_id`,`order_number`) values (1,1,'100001'),(2,1,'100002');

/*Table structure for table `user` */

DROP TABLE IF EXISTS `user`;

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(30) NOT NULL,
  `birthday` date DEFAULT NULL,
  `sex` char(1) DEFAULT NULL,
  `address` varchar(200) DEFAULT NULL COMMENT '地址',
  `detail` text,
  `score` float(4,1) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8;

/*Data for the table `user` */

insert  into `user`(`id`,`username`,`birthday`,`sex`,`address`,`detail`,`score`) values (1,'王五',NULL,'2',NULL,NULL,NULL),(10,'张三','2014-07-10','1','北京市','好同志',99.8),(16,'王六',NULL,NULL,NULL,NULL,NULL);

/*!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 */;
生成的数据表:

5、配置log4j日志信息:

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

注意:开发阶段使用debug模式,生产环境使用info或者error级别。

6、新建SqlMapConfig.xml文件:

最后:工程结构如下:

二、MyBatis入门程序

2.1 需求
根据用户id(主键)查询用户信息
根据用户名称模糊查询用户信息
添加用户
删除用户
更新用户

2.2 配置SqlMapConfig.xml

1、全局配置文件:SqlMapConfig.xml(名称是不固定的)


2、配置的内容包括

①数据库运行环境(和Spring整合后废除了)
②Mapper映射文件

<?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>
	<!-- 和spring整合后 environments配置将废除-->
	<environments default="development">
		<environment id="development">
			<!-- 使用JDBC事务管理,由mybatis控制 -->
			<transactionManager type="JDBC" />
			<!-- 数据库连接池,由mybatis管理 -->
			<dataSource type="POOLED">
				<property name="driver" value="com.mysql.jdbc.Driver" />
				<property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8" />
				<property name="username" value="root" />
				<property name="password" value="root" />
			</dataSource>
		</environment>
	</environments>
	
</configuration>

三、开发过程

3.1 创建PO类
创建User表对应的PO,属性名与数据库表中的字段一致,并且需要提供getter和setter方法。

package cn.sunft.mybatis.po;

import java.util.Date;

/**
 * 用户po
 */
public class User {
	// 属性名和数据库表的字段对应
	private int id;
	private String username;// 用户姓名
	private String sex; // 性别
	private Date birthday; // 生日
	private String address; // 地址

	public int getId() {
		return id;
	}

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

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getSex() {
		return sex;
	}

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

	public Date getBirthday() {
		return birthday;
	}

	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

}

3.2 创建映射文件

User.xml,mapper代理开发映射文件名称叫xxxMapper.xml,比如:UserMapper.xml、ItemsMapper.xml在映射文件中配置sql语句。

<?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">

<!-- namwspace命名空间:作用就是对SQL进行分类管理,进行SQL隔离 -->
<!-- namespace命名空间特殊作用:
如果使用mapper动态代理方法,这里就需要配置mapper接口地址-->
<mapper namespace="test">
	
	<!-- 在映射文件中配置很多sql语句 -->
	<!-- 需求:通过id查询用户表的记录 -->
	<!-- 通过select执行数据库查询
	id:标识映射文件中的sql
	将sql语句封装到mappedStatement对象中,所以将id成为statement的id
	parameterType:指定输入参数的类型,这里指定int型
	#{}表示一个占位符
	#{id}:其中的id表示接收输入的参数,参数名称就是id,如果输入参数是简单类型,
	#{}中的参数名可以任意,可以是value或其他名称
	resultType:指定SQL输出结果所映射的java对象类型,select指定resultType表示
	将单条记录映射成的java对象
	 -->
	 <select id="findUserById" parameterType="int" 
	 	resultType="cn.sunft.mybatis.po.User">
	 	select * from user where id=#{id}
	 </select>
	
</mapper>

3.3 在SqlMapConfig.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>
	<!-- 和spring整合后 environments配置将废除-->
	<environments default="development">
		<environment id="development">
			<!-- 使用JDBC事务管理,由mybatis控制 -->
			<transactionManager type="JDBC" />
			<!-- 数据库连接池,由mybatis管理 -->
			<dataSource type="POOLED">
				<property name="driver" value="com.mysql.jdbc.Driver" />
				<property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8" />
				<property name="username" value="root" />
				<property name="password" value="root" />
			</dataSource>
		</environment>
	</environments>
	
	<!-- 加载映射文件,只能写类路径名,不能带上应用名,否则会报错 -->
	<mappers>
		<mapper resource="sqlmap/User.xml" />
	</mappers>
	
</configuration>

3.4 编写查询测试类

package cn.sunft.mybatis.first;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import cn.sunft.mybatis.po.User;

/**
 * Mybatis入门程序
 */
public class MybatisFirst {

	/**
	 * 根据id查询用户信息
	 * @throws IOException 
	 */
	@Test
	public void findUserByIdTest() throws IOException{
		//mybatis配置文件
		String resource = "SqlMapConfig.xml";
		//得到配置文件,这种方式与路径耦合
		//InputStream inStream = Resources.getResourceAsStream(resource);
		//与路径解耦
		InputStream inStream = this.getClass()
				.getClassLoader().getResourceAsStream(resource);
		
		//创建会话工厂
		SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
		SqlSessionFactory factory = builder.build(inStream);//创建工厂
		
		//通过工厂得到SqlSession
		SqlSession sqlSession = factory.openSession();
		
		//通过SqlSession操作数据库
		//第一个参数:映射文件中statement的id,等于namespace+"."+statement的id
		//第二个参数:指定和映射文件中所匹配的parameterType类型的输入参数
		//sqlSession.selectOne结果是与映射文件中所匹配的resultType类型的对象
		//该方法是泛型方法,不用强转
		User user = sqlSession.selectOne("test.findUserById", 1);
		System.out.println(user);
		//释放资源
		sqlSession.close();
	}
	
}
运行结果
cn.sunft.mybatis.po.User@3224f60b







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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值