MyBatis 是一款优秀的持久层框架,
它支持定制化 SQL、存储过程以及高级映射。
MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。
MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Ordinary Java Object,普通的 Java对象)映射成数据库中的记录。
根据用户ID查询用户信息
根据用户名查找用户列表
添加用户
修改用户
删除用户
SQL语句
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `orders`
-- ----------------------------
DROP TABLE IF EXISTS `order`;
CREATE TABLE `order` (
`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_order_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 `order` VALUES ('3', '1', '1000010', '2015-02-04 13:22:35', null);
INSERT INTO `order` VALUES ('4', '1', '1000011', '2015-02-03 13:22:41', null);
INSERT INTO `order` 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', '张三', '2019-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);
github下载地址:
https://github.com/mybatis/mybatis-3/releases
<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:3306/mybatis?characterEncoding=utf-8" />
<property name="username" value="root" />
<property name="password" value="root" />
dataSource>
environment>
environments>
configuration>
# 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
package com.itzheng.mybatis.pojo;
import java.util.Date;
public class Order {
private Integer id;
private Integer userId;
private String number;
private Date createtime;
private String note;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number == null ? null : number.trim();
}
public Date getCreatetime() {
return createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note == null ? null : note.trim();
}
@Override
public String toString() {
return "Order [id=" + id + ", userId=" + userId + ", number=" + number + ", createtime=" + createtime
+ ", note=" + note + "]";
}
}
package com.itzheng.mybatis.pojo;
import java.util.Date;
public class User {
private Integer id;
private String username;// 用户姓名
private String sex;// 性别
private Date birthday;// 生日
private String address;// 地址
public Integer getId() {
return id;
}
public void setId(Integer 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;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", sex=" + sex + ", birthday=" + birthday + ", address="
+ address + "]";
}
}
<mapper namespace="user">
mapper>
<mappers>
<mapper resource="mybatis/user.xml" />
mappers>
SELECT id,
username,
birthday,
sex,
address
FROM `user`
WHERE id = 1
<mapper namespace="user">
<select id="getUserByid" parameterType="int" resultType="com.itzheng.mybatis.pojo.User" >
SELECT * FROM USER WHERE id = #{id1}
select>
mapper>
package com.itzheng.mybatis.test;
import java.io.IOException;
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;
import org.junit.Test;
import com.itzheng.mybatis.pojo.User;
public class MybatisTest {
@Test
public void testGetUserById() throws IOException {
// 加载配置文件,创建SqlSessionFactoryBuilder
SqlSessionFactoryBuilder ssfb = new SqlSessionFactoryBuilder();
// 创建核心配置文件的输入流
InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
// 通过输入流创建sqlSessionFactory对象
SqlSessionFactory sqlSessionFactory = ssfb.build(inputStream);
// 创建SqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
// 执行查询,参数一SQL id 参数二,入参
User user = (User) sqlSession.selectOne("user.getUserByid", 1);
//输出查询到的对象
System.out.println(user);
//释放资源
sqlSession.close();
}
}
SELECT id,
username,
birthday,
sex,
address
FROM `user`
WHERE username LIKE '%张%'
<select id="getUserByUserName" parameterType="string" resultType="com.itzheng.mybatis.pojo.User" >
SELECT id,username,birthday,sex,address FROM `user` WHERE username LIKE #{name}
select>
package com.itzheng.mybatis.jdbc.utils;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
/*
* SqlSessionFactory工具类
*/
public class SqlSessionFactoryUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
// 加载配置文件,创建SqlSessionFactoryBuilder
SqlSessionFactoryBuilder ssfb = new SqlSessionFactoryBuilder();
// 创建核心配置文件的输入流
InputStream inputStream;
inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
// 通过输入流创建sqlSessionFactory对象
sqlSessionFactory = ssfb.build(inputStream);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
* 获取sqlSessionFactory
*/
public static SqlSessionFactory getSqlSessionFactory() {
return sqlSessionFactory;
}
}
@Test
public void testGetUserByUserName() {
// 获取sqlSessionFactory
SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
// 创建SqlSession
SqlSession openSession = sqlSessionFactory.openSession();
List<User> selectList = openSession.selectList("user.getUserByUserName", "%张%");
for (User user : selectList) {
System.out.println(user);
}
// 释放资源
openSession.close();
}
${}
:字符串拼接指令,如果入参为普通数据类型{}内部只能写value @Test
public void testGetUserByUserName() {
// 获取sqlSessionFactory
SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
// 创建SqlSession
SqlSession openSession = sqlSessionFactory.openSession();
//List selectList = openSession.selectList("user.getUserByUserName", "%张%");
List<User> selectList = openSession.selectList("user.getUserByUserName", "张");
for (User user : selectList) {
System.out.println(user);
}
// 释放资源
openSession.close();
}
INSERT INTO `user `
(id,
username,
birthday,
sex,
address )
VALUES
('id',
'username',
'birthday',
'sex',
'address' );
<!-- 插入用户 -->
<insert id="insertUser" parameterType="com.itzheng.mybatis.pojo.User">
INSERT INTO USER
(`username`,
`birthday`,
`sex`,
`address`)
VALUES (#{username},
#{birthday},
#{sex},
#{address});
</insert>
@Test
public void testInsertUser() {
// 获取sqlSessionFactory
SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
// 创建SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
User user = new User();
user.setSex("1");
user.setBirthday(new Date());
user.setUsername("张飞");
user.setAddress("四川");
sqlSession.insert("user.insertUser", user);
//提交事务
sqlSession.commit();
// 释放资源
sqlSession.close();
}
@Test
public void testInsertUser() {
// 获取sqlSessionFactory
SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
// 创建SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession(true);// 设置为true自动提交事务
User user = new User();
user.setSex("1");
user.setBirthday(new Date());
user.setUsername("张飞4");
user.setAddress("四川");
sqlSession.insert("user.insertUser", user);
System.out.println(user);// 输出数控影响的行数
// 提交事务
// sqlSession.commit();
// 释放资源
sqlSession.close();
}
<insert id="insertUser" parameterType="com.itzheng.mybatis.pojo.User"
useGeneratedKeys="true" keyProperty="id">
private String uuid2;
public String getUuid2() {
return uuid2;
}
public void setUuid2(String uuid2) {
this.uuid2 = uuid2;
}
@Test
public void testInsertUserUUID() {
// 获取sqlSessionFactory
SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
// 创建SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession(true);// 设置为true自动提交事务
User user = new User();
user.setSex("1");
user.setBirthday(new Date());
user.setUsername("张飞7");
user.setAddress("四川");
sqlSession.insert("user.insertUserUUID", user);
System.out.println(user);// 输出数控影响的行数
// 提交事务
// sqlSession.commit();
// 释放资源
sqlSession.close();
}
<update id="updateUser" parameterType="com.itzheng.mybatis.pojo.User" >
UPDATE `user`
SET
`username` = #{username}
WHERE
`id` = #{id} ;
update>
@Test
public void testUpdateUser() {
// 获取sqlSessionFactory
SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
// 创建SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession(true);// 设置为true自动提交事务
User user = new User();
user.setId(30);
user.setUsername("张角");
sqlSession.insert("user.updateUser", user);
// 提交事务
// sqlSession.commit();
// 释放资源
sqlSession.close();
}
<update id="deleteUser" parameterType="int" >
DELETE `user`
FROM `user`
WHERE `id` = #{id};
update>
@Test
public void testDeleteUser() {
// 获取sqlSessionFactory
SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
// 创建SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession(true);// 设置为true自动提交事务
sqlSession.delete("user.deleteUser", 33);
// 提交事务
// sqlSession.commit();
// 释放资源
sqlSession.close();
}