mybatis框架
MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Ordinary Java Object,普通的 Java对象)映射成数据库中的记录。
简单的来说就是:Mybatis是一个实现数据持久化的开源框架,简单理解为就是对JDBC进行封装。开发者只需要关注sql语句本身,而不是去花费精力去处理加载驱动、创建连接、创建statement等繁杂的过程
优点
与JDBC减少了一半以上的代码量
Mybatis是简单的持久化框架,简单,容易学习
相对灵活 sql写在xml中,从程序代码中直接分离,降低耦合,便于管理优化
支持动态sql
提供映射标签 支持对象与数据库中的ORM字段映射
常见的框架
MyBatis
spring MVC
spring
MyBatis入门案例
一.创建数据库
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','18325367826','羊村');
insert into t_user(username,password,phone,address)values('懒羊羊','999','18325367246','羊村');
insert into t_user(username,password,phone,address)values('灰太狼','666','18325361796','狼堡');
select * from t_user;
二.创建一个Java项目在项目中创建一个lib文件夹放入mybatis框架的jar包并导入项目中
三.编写对应的实体类类的首字母大写属性名首字母小写在src中创建com.chen.bean包然后创建user实体类
package com.chen.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 + '\'' +
'}';
}
}
四.创建针对表操作的接口类在src中创建com.chen.dao包,然后创建userDao接口然后在接口中定义针对数据库增删改查的操作
package com.chen.dao;
import com.chen.bean.User;
import java.util.List;
public interface UserDao {
List<User> selectAll();
}
五.在接口的包中创建对应的mapper映射配置文件。在dao接口的同目录下创建跟接口名字一样的配置文件。
<?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">
<mapper namespace="com.yang.dao.UserDao">
<!--通过select标签进行查询
ID:映射接口的方法名
parameterType:指定参数的类型(如果是集合类型只需要指定集合元素的类型即可)
resultType:指定返回值的类型
-->
<select id="selectAll" resultType="com.yang.bean.User">
select * from t_user;
</select>
</mapper>
六.在src目录中创建mybatis框架的核心配置文件。在src中创建一个文件,命名为SqlMapConfig.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>
<!--配置环境信息===就是配置连接数据库的参数
default:指定配置的环境信息的ID,表示默认连接该环境
-->
<environments default="mysql">
<environment id="mysql">
<transactionManager type="jdbc"></transactionManager>
<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="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper class="com.yang.dao.UserDao"></mapper>
</mappers>
</configuration>
7.在测试类中进行测试使用mybatis框架需要按照框架的步骤进行
package com.chen.test;
import com.chen.bean.User;
import com.chen.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='18325367826', address='羊村'}
User{uid=2, username='懒羊羊', password='999', phone='18325367246', address='羊村'}
User{uid=3, username='灰太狼', password='666', phone='18325361796', address='狼堡'}Process finished with exit code 0
八,增删改查全代码
接口类:
package com.chen.dao;
import com.chen.bean.User;
import java.util.List;
public interface UserDao {
//全查
List<User> selectAll();
//添加
int add(User user);
//删除
int del(int uid);
//单查
User selectByUid(int uid);
//修改
int update(User user);
}
<?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">
<mapper namespace="com.chen.dao.UserDao">
<select id="selectAll" resultType="com.chen.bean.User">
select * from t_user;
</select>
<insert id="add" parameterType="com.chen.bean.User">
insert into t_user(username,password,phone,address)values(#{username},#{password},#{phone},#{address});
</insert>
<delete id="del" parameterType="int">
delete from t_user where uid=#{uid};
</delete>
<select id="selectByUid" parameterType="int" resultType="com.chen.bean.User">
select * from t_user where uid=#{uid};
</select>
<update id="update" parameterType="com.chen.bean.User">
update t_user set username=#{username},password=#{password},phone=#{phone},address=#{address} where uid=#{uid};
</update>
</mapper>
测试类:
package com.chen.test;
import com.chen.bean.User;
import com.chen.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.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class UserTest {
InputStream stream=null;
SqlSessionFactoryBuilder builder=null;
SqlSessionFactory factory=null;
SqlSession sqlSession=null;
UserDao userDao=null;
@Before
public void init() throws IOException {
stream= Resources.getResourceAsStream("mybatis.xml");
builder=new SqlSessionFactoryBuilder();
factory= builder.build(stream);
sqlSession=factory.openSession();
userDao=sqlSession.getMapper(UserDao.class);
}
//全查
@Test
public void testSelectAll(){
List<User> userList=userDao.selectAll();
for (User user:userList){
System.out.println(user);
}
}
//添加
@Test
public void testAdd(){
User user=new User();
user.setUsername("小孩");
user.setPassword("666");
user.setPhone("237423904");
user.setAddress("南极洲");
int n=userDao.add(user);
if(n>0){
System.out.println("正确");
}else {
System.out.println("错误");
}
}
//删除
@Test
public void testDel(){
int n=userDao.del(7);
if (n>0){
System.out.println("正确");
}else {
System.out.println("错误");
}
}
//单查
@Test
public void testSelectByUid(){
User user=userDao.selectByUid(2);
System.out.println(user);
}
//修改
@Test
public void testUpdate(){
//数据回显
User oidUser = userDao.selectByUid(8);
System.out.println("修改前"+oidUser);
//根据需要修改字段值
oidUser.setUsername("小朋友");
oidUser.setAddress("阿拉斯加");
//执行数据更新
userDao.update(oidUser);
//再次查询
User newUser = userDao.selectByUid(8);
System.out.println("修改后"+newUser);
}
//关闭资源
@After
public void distroy() throws IOException {
sqlSession.commit();
sqlSession.close();
stream.close();
}
}
多个删除,模糊查询,单个修改
package com.chen.dao;
import com.chen.bean.DelVO;
import com.chen.bean.User;
import java.util.List;
public interface UserDao {
List<User> seach(User user);
int update(User user);
int del(DelVO delVO);
}
<?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">
<mapper namespace="com.chen.dao.UserDao">
<select id="seach" parameterType="user" resultType="User">
select * from t_user
<where>
<if test="username !=null and username !='' ">
and username like concat('%',#{username},'%')
</if>
<if test="address !=null and address !='' ">
and address like concat('%',#{address},'%')
</if>
</where>
</select>
<update id="update" parameterType="user">
update t_user
<set>
<if test="username!=null and username!=''">
username=#{username},
</if>
<if test="password!=null and password!=''">
password=#{password},
</if>
<if test="phone!=null and phone!=''">
phone=#{phone},
</if>
<if test="address!=null and address!=''">
address=#{address},
</if>
</set>
where uid=#{uid}
</update>
<delete id="del" parameterType="delVO">
delete from t_user where uid in
<foreach item="id" collection="ids" open="(" close=")" separator=",">
#{id}
</foreach>
</delete>
</mapper>
package com.chen.test;
import com.chen.bean.DelVO;
import com.chen.bean.User;
import com.chen.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.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class UserTest {
InputStream stream=null;
SqlSessionFactoryBuilder builder=null;
SqlSessionFactory factory=null;
SqlSession sqlSession=null;
UserDao userDao=null;
@Before
public void init() throws IOException {
stream= Resources.getResourceAsStream("mybatis.xml");
builder=new SqlSessionFactoryBuilder();
factory= builder.build(stream);
sqlSession=factory.openSession();
userDao=sqlSession.getMapper(UserDao.class);
}
@Test
public void seachTest(){
User user=new User();
user.setUsername("羊");
user.setAddress("羊村");
List<User> userList = userDao.seach(user);
for (User user1 : userList) {
System.out.println(user1);
}
}
@Test
public void updateTest(){
User user=new User();
user.setUid(5);
user.setUsername("小芬");
user.setPassword("888");
user.setPhone("238878");
user.setAddress("阿拉斯加");
userDao.update(user);
}
@Test
public void delTest(){
List<Integer> ids=new ArrayList<>();
ids.add(1);
ids.add(4);
ids.add(5);
DelVO delVO=new DelVO();
delVO.setUids(ids);
int del=userDao.del(delVO);
}
@After
public void dis() throws IOException {
sqlSession.commit();
sqlSession.close();
stream.close();
}
}