mybatis框架简介
mybatis是一个优秀的基于java的持久层框架,它内部封装了jdbc,使开发者只需要关注sql语句本身,而不需要花费精力去处理加载驱动、创建连接、创建statement等繁杂的过程。
mybatis框架的配置
1.创建连接的数据库
#判断存在即删除数据库
drop database if exists mydb;
#创建数据库
create database mydb;
#使用数据库
use mydb;
#创建表
create table t_user
(
uid int primary key auto_increment,
username varchar(20),
password varchar(20),
phone varchar(11),
address varchar(50)
);
insert into t_user(username,password,phone,address) values('张
三','666','18965423548','南阳');
insert into t_user(username,password,phone,address) values('李
四','333','18754263548','许昌');
insert into t_user(username,password,phone,address) values('小
美','123','18565234759','信阳');
select * from t_user;
2.创建一个Java项目在项目中创建一个lib文件夹放入mybatis框架的jar包并导入项目中
3.编写对应的实体类并在src中创建包然后创建user实体类
package com.zhang.bean;
public class User {
private Integer uid;
private String username;
private String password ;
private String phone;
private String address;
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User{" +
"uid=" + uid +
", username='" + username + '\'' +
", password='" + password + '\'' +
", phone='" + phone + '\'' +
", address='" + address + '\'' +
'}';
}
}
4.创建针对表操作的接口类。
public interface UserDao {
/**
* 查询所有用户信息
* @return
*/
List<User> selectAll();
}
5.在接口的包中创建对应的mapper映射配置文件。
<?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 namespace="com.chen.dao.UserDao">
<!--通过select标签进行查询
id:映射接口的方法名
parameterType:指定参数的类型(如果是集合类型只需要指定集合元素的类型即可)
resultType:指定返回值的类型
-->
<select id="selectAll" resultType="com.chen.bean.User">
select * from t_user;
</select>
</mapper>
6..在src目录中创建mybatis框架的核心配置文件。
<?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>
<!--配置环境信息===就是配置连接数据库的参数
default:指定配置的环境信息的id,表示默认连接该环境
-->
<environments default="mysql">
<environment id="mysql">
<!--配置事务的处理方式:模式使用JDBC的事务处理-->
<transactionManager type="jdbc"></transactionManager>
<!--数据源的默认type设置为pooled,表示使用连接池-->
<dataSource type="pooled">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/mydb"/>
<property name="username" value="root"/>
<property name="password" value="123"/>
</dataSource>
</environment>
<environment id="oracle">
<transactionManager type=""></transactionManager>
<dataSource type=""></dataSource>
</environment>
</environments>
<!--加载mapper配置文件-->
<mappers>
<mapper class="com.chen.dao.UserDao" />
</mappers>
7.在测试类中进行测试
package com.zhang.test;
import com.zhang.bean.User;
import com.zhang.dao.UserDao;
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 java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class UserTest {
@Test
public void testSelectAll() throws IOException {
//1.加载核心配置文件的字节输入流
InputStream stream= Resources.getResourceAsStream("mybatis.xml");
//2.创建SqlSessionFactory的构建对象--框架使用的是构建者模式
SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();
//3.通过构建对象加载配置文件的输入流获取SqlSessionFactory
SqlSessionFactory factory=builder.build(stream);
//4.通过工厂对象获取SqlSession对象----执行JDBC操作的
SqlSession sqlSession=factory.openSession();
//5.通过SqlSession对象获取接口对应的代理对象
UserDao userDao=sqlSession.getMapper(UserDao.class);
//6.通过代理对象执行查询方法
List<User> userList=userDao.selectAll();
for (User user:userList) {
System.out.println(user);
}
}
}
运行结果如下: log4j:WARN No appenders could be found for logger (org.apache.ibatis.logging.LogFactory). log4j:WARN Please initialize the log4j system properly. log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info. User{uid=1, username='张三', password='666', phone='18965423548', address='南阳'} User{uid=2, username='李四', password='333', phone='18754263548', address='许昌'} User{uid=3, username='小美', password='123', phone='18565234759', address='信阳'}
8.增删改查
单查
@Test
public void SelectByuid(){
User user=userDao.selectByuid(1);
System.out.println(user);
}
新增
@Test
public void testAdd() {
User user=new User();
user.setUsername("000");
user.setPassword("111");
user.setPhone("222");
user.setAddress("333");
int n= userDao.add(user);
if(n>0){
System.out.println("success");
}else{
System.out.println("error");
}
}
删除
@Test
public void testDelete() {
int n = userDao.delete(5);
if (n > 0) {
System.out.println("success");
} else {
System.out.println("error");
}
}
修改
@Test
public void testUpdate(){
User oldUser=userDao.selectByuid(2);
System.out.println("修改前:"+oldUser);
oldUser.setUsername("小明");
oldUser.setAddress("河南郑州");
userDao.update(oldUser);
User newuser=userDao.selectByuid(2);
System.out.println("修改后:"+newuser);
}