1Mybatis是什么?
MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis,实质上Mybatis对ibatis进行一些改进。
MyBatis是半ORM框架.
MyBatis是一个优秀的持久层框架,它对jdbc的操作数据库的过程进行封装,使开发者只需要关注 SQL 本身,而不需要花费精力去处理例如注册驱动、创建connection、创建statement、手动设置参数、结果集检索等jdbc繁杂的过程代码。
Mybatis通过xml或注解的方式将要执行的各种statement(statement、preparedStatemnt、CallableStatement)配置起来,并通过java对象和statement中的sql进行映射生成最终执行的sql语句,最后由mybatis框架执行sql并将结果映射成java对象并返回。
Mybatis框架执行流程图
那接下来我们就该开始使用Mybatis框架了:
1.创建数据库,并且添加数据:
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
`age` int(20) DEFAULT NULL,
`sex` varchar(11) DEFAULT NULL,
`username` varchar(60) DEFAULT NULL,
`password` varchar(60) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', '张三丰', '-1', '男', '张三', '123');
INSERT INTO `user` VALUES ('2', '超级玛丽', '75', '男', '李四', '123');
INSERT INTO `user` VALUES ('3', '苏曼', '45', '女', '肖大炮', '123');
INSERT INTO `user` VALUES ('4', '苏雁妮', '44', '男', '赵六', '123');
INSERT INTO `user` VALUES ('5', '赵二狗', '11', '女', '田七', '123');
INSERT INTO `user` VALUES ('6', '格格', '55', '男', '孙八', '123');
INSERT INTO `user` VALUES ('7', '赵铁柱', '12', '男', '曹子怡', '123');
INSERT INTO `user` VALUES ('8', '赵铁柱', '12', '男', '苏艳妮', '123');
INSERT INTO `user` VALUES ('12', '郑子轩', '20', '男', '郑子轩', '123');
INSERT INTO `user` VALUES ('13', '马六', '45', '男', '马六', '123');
INSERT INTO `user` VALUES ('14', '哈哈哈', '0', '男', '哈哈哈', '123');
2.导入Mybatis框架的核心jar包:
3.配置db.properties文件:
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/dog
jdbc.username=root
jdbc.password=123456```
```q
4.配置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>
<!--加载配置文件-->
<properties resource="db.properties"></properties>
<!--添加缓存-->
<settings>
<setting name="cacheEnabled" value="true"/>
</settings>
<!--类型别名-->
<typeAliases>
<!--每个单独的类取别名-->
<!--<typeAlias type=""alias=""/>-->
<!--给包下的所有类起别名-->
<package name="com.zzx"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--第一种写法-加载包下指定是映射文件 -->
<!--<mapper resource="com/zzx/mapper/UserMapper.xml"/>-->
<!--第二种写法-加载包下的所有的映射文件 -->
<package name="com.zzx.mapper"/>
</mappers>
</configuration>
5.在model包下创建实体类:
package com.zzx.model;
/**
* @auther ZhengZiXuan
* @date 2021/3/8 11:29
* @desc
*/
public class User {
private Integer id;
private String name;
private Integer age;
private String sex;
private String username;
private String password;
public User(Integer id, String name, Integer age, String sex, String username, String password) {
this.id = id;
this.name = name;
this.age = age;
this.sex = sex;
this.username = username;
this.password = password;
}
public User() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
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;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", sex=" + sex +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
6.在UserMapper接口中写方法:
package com.zzx.mapper;
import com.zzx.model.User;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
/**
* @auther ZhengZiXuan
* @date 2021/3/8 11:41
* @desc
*/
public interface UserMapper {
User findUserByid(int id);
User findUserById(int id);
User findUserById1(int id);
void add(User user);
void add1(User user);
void insert(User user);
void update(Map<String,Object> map);
void update2(User user);
void update1(@Param("name") String name, @Param("id") int id);
void delete(int id);
//计算总数
int count();
//模糊查询
List<User> findKeyWord(String keyword);
//查询全部
List<User> findAll();
}
7.在mapper.xml中添加我们的SQL:
<?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.zzx.mapper.UserMapper">
<!--id:映射接口的方法名
resultType"" 返回值类型,如果是自定义类,需要写全路径
parameterType:入参类型,与映射接口方法内的参数类型一致
SQL语句:
需要传入参数的位置,使用#{}站稳-->
<resultMap id="userMapId" type="User">
<!--
property :要封装的对象数据类型,就是model类的属性名
column:对应的列名,就是数据库列名的别名
-->
<result property="id" column="idd"></result>
<result property="name" column="ne"></result>
<result property="age" column="a"></result>
<result property="sex" column="s"></result>
<result property="username" column="usernames"></result>
<result property="password" column="admin"></result>
</resultMap>
<!--sql判断
-->
<sql id="testsqlId">
id,`name`,age,sex,username,password
</sql>
<!--第三种写法-->
<select id="findUserById1" resultType="User" parameterType="int">
select <include refid="testsqlId"/> from user where id = #{id}
</select>
<!--第二种方法-->
<select id="findUserByid" resultMap="userMapId" parameterType="int">
select id idd, `name` ne,age a,sex s,username usernames,password admin from user where id = #{id}
</select>
<!--第一种方法-->
<select id="findUserById" resultType="User" parameterType="int">
select * from user where id = #{id}
</select>
<!--第一种写法-->
<insert id="add" parameterType="User">
insert into user values(#{id},#{name},#{age},#{sex},#{username},#{password});
</insert>
<insert id="add1" parameterType="User">
insert into user values(#{id},#{name},#{age},#{sex},#{username},#{password});
</insert>
<update id="update" parameterType="Map">
update user set `name` = #{name} , age = #{age} ,sex = #{sex} ,username=#{username},password=#{password} where id =#{id}
</update>
<!--此处#{name}中的name是接口中注解@Param("name") String name 括号中的name-->
<!--此处#{id}中的name是接口中注解@Param("id") int id 括号中的id-->
<update id="update1" parameterType="Map">
update user set `name` = #{name} where id =#{id}
</update>
<delete id="delete" parameterType="int">
delete from `user` where id = #{id}
</delete>
<select id="count" resultType="int">
select count(*) from `user`
</select>
<select id="findKeyWord" parameterType="String" resultType="User">
select * from user where username like concat('%',#{keyword},'%')
</select>
<update id="update2" parameterType="User" >
update `user` set name=#{name},age = #{age},username=#{username} where id=#{id}
</update>
<select id="findAll" resultType="User">
select <include refid="testsqlId"/> from `user`
</select>
<
insert id="insert" parameterType="User">
insert into `user` (name,age,sex,username,password)values(#{name},#{age},#{sex},#{username},#{password})
</insert>
</mapper>
8.创建测试类,测试代码:
package com.zzx.test;
import com.zzx.mapper.UserMapper;
import com.zzx.model.User;
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.HashMap;
import java.util.List;
/**
* @auther ZhengZiXuan
* @date 2021/3/8 11:55
* @desc
*/
public class MainClass {
private SqlSession sqlSession = null;
@Before
public void beforTest() throws IOException {
String path = "sqlconfigtion.xml";
// 1 加载配置文件
InputStream stream = Resources.getResourceAsStream(path);
// 2 通过配置文件,创建sqlsession工厂
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder( ).build(stream);
// 3 创建出sqlsession
sqlSession = sqlSessionFactory.openSession( );
}
@Test
public void selectOne() throws IOException {
String path = "sqlconfigtion.xml";
//1.加载配置文件
InputStream stream = Resources.getResourceAsStream(path);
//2,通过配置文件创建sqlsession工厂
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(stream);
//3.创建出SQLsession
SqlSession sqlSession = build.openSession();
//4.1获得代理对象
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//4.2执行
User user = mapper.findUserByid(1);
System.out.println(user);
//5.关闭会话
sqlSession.close();
}
@Test
public void insert(){
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = new User();
// user.setId(null);
user.setName("铁手");
user.setAge(12);
user.setSex("男");
user.setUsername("铁手帮");
user.setPassword("123");
mapper.insert(user);
System.out.println(user+"添加成功");
}
@Test
public void selectOne2() throws IOException {
String path = "sqlconfigtion.xml";
//1.加载配置文件
InputStream stream = Resources.getResourceAsStream(path);
//2,通过配置文件创建sqlsession工厂
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(stream);
//3.创建出SQLsession
SqlSession sqlSession = build.openSession();
//4.1获得代理对象
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//4.2执行
User user = mapper.findUserById(1);
System.out.println(user);
//5.关闭会话
sqlSession.close();
}
@Test
public void selectOne3() throws IOException {
String path = "sqlconfigtion.xml";
//1.加载配置文件
InputStream stream = Resources.getResourceAsStream(path);
//2,通过配置文件创建sqlsession工厂
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(stream);
//3.创建出SQLsession
SqlSession sqlSession = build.openSession();
//4.1获得代理对象
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//4.2执行
User user = mapper.findUserById1(1);
System.out.println(user);
//5.关闭会话
sqlSession.close();
}
@Test
public void addone(){
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = new User();
user.setId(7);
user.setName("赵铁柱");
user.setAge(12);
user.setSex("男");
user.setUsername("曹子怡");
user.setPassword("123");
mapper.add(user);
//增删改需要提交
sqlSession.commit();
}
@Test
public void addone1(){
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = new User();
user.setId(8);
user.setName("赵铁柱");
user.setAge(12);
user.setSex("男");
user.setUsername("曹子怡");
user.setPassword("123");
mapper.add1(user);
//增删改需要提交
sqlSession.commit();
}
@Test
public void update(){
//获得代理对象
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//执行
HashMap<String, Object> map = new HashMap<>();
map.put("id",3);
map.put("name","肖铁手");
map.put("age",45);
map.put("sex","女");
map.put("username","肖大炮");
map.put("password","123");
mapper.update(map);
sqlSession.commit();
}
@Test
public void update1(){
//获得代理对象
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//执行
mapper.update1("苏曼",3);
sqlSession.commit();
}
@Test
public void delete1(){
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.delete(16);
sqlSession.commit();
}
@Test
public void count1(){
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int count = mapper.count();
System.out.println(count);
}
@Test
public void KeyWord(){
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> keyword = mapper.findKeyWord("炮");
System.out.println(keyword);
}
@Test
public void findAll(){
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> list = mapper.findAll();
System.out.println(list);
}
@Test
public void update(){
//获得代理对象
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//执行
HashMap<String, Object> map = new HashMap<>();
map.put("id",3);
map.put("name","肖铁手");
map.put("age",45);
map.put("sex","女");
map.put("username","肖大炮");
map.put("password","123");
mapper.update(map);
sqlSession.commit();
}
@After
public void afterTest(){
//关闭会话
sqlSession.close();
}
}