一、Mybatis是什么?
简而言之,Mybatis,其本质,就是换了一种方式做增删改查。
mybatis-3.2.7.jar,Mybatis 框架最终会被封装一个 jar 包,解压后就是很多类,所谓的框架,其本质就是类。从文件的命名上可以看的出来,Mybatis 是由 apache 这个组织提供的一个技术,原名叫ibatis。
二、实现步骤
1.配置文件
<?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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="org/mybatis/example/BlogMapper.xml"/>
</mappers>
</configuration>
2.映射文件
<?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="org.mybatis.example.BlogMapper">
<select id="selectBlog" parameterType="int" resultType="Blog">
select * from Blog where id = #{id}
</select>
</mapper>
三、具体代码
1. 测试类
package com.mybatis.test;
import java.io.IOException;
import java.io.InputStream;
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.Test;
import com.mybatis.bean.Flower;
/**
1. 用Mybatis做的增删改查
2. @author Lenovo
3. */
public class MybatisCRUD {
//连接数据库
public SqlSession getConnDBByMyBatis() throws IOException {
String resource = "xiangge.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sfbqq = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sfbqq.openSession();
return session;
}
/**
* 增加
* 注意:用Mybatis做增删改时,需要提交事务
* @throws IOException
*/
@Test
public void insertInfoByMyBatis() throws IOException {
SqlSession sessionSunchen = this.getConnDBByMyBatis();
int data = sessionSunchen.insert("com.mybatis.dao.FlowerDao.insertID");
System.out.println("data:"+data);
if(data>0){
sessionSunchen.commit();
System.out.println("增加成功!");
this.selectInfoByMyBatis();
}else{
System.out.println("增加失败!");
sessionSunchen.rollback();
}
}
/**
* 增加,带参数的增加
* alt+/;方法自动补全
* Shift+alt+L:接收对象的返回值
* @throws IOException
*/
@Test
public void insertInfoByParam() throws IOException {
SqlSession sesion = this.getConnDBByMyBatis();
//此处稍后需要修改
Flower flower = new Flower();
flower.setName("教父");
flower.setPrice(1.8f);
flower.setProduction("马龙白兰度");
sesion.insert("com.mybatis.dao.FlowerDao.insertInfoByParam", flower);
sesion.commit();
this.selectInfoByMyBatis();
}
//删除
@Test
public void deleteInfo() throws IOException {
SqlSession session = this.getConnDBByMyBatis();
session.delete("com.mybatis.dao.FlowerDao.deleteInfo");
session.commit();
this.selectInfoByMyBatis();
}
/**
* 删除;带有参数的删除
* @throws IOException
*/
@Test
public void deleteInfoByID() throws IOException {
int id = 17;
SqlSession session = this.getConnDBByMyBatis();
session.delete("com.mybatis.dao.FlowerDao.deleteInfoByID", id);
session.commit();
this.selectInfoByMyBatis();
}
//修改
@Test
public void updateInfo() throws IOException {
SqlSession session = this.getConnDBByMyBatis();
session.update("com.mybatis.dao.FlowerDao.updateInfo");
session.commit();
this.selectInfoByMyBatis();
}
/**
* 修改;带有参数的修改
* @throws IOException
*/
@Test
public void updateInfoByParam() throws IOException {
SqlSession session = this.getConnDBByMyBatis();
Flower flower = new Flower();
flower.setId(5);
flower.setName("火苗");
flower.setPrice(1.5f);
flower.setProduction("格格");
session.update("com.mybatis.dao.FlowerDao.updateInfoByParam", flower);
session.commit();
this.selectInfoByMyBatis();
}
//查询
@Test
public void selectInfoByMyBatis() throws IOException {
//稍后在次数补上查询方法
SqlSession session = this.getConnDBByMyBatis();
List<Object> list = session.selectList("com.mybatis.dao.FlowerDao.selectZCID");
for (Object longge : list) {
System.out.println(longge);
}
session.close();
}
/**
* 查询一条数据
* @throws IOException
*/
@Test
public void selectById() throws IOException {
SqlSession session = this.getConnDBByMyBatis();
int id = 6;
Object obj = session.selectOne("com.mybatis.dao.FlowerDao.selectById", id);
System.out.println(obj);
session.close();
}
}
2.com.mybatis.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.mybatis.dao.FlowerDao">
<!-- 后边就是在这个文件中,补充增删改查对应的sql语句 -->
<!-- 增加 -->
<insert id="insertID">
INSERT INTO flower(`name`,price,production) VALUES('月亮之上','2.5','凤凰传奇');
</insert>
<!-- 增加;带参数的增加;#{}Mybatis中占位符 -->
<insert id="insertInfoByParam" parameterType="com.mybatis.bean.Flower">
INSERT INTO flower(`name`,price,production) VALUES(#{name},#{price},#{production});
</insert>
<!-- 删除 -->
<delete id="deleteInfo">
DELETE FROM flower WHERE id=16
</delete>
<!-- 删除;通过ID删除 -->
<delete id="deleteInfoByID" parameterType="java.lang.Integer">
DELETE FROM flower WHERE id=#{id}
</delete>
<!-- 修改 -->
<update id="updateInfo">
UPDATE flower SET `name`='浪漫樱花',price='1.9',production='郭富城' WHERE id=11
</update>
<!-- 修改;带有参数的修改 -->
<update id="updateInfoByParam" parameterType="com.mybatis.bean.Flower">
UPDATE flower SET `name`=#{name},price=#{price},production=#{production} WHERE id=#{id}
</update>
<!-- 查询 -->
<select id="selectZCID" resultType="com.mybatis.bean.Flower">
SELECT * FROM flower;
</select>
<!-- 查询;用ID编号来查询 -->
<select id="selectById" parameterType="java.lang.Integer" resultType="com.mybatis.bean.Flower">
SELECT * FROM flower WHERE id=#{id}
</select>
</mapper>
3. 配置文件
<?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>
<!-- 配置文件 -->
<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://127.0.0.1:3306/flowerdb6-20"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<!-- 这里需要关联上映射文件 -->
<mapper resource="com/mybatis/dao/FlowerDao.xml"/>
</mappers>
</configuration>
3. com.mybatis.bean(属性文件)
package com.mybatis.bean;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Flower {
private int id;
private String name;
private float price;
private String production;
}
总结
第一步:创建项目并导包
- mybatis-3.2.7.jar:Mybatis 框架的核心包
- mysql-connector-java-5.1.30.jar。MySQL 驱动包,用于连接数据库
- lombok.jar,小辣椒包,用于封装实体类
第二步:创建分层开发需要包+类+方法等
第三步:在 src 文件夹下创建 Mybatis“配置文件”
第四步:在 dao 层中,创建“映射文件”
第五步:在增删改查测试类中用注释搭好架子,增删改查和连接数据库的方法写好。
第六步:开始执行增删改查相关方法
- 用 getConnDBByMyBatis 连接数据库
- 在配置文件中关联上映射文件
- 在映射文件中加上 sql 语句
- 用 session 对象调用相应增删改查方法
- 将返回结果打印到控制台中