MyBatis 本是apache的一个开源项目iBatis
2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis
2013年11月迁移到Github
MyBatis是一个优秀的持久层框架,它对jdbc的操作数据库的过程进行封装
Mybatis通过xml或注解的方式进行开发
package com.itheima.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JDBCTest {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
// 加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");
// 通过驱动管理类获取数据库链接
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8",
"root", "root");
// 定义sql语句 ?表示占位符
String sql = "select * from user where username = ?";
// 获取预处理statement
preparedStatement = connection.prepareStatement(sql);
// 设置参数,第一个参数为sql语句中参数的序号(从1开始),第二个参数为设置的参数值
preparedStatement.setString(1, "王五");
// 向数据库发出sql执行查询,查询出结果集
resultSet = preparedStatement.executeQuery();
// 遍历查询结果集
while (resultSet.next()) {
System.out.println(resultSet.getString("id") + " " + resultSet.getString("username"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 释放资源
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
https://github.com/mybatis/mybatis-3/releases
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '用户ID',
`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=28 DEFAULT CHARSET=utf8;
CREATE TABLE `orders` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '订单id',
`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;
在工程下创建一个资源文件夹,名字为config,创建核心配置文件SqlMapConfig.xml
log4j.properties
# 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.itheima.pojo;
import java.io.Serializable;
import java.util.Date;
public class User implements Serializable {
private static final long serialVersionUID = 1L;
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 + "]";
}
}
SELECT LAST_INSERT_ID()
insert into user(username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address})
update user set username = #{username} where id=#{id}
delete from user where id=#{id}
package com.itheima.test;
import static org.junit.Assert.*;
import java.io.InputStream;
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 org.junit.Before;
import org.junit.Test;
import com.itheima.pojo.User;
public class MybatisTest {
private SqlSessionFactory sqlSessionFactory;
@Before
public void init() throws Exception {
String resource = "SqlMapConfig.xml";
//读取配置文件
InputStream inputStream = Resources.getResourceAsStream(resource);
//创建工厂
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
@Test
public void selelctUserById() throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession();
//参数说明:1.指定要执行的sql语句,2.SQL语句中的占位符
User user = sqlSession.selectOne("test.selectUserById", 10);
System.err.println(user);
sqlSession.close();
}
@Test
public void selectUserByUsername() throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession();
//参数说明:1.指定要执行的sql语句,2.SQL语句中的占位符
List list = sqlSession.selectList("test.selectUserByUsername", "小");
for (User user : list) {
System.err.println(user);
}
sqlSession.close();
}
@Test
public void saveUser() throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession();
User user = new User();
user.setUsername("边江");
user.setSex("1");
user.setBirthday(new Date());
user.setAddress("北京");
sqlSession.insert("test.saveUser",user);
sqlSession.commit();
sqlSession.close();
}
@Test
public void updateUserById() throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession();
User user = new User();
user.setId(26);
user.setUsername("阿杰");
user.setSex("1");
user.setBirthday(new Date());
user.setAddress("北京");
sqlSession.insert("test.updateUserById",user);
sqlSession.commit();
sqlSession.close();
}
@Test
public void deleteUserById() throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession();
sqlSession.delete("test.deleteUserById",26);
sqlSession.commit();
sqlSession.close();
}
}