一、MyBatis简介
1.1、概述
MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架。
MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。
MyBatis 可以对配置和原生Map使用简单的 xml 或注解,将接口和 java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
1.2、ORM
orm工具的基本思想
无论是用过的hibernate,mybatis,你都可以法相他们有一个共同点:
1. 从配置文件(通常是XML配置文件中)得到 sessionfactory.
2. 由sessionfactory 产生 session
3. 在session 中完成对数据的增删改查和事务提交等.
4. 在用完之后关闭session 。
5. 在java 对象和 数据库之间有做mapping 的配置文件,也通常是xml 文件。
二、环境搭建
2.1、所需要Jar包
要使用 MyBatis, 只需将 mybatis-x.x.x.jar 文件置于 classpath 中即可。
2.2、建立数据库与插入数据
这里使用MySQL数据库:
CREATE TABLE `mybatis`.`user` ( `id` INT(11) NOT NULL AUTO_INCREMENT COMMENT '用户ID', `name` VARCHAR(45) NOT NULL DEFAULT '无名氏' COMMENT '用户名', `age` TINYINT(3) NOT NULL DEFAULT 21 COMMENT '用户年龄', `birthday` DATETIME NOT NULL DEFAULT '1970-01-01 00:00:00' COMMENT '用户生日', `address` VARCHAR(256) NOT NULL DEFAULT '北京' COMMENT '用户地址', PRIMARY KEY (`id`) COMMENT '') COMMENT = '用户表';
insert into user(id,name,age,birthday,address)values(1,'张三',23,'1990-01-23 20:24:21','上海'),(2,'李四',18,'1986-12-23 12:13:11','广州'),(3,'
2.3、建立Web项目把Jar包引入项目
三、建立配置文件,实体类,与接口
3.1、建立实体类
/** * @Title: User.java
* @Package com.pb.mybatis.po
* @Description: TODO(用户类)
* @author 刘楠
* @date 2015-10-26 下午5:42:13
* @version V1.0
*/package com.pb.mybatis.po;import java.util.Date;/**
* @ClassName: User
* @Description: TODO(用户类)
* @author 刘楠
* @date 2015-10-26 下午5:42:13
* */public class User {
/**
* id(用户ID) */
private int id; /**
* name(用户名) */
private String name; /**
*age (用户年龄) */
private int age; /**
* birthday(用户生日) */
private Date birthday; /**
* address (用户地址) */
private String address; /**
* @return the id */
public int getId() { return id;
} /**
* @param id the id to set */
public void setId(int id) { this.id = id;
} /**
* @return the name */
public String getName() { return name;
} /**
* @param name the name to set */
public void setName(String name) { this.name = name;
} /**
* @return the age */
public int getAge() { return age;
} /**
* @param age the age to set */
public void setAge(int age) { this.age = age;
} /**
* @return the brithday */
public Date getBirthday() { return brithday;
} /**
* @param brithday the brithday to set */
public void setBirthday(Date birthday) { this.birthday = birthday;
} /**
* @return the address */
public String getAddress() { return address;
} /**
* @param address the address to set */
public void setAddress(String address) { this.address = address;
}
}
3.2、写实体类接口
/** * @Title: UserMapper.java
* @Package com.pb.mybatis.dao
* @Description: TODO(用一句话描述该文件做什么)
* @author 刘楠
* @date 2015-10-26 下午5:45:13
* @version V1.0
*/package com.pb.mybatis.dao;import com.pb.mybatis.po.User;/**
* @ClassName: UserMapper
* @Description: TODO(用户类数据访问接口)
* @author 刘楠
* @date 2015-10-26 下午5:45:13
* */public interface UserMapper { /**
*
* @Title: selectUserById
* @Description: TODO(根据用户ID查询)
* @param id
* @return User */
public User selectUserById(int id);
}
3.3、与db.properties
db.properties
#数据库基本配置
#驱动
driver=com.mysql.jdbc.Driver
#连接url
url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf8#用户名
username=root
#密码
passWord=root
3.4、建立映射文件与configuration.xml配置
UserMapper.xml
44268761adfa814cf615c226dea7943903dfc2bf31bc63834207984f4dc7cfa1
b57c223193025f175c59c6e443d054f9c7e24c51d7c312f2f68b23b5d6ab376ca2922858667b44302f5f44c40464f8e10d808b2c0c1a3b4e1cd54772049288b5select * from user
where id=#{id}18bb6ffaf0152bbe49cd8a3620346341c0b08e356654e8ca9da308b068748e7b
configuration.xml
44268761adfa814cf615c226dea794391b2d3380e222cd45190c394123b6bc32be7fee14d1861eb5f4b10d3c0e731574f9d9f4a8f32d97f3ef0c10742ed31240fe1da682cb1a6613a7e4fa8f80a418b6851d7b4e524c355470590e312b212f24e8ba38100e87047ce1623d116f5d64ede7cfaa88c5d3ee26d5b3494efa45a73858237243e8ecf42c8becf7249a861e4ddf2384d671d95e90b2cdd9f4aad0f3d954b96610c9979ee50f6ca4824c1131234fed10cd7cf881b9ae306dcec0ee515820a0c3ea064a1de1ea5023dc8be28a88feec7b07c029d4853673dd8dd698dca2a4c26ceb89f42767f32dc04d774b1b4847ec3018e815732324157b1a74ae70c60ca08677dbe5285d8db4d4ba4d17c4dd4ee426ccc8790b185055105c243b1c3f67ada753a06f9296b64d2e0e24b22ceac99c25a19e2b78abf797cdba6fcfc914d15eb7229fcb3ee3398b61a41934bab7057950e86b81b87b31d408c1f841fee31c6a0b0cba36824e074e3d9e369b2e45c7adc8b5a1b27fe5111bb8d60c6e21031317df7cd2b9a25783a5b8d3038c1deeeb50fe019e6ad981d370567c0679aebc5810cea030320761e58c9dcc8103f1c4ff172655b900e06efff9ee4818d319884b1b9d85fe86862ae3eab7e2045cf8a0
3.5、简单根据ID查询
/** * @Title: Test1.java
* @Package com.pb.mybatis.test
* @Description: TODO(用一句话描述该文件做什么)
* @author 刘楠
* @date 2015-10-26 下午5:55:54
* @version V1.0
*/package com.pb.mybatis.test;import java.io.IOException;import java.io.Reader;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 com.pb.mybatis.dao.UserMapper;import com.pb.mybatis.po.User;/**
* @ClassName: Test1
* @Description: TODO(测试类)
* @author 刘楠
* @date 2015-10-26 下午5:55:54
* */public class Test1 { //Session工厂
static SqlSessionFactory sqlSessionFactory=null; //Session
static SqlSession session=null; //字符流
static Reader reader=null;
public static void main(String[] args) {
selectById();
} /**
*
* @Title: selectById
* @Description: TODO(根据ID查找用户)
void */
public static void selectById(){ //加载配置文件
try {
reader=Resources.getResourceAsReader("configuration.xml"); //建立SqlSessionFactory
sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader); //打开Session
session=sqlSessionFactory.openSession(); //获取用户接口对象
UserMapper userMapper=session.getMapper(UserMapper.class); //调用查询方法
User user=userMapper.selectUserById(1);
System.out.println(user.getName()+"..."+user.getAge()+"..."+user.getBirthday().toLocaleString()+"..."+user.getAddress());
} catch (IOException e) {
e.printStackTrace();
}
}
}
3.6、使用别名
60b9aab1f9b42079b96ac82dd8be72939542a02f6b273f92cc32f0b46d9d2305baba2e6a192d8bfc23516a84f4f7cec1296e3c4a3a359c4903552031cb8751fac9ec9bdd3e96496d6fb40ca4d76d0dbe
更改mapper.xml中的User类的路径 为别名
44268761adfa814cf615c226dea7943903dfc2bf31bc63834207984f4dc7cfa1
b57c223193025f175c59c6e443d054f9c7e24c51d7c312f2f68b23b5d6ab376ca2922858667b44302f5f44c40464f8e1411752817331a0a3e0302f23d1e9f3beselect * from user
where id=#{id}18bb6ffaf0152bbe49cd8a3620346341c0b08e356654e8ca9da308b068748e7b
测试类不变
3.7、使用resultMap
在mapper.xml中使用resultMap
44268761adfa814cf615c226dea7943903dfc2bf31bc63834207984f4dc7cfa1
b57c223193025f175c59c6e443d054f9c7e24c51d7c312f2f68b23b5d6ab376c27883b2a06054b92c18a59cffac08a871ad2e25f946a38e60033e3e705183a3ea1e864921f0b0d4e296b20880c35c8e0fc8fbdd715bbd0a1e0af1335033ca5600b84badccc7e8e2f814cf4d6fff5bfa0137ed6d5dfe81c41de3e7b71b27de132fac377315e777fcca3940e312a1f848375ae2d9249e36032d0ddd1bec458d4149f2d83780345992f55716e21d71a02c80de62db9b5fee1287d03606d63f668ff23f593aba86c611336605bcecfd917c35041d2f4a1b20582b830ae5023065bce6ebaf93ccf0a7eb73abf17f5d66f496dfee232fc7765272c3bbda181a2930f1df7e5548df63e583db062731c7dc81883select * from user
where id=#{id}18bb6ffaf0152bbe49cd8a3620346341c0b08e356654e8ca9da308b068748e7b
测试类不变
四、实现基本的增、删、改、查
4.1、在接口中增加,模糊查询,添加,修改,删除的方法,
/** * @Title: UserMapper.java
* @Package com.pb.mybatis.dao
* @Description: TODO(用一句话描述该文件做什么)
* @author 刘楠
* @date 2015-10-26 下午5:45:13
* @version V1.0
*/package com.pb.mybatis.dao;import java.util.Date;import java.util.List;import com.pb.mybatis.po.User;/**
* @ClassName: UserMapper
* @Description: TODO(用户类数据访问接口)
* @author 刘楠
* @date 2015-10-26 下午5:45:13
* */public interface UserMapper { /**
*
* @Title: selectUserById
* @Description: TODO(根据用户ID查询)
* @param id
* @return User */
public User selectUserById(int id); /**
*
* @Title: selectUserLikeName
* @Description: TODO(根据姓名模糊查询)
* @param name
* @return List4c8e0c17c3bd7e0081bb17cc795e1984 */
public List4c8e0c17c3bd7e0081bb17cc795e1984 selectUserLikeName(String name);
/**
*
* @Title: addUser
* @Description: TODO(添加用户)
* @param user void */
public void addUser(User user); /**
*
* @Title: updateUser
* @Description: TODO(修改用户)
* @param user void */
public void updateUser(User user); /**
*
* @Title: deleteUser
* @Description: TODO(删除用户)
* @param id void */
public void deleteUser(int id);
}
4.2、在mapper.xml中增加相应的映射
44268761adfa814cf615c226dea7943903dfc2bf31bc63834207984f4dc7cfa1
b57c223193025f175c59c6e443d054f9c7e24c51d7c312f2f68b23b5d6ab376c27883b2a06054b92c18a59cffac08a871ad2e25f946a38e60033e3e705183a3ea1e864921f0b0d4e296b20880c35c8e0fc8fbdd715bbd0a1e0af1335033ca5600b84badccc7e8e2f814cf4d6fff5bfa0137ed6d5dfe81c41de3e7b71b27de132fac377315e777fcca3940e312a1f848375ae2d9249e36032d0ddd1bec458d4149f2d83780345992f55716e21d71a02c80de62db9b5fee1287d03606d63f668ff23f593aba86c611336605bcecfd917c35041d2f4a1b20582b830ae5023065bce6ebaf93ccf0a7eb73abf17f5d66f496dfee232fc7765272c3bbda181a2930f1df7e5548df63e583db062731c7dc81883select * from user
where id=#{id}18bb6ffaf0152bbe49cd8a3620346341b5212d0755debde6974bf807a27dcc1a7872f7f6051b1785ceee16974bf7ea43select * from user
where name like "%"#{name}"%"18bb6ffaf0152bbe49cd8a362034634169ae0a557f14ac7b43b9bde11e501d90dc5f159b08e3163a1d7a5a704e80fcaainsert into user(name,age,birthday,address)
values(#{name},#{age},#{birthday},#{address})76f304ec0e9635871afd8698a75569ba3d9e8b13e6b88571c189cfee94cf4b8c4b6736444a9bbe84d5478162ef7afd12update user set name=#{name},age=#{age},birthday=#{birthday},address=#{address}
where id=#{id}e86b183cd12ef6bc144b0989d29dea3f3ca33cf1ff4565f03e06de2e9e9ddea51cf0a0ddb3bde6216af80545449e87a6delete from user
where id=#{id}d42c0d2214b1fae41f8b299c27bd4e97c0b08e356654e8ca9da308b068748e7b
4.3、测试类
/**
* @Title: Test1.java
* @Package com.pb.mybatis.test
* @Description: TODO(用一句话描述该文件做什么)
* @author 刘楠
* @date 2015-10-26 下午5:55:54
* @version V1.0
*/package com.pb.mybatis.test;import java.io.IOException;import java.io.Reader;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;import java.util.List;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 com.pb.mybatis.dao.UserMapper;import com.pb.mybatis.po.User;/**
* @ClassName: Test1
*
* @Description: TODO(测试类)
*
* @author 刘楠
*
* @date 2015-10-26 下午5:55:54
*
*
*/public class Test1 { // Session工厂
static SqlSessionFactory sqlSessionFactory = null; // Session
static SqlSession session = null; // 字符流
static Reader reader = null; public static void main(String[] args) {
} /**
*
* @Title: selectById
*
* @Description: TODO(根据ID查找用户) void */
public static void selectById() { // 加载配置文件
try {
reader = Resources.getResourceAsReader("configuration.xml"); // 建立SqlSessionFactory
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); // 打开Session
session = sqlSessionFactory.openSession(); // 获取用户接口对象
UserMapper userMapper = session.getMapper(UserMapper.class); // 调用查询方法
User user = userMapper.selectUserById(1);
System.out.println(user.getName() + "..." + user.getAge() + "..."
+ user.getBirthday().toLocaleString() + "..."
+ user.getAddress());
} catch (IOException e) {
e.printStackTrace();
}
} /**
*
* @Title: selectLikeName
*
* @Description: TODO(根据用户名模糊查询) void */
public static void selectLikeName() { // 加载配置文件
try {
reader = Resources.getResourceAsReader("configuration.xml"); // 建立SqlSessionFactory
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); // 打开Session
session = sqlSessionFactory.openSession(); // 获取用户接口对象
UserMapper userMapper = session.getMapper(UserMapper.class); // 调用查询方法
List4c8e0c17c3bd7e0081bb17cc795e1984 users = userMapper.selectUserLikeName("张"); for (User user : users) {
System.out.println(user.getName() + "..." + user.getAge() + "..." + user.getBirthday().toLocaleString() + "..."
+ user.getAddress());
}
} catch (IOException e) {
e.printStackTrace();
}
} /**
*
* @Title: addUser
* @Description: TODO(添加用户)
void */
public static void addUser() { // 加载配置文件
try {
reader = Resources.getResourceAsReader("configuration.xml"); // 建立SqlSessionFactory
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); // 打开Session
session = sqlSessionFactory.openSession(); // 获取用户接口对象
UserMapper userMapper = session.getMapper(UserMapper.class); // 声明新用户
User user =new User();
user.setName("呵呵");
user.setAge(22);
String d="1984-09-23 20:23:22";
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-DD HH:mm:ss");
Date date=sdf.parse(d);
user.setBirthday(date);
user.setAddress("不知道是哪的");
userMapper.addUser(user);
System.out.println("插入后的ID"+user.getId()); //提交事务 session.commit();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace();
}
} /**
*
* @Title: updateUser
* @Description: TODO(修改用户)
void */
public static void updateUser() { // 加载配置文件
try {
reader = Resources.getResourceAsReader("configuration.xml"); // 建立SqlSessionFactory
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); // 打开Session
session = sqlSessionFactory.openSession(); // 获取用户接口对象
UserMapper userMapper = session.getMapper(UserMapper.class); // 调用查询方法
User user = userMapper.selectUserById(6);
user.setName("想起 来叫什么了");
user.setAddress("魔都上海"); //更新 userMapper.updateUser(user); //提交事务 session.commit();
} catch (IOException e) {
e.printStackTrace();
}
} public static void detleUser() { // 加载配置文件
try {
reader = Resources.getResourceAsReader("configuration.xml"); // 建立SqlSessionFactory
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); // 打开Session
session = sqlSessionFactory.openSession(); // 获取用户接口对象
UserMapper userMapper = session.getMapper(UserMapper.class);
//删除
userMapper.deleteUser(6); //提交事务 session.commit();
} catch (IOException e) {
e.printStackTrace();
}
}
以上就是MyBatis入门(一)---基本使用的内容,更多相关内容请关注PHP中文网(www.php.cn)!