MyBatis入门(案例一)
mybaitis_demo001
│ pom.xml
│
└─src
├─main
│ ├─java
│ │ └─com
│ │ └─lifeibai
│ │ └─po
│ │ User.java----实体类
│ │
│ └─resources
│ db.properties----数据库连接配置
│ log4j.properties----日志(可以没有)
│ mybatis-conf.xml----mybatis核心配置文件
│ mybatis.sql----数据库文件
│ User.xml----映射文件
│
└─test
└─java
└─com
└─lifeibai
└─test
MyTest.java----测试文件
sql数据库数据 mybatis.sql
/*
Navicat MySQL Data Transfer
Source Server : localhost_3306
Source Server Version : 50521
Source Host : localhost:3306
Source Database : mybatis
Target Server Type : MYSQL
Target Server Version : 50521
File Encoding : 65001
Date: 2015-04-09 16:03:53
*/
create database mybatis_db;
use mybatis_db;
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `orders`
-- ----------------------------
DROP TABLE IF EXISTS `orders`;
CREATE TABLE `orders` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL COMMENT '下单用户id',
`number` varchar(32) NOT NULL COMMENT '订单号',
`createtime` datetime NOT NULL COMMENT '创建订单时间',
`note` varchar(100) DEFAULT NULL COMMENT '备注',
PRIMARY KEY (`id`),
KEY `FK_orders_1` (`user_id`),
CONSTRAINT `FK_orders_id` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of orders
-- ----------------------------
INSERT INTO `orders` VALUES ('3', '1', '1000010', '2015-02-04 13:22:35', null);
INSERT INTO `orders` VALUES ('4', '1', '1000011', '2015-02-03 13:22:41', null);
INSERT INTO `orders` VALUES ('5', '10', '1000012', '2015-02-12 16:13:23', null);
-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(32) NOT NULL COMMENT '用户名称',
`birthday` date DEFAULT NULL COMMENT '生日',
`sex` char(1) DEFAULT NULL COMMENT '性别',
`address` varchar(256) DEFAULT NULL COMMENT '地址',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', '王五', null, '2', null);
INSERT INTO `user` VALUES ('10', '张三', '2014-07-10', '1', '北京市');
INSERT INTO `user` VALUES ('16', '张小明', null, '1', '河南郑州');
INSERT INTO `user` VALUES ('22', '陈小明', null, '1', '河南郑州');
INSERT INTO `user` VALUES ('24', '张三丰', null, '1', '河南郑州');
INSERT INTO `user` VALUES ('25', '陈小明', null, '1', '河南郑州');
INSERT INTO `user` VALUES ('26', '王五', null, null, null);
pom.xml
?xml version="1.0" encoding="UTF-8"?
project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
modelVersion4.0.0/modelVersion
groupIdcom.lifeibai.mybatis/groupId
artifactIdmybaitis_demo003/artifactId
version1.0-SNAPSHOT/version
build
plugins
plugin
groupIdorg.apache.maven.plugins/groupId
artifactIdmaven-compiler-plugin/artifactId
version3.5.1/version
configuration
source1.8/source
target1.8/target
/configuration
/plugin
/plugins
/build
dependencies
!--数据库库驱动--
dependency
groupIdmysql/groupId
artifactIdmysql-connector-java/artifactId
version5.1.6/version
/dependency
!--junit测试--
dependency
groupIdjunit/groupId
artifactIdjunit/artifactId
versionRELEASE/version
/dependency
!--Mybatis--
dependency
groupIdorg.mybatis/groupId
artifactIdmybatis/artifactId
version3.4.5/version
/dependency
!--日志--
dependency
groupIdlog4j/groupId
artifactIdlog4j/artifactId
version1.2.17/version
/dependency
/dependencies
/project
com.lifeibai.po.User.java
public class User {
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
.....
}
db.properties
!--jdbc连接数据库配置信息--
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis_db?characterEncoding=utf-8
jdbc.username=root
jdbc.password=root
mybatis-conf.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
!-- 配置属性 再加载外部属性,如果有同名属性会覆盖 --
properties resource="db.properties"/
!-- 和spring整合后 environments配置将废除--
environments default="development"
environment id="development"
!-- 使用jdbc事务管理--
transactionManager type="JDBC" /
!-- 数据库连接池--
dataSource type="POOLED"
property name="driver" value="${jdbc.driver}" /
property name="url" value="${jdbc.url}" /
property name="username" value="${jdbc.username}" /
property name="password" value="${jdbc.password}" /
/dataSource
/environment
/environments
!-- 加载mapper文件 --
mappers
!-- resource基于classpath查找 --
mapper resource="User.xml"/
/mappers
/configuration
User.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"
!--namespace:使用mapper resource="User.xml"/ 时这个别名可以随便起,用来找到对应的sql操作--
mapper namespace="test"
select id="findUserById" parameterType="int" resultType="com.lifeibai.po.User"
select * from user where id = #{id}
/select
select id="findUserByUsername" parameterType="java.lang.String"
resultType="com.lifeibai.po.User"
select * from user where username like '%${value}%'
/select
insert id="insert" parameterType="com.lifeibai.po.User"
selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer"
select LAST_INSERT_ID()
/selectKey
INSERT INTO mybatis_db.user (username, birthday, sex, address)
VALUES (#{username}, #{birthday}, #{sex}, #{address});
/insert
update id="update" parameterType="com.lifeibai.po.User"
UPDATE mybatis_db.user
SET username = #{username}, birthday = #{birthday}, sex = #{sex}, address = #{address}
WHERE id = #{id};
/update
delete id="delete" parameterType="int"
delete from mybatis_db.user where id = #{id}
/delete
/mapper
测试代码MyTest.java
package com.lifeibai.test;
import com.lifeibai.po.User;
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.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.List;
public class MyTest {
/*
*//**
* TODO JDBC链接
* 传统方式开发
*/
@Test
public void test01() throws Exception{
//加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");
//通过驱动管理类获取数据库链接
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis_db?characterEncoding=utf-8" , "root" , "root");
//得到执行者
String sql = "select * from user";
PreparedStatement preparedStatement = con.prepareStatement(sql);
//执行语句,得到resultSet
ResultSet resultSet = preparedStatement.executeQuery();
ResultSetMetaData metaData = resultSet.getMetaData();
//遍历resultSet
while (resultSet.next()){
for (int i = 1; i = metaData.getColumnCount(); i++) {
System.out.print(resultSet.getObject(i)+"t");
}
System.out.println();
}
//关闭资源
resultSet.close();
preparedStatement.close();
con.close();
}
/*===================================================================================*/
/*使用Mybatis 开发*/
private SqlSessionFactory sqlSessionFactory;
@Before
public void conf() throws IOException{
String resource = "mybatis-conf.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
/**
* TODO MyBatis --selectOne
*/
@Test
public void test02(){
SqlSession session = sqlSessionFactory.openSession();
User user = session.selectOne("findUserById" , 1);
System.out.println(user);
}
/**
* TODO MyBatis -- 模糊查询
*/
@Test
public void test03(){
SqlSession session = sqlSessionFactory.openSession();
ListUser list = session.selectList("test.findUserByUsername" , "张三");
System.out.println(list);
}
/**
* TODO 添加
*/
@Test
public void test04(){
SqlSession session = sqlSessionFactory.openSession();
User user = new User();
user.setUsername("王二小");
user.setAddress("河南");
int i = session.insert("test.insert" , user);
session.commit();
System.out.println(i);
}
/**
* TODO 修改
*/
@Test
public void test05(){
/*错误提示:Column 'username' cannot be null*/
SqlSession session = sqlSessionFactory.openSession();
User user = new User();
user.setId(28);
user.setUsername("大牛");
user.setAddress("北京");
int i = session.update("test.update" , user);
session.commit();
System.out.println(i);
}
}
文章如有错误,请您一定指出,感谢之至!
如果你有不同的见解,欢迎留言,或者加我QQ986320270
图片可能来源于网络,如有侵权请告知。
最后:关注一下呗
长按二维码识别关注