MyBatis是一个持久层的框架,mybatis可以将向 preparedStatement中的输入参数自动进行输入映射,将查询结果集灵活映射成java对象即输出映射。
PART_ONE:环境搭建和配置文件编写
1.准备基本的user类和数据库user表
package entiy;
import java.io.Serializable;
public class User implements Serializable {
private int id;
private String name;
private String address;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", address=" + address + "]";
}
}
2.在MyBatis官网中下载其jar包
image.png
将jar包导入到工程中。
2.编写SqlMapConfig.xml,这个文件配置基本的数据库连接信息和之后需要的mappers信息。这个文件需要放在资源文件的根下,或者在使用的时候表明位置
<?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>
<!-- 和spring整合后 environments配置将废除-->
<environments default="development">
<environment id="development">
<!-- 使用jdbc事务管理,事务控制由mybatis-->
<transactionManager type="JDBC" />
<!-- 数据库连接池,由mybatis管理-->
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</dataSource>
</environment>
</environments>
<!-- 加载 映射文件 -->
<mappers>
<!--配置单个xml文件-->
<!--<mapper resource="sqlmap/User.xml"/>
<mapper resource="mapperxml/UserMapper.xml"/>-->
<!-- 配置mapper接口class的方式 -->
<!--<mapper class="Mapper.UserMapper"/> -->
<!-- 批量导入的方式 -->
<package name="Mapper"/>
</mappers>
</configuration>
3.编写user类对应的UserMapper.xml
<?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命名空间,作用就是对sql进行分类化管理,理解sql隔离
注意:使用mapper代理方法开发,namespace有特殊重要的作用
-->
<mapper namespace="Mapper.UserMapper">
<!-- 在 映射文件中配置很多sql语句 -->
<!-- 需求:通过id查询用户表的记录 -->
<!-- 通过 select执行数据库查询
id:标识 映射文件中的 sql
将sql语句封装到mappedStatement对象中,所以将id称为statement的id
parameterType:指定输入 参数的类型,这里指定int型
#{}表示一个占位符号
#{id}:其中的id表示接收输入 的参数,参数名称就是id,如果输入 参数是简单类型,#{}中的参数名可以任意,可以value或其它名称
resultType:指定sql输出结果 的所映射的java对象类型,select指定resultType表示将单条记录映射成的java对象。
-->
<select id="findUserById" parameterType="int" resultType="entiy.User">
select * from t_user where id =#{value}
</select>
<!--用户名模糊查询用户,${}表示拼接字符串,如果只需要传入简单类型,里面只能传value-->
<select id="findUserByName" parameterType="String" resultType="entiy.User">
select * from t_user where name like '%${value}%'
</select>
<!-- 添加用户,#{}中对应User中的变量 -->
<insert id="addUser" parameterType="entiy.User">
<!--查询刚插入的ID,只对sql的自增适用,id是保存在user中的意思-->
<selectKey keyProperty="id" order="AFTER" resultType="String">SELECT LAST_INSERT_ID()</selectKey>
<!--插入UUID-->
<!--<selectKey keyProperty="id" order="BEFORE" resultType="String">SELECT UUID()</selectKey>-->
insert into t_user (name,address) values (#{name},#{address})
</insert>
<!--删除用户-->
<delete id="deleteUserById" parameterType="int">
delete from t_user where id =#{id}
</delete>
<!-- 更新用户 -->
<update id="updateUser" parameterType="entiy.User">
update t_user set name=#{name},address=#{address} where id=#{id}
</update>
<!-- 用户综合查询 -->
<select id="findUserList" parameterType="entiy.UserQueryVo" resultType="entiy.UserCustom">
select * from t_user
<where>
<if test="usercustom!=null">
<if test="usercustom.address!=null and usercustom.address!=''">
and address = #{usercustom.address}
</if>
</if>
</where>
</select>
<!--自定义的resultMap-->
<resultMap type="entiy.User" id="userResultMap">
<id column="id_" property="id"/>
<result column="name_" property="name"/>
</resultMap>
<!-- 字段查询 -->
<select id="findUserResultMap" parameterType="int" resultMap="userResultMap" >
select id id_,name name_ from t_user where id = #{id}
</select>
</mapper>
PART_TWO:基本的CRUD实现,之后还有dao和Mapper的两种方式来实现。
package test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import javax.annotation.Resource;
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.jupiter.api.Test;
import entiy.User;
public class domain {
@Test
public void testselect() throws IOException {
String resource = "SqlMapConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
//创建SqlsessionFactory
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//通过工厂得到sqlsession
SqlSession sqlsession = sessionFactory.openSession();
//通过sqlsession操作数据库,第一个参数是User.xml的方法,第二参数是需要传入的值
User user = sqlsession.selectOne("test.findUserById", 1);
System.out.println(user);
sqlsession.close();
}
@Test
public void testselectByName() throws IOException {
String resource = "SqlMapConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
//创建SqlsessionFactory
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//通过工厂得到sqlsession
SqlSession sqlsession = sessionFactory.openSession();
//通过sqlsession操作数据库,第一个参数是User.xml的方法,第二参数是需要传入的值
List<User> users = sqlsession.selectList("test.findUserByName", "胖");
System.out.println(users);
sqlsession.close();
}
@Test
public void testinsertuser() throws IOException {
String resource = "SqlMapConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
//创建SqlsessionFactory
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//通过工厂得到sqlsession
SqlSession sqlsession = sessionFactory.openSession();
//通过sqlsession操作数据库,第一个参数是User.xml的方法,第二参数是需要传入的值
User test = new User();
test.setName("傻强");
test.setAddress("广州");
sqlsession.insert("test.addUser",test);
sqlsession.commit();
System.out.println(test.getId());
sqlsession.close();
}
@Test
public void testdeletuserbyid() throws IOException {
String resource = "SqlMapConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
//创建SqlsessionFactory
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//通过工厂得到sqlsession
SqlSession sqlsession = sessionFactory.openSession();
//通过sqlsession操作数据库,第一个参数是User.xml的方法,第二参数是需要传入的值
sqlsession.delete("test.deleteUserById",5);
sqlsession.commit();
sqlsession.close();
}
@Test
public void testupdateuser() throws IOException {
String resource = "SqlMapConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
//创建SqlsessionFactory
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//通过工厂得到sqlsession
SqlSession sqlsession = sessionFactory.openSession();
//通过sqlsession操作数据库,第一个参数是User.xml的方法,第二参数是需要传入的值
User test = sqlsession.selectOne("test.findUserById", 3);
test.setName("冲锋舟");
sqlsession.update("test.updateUser", test);
sqlsession.commit();
sqlsession.close();
}
}
PART_THREE:使用dao来实现CRUD操作
1.dao文件
image.png
2.UserDao.java
package dao;
import entiy.User;
public interface UserDao {
public User selectUserById(int id);
}
3.UserDaoImpl.java
package dao;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import entiy.User;
public class UserDaoImpl implements UserDao {
private SqlSessionFactory sqlSessionFactory;
public UserDaoImpl(SqlSessionFactory sqlSessionFactory) {
this.sqlSessionFactory = sqlSessionFactory;
}
@Override
public User selectUserById(int id) {
SqlSession sqlsession = sqlSessionFactory.openSession();
User user = sqlsession.selectOne("test.findUserById", id);
return user;
}
}
备注:SqlSessionFactory是单线程的以节约资源,SqlSession是多线程的,因为其线程不安全。
PART_FOUR:使用Mapper(类似dao只是不用写实现类)来实现CRUD操作
开发规范:
1、在mapper.xml中namespace等于mapper接口地址
2、mapper.java接口中的方法名和mapper.xml中statement的id一致
3、mapper.java接口中的方法输入参数类型和mapper.xml中statement的parameterType指定的类型一致。
4、mapper.java接口中的方法返回值类型和mapper.xml中statement的resultType指定的类型一致。
1.文件结构
2. UserMapper.xml
<?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命名空间,作用就是对sql进行分类化管理,理解sql隔离
注意:使用mapper代理方法开发,namespace有特殊重要的作用
-->
<mapper namespace="Mapper.UserMapper">
<!-- 在 映射文件中配置很多sql语句 -->
<!-- 需求:通过id查询用户表的记录 -->
<!-- 通过 select执行数据库查询
id:标识 映射文件中的 sql
将sql语句封装到mappedStatement对象中,所以将id称为statement的id
parameterType:指定输入 参数的类型,这里指定int型
#{}表示一个占位符号
#{id}:其中的id表示接收输入 的参数,参数名称就是id,如果输入 参数是简单类型,#{}中的参数名可以任意,可以value或其它名称
resultType:指定sql输出结果 的所映射的java对象类型,select指定resultType表示将单条记录映射成的java对象。
-->
<select id="findUserById" parameterType="int" resultType="entiy.User">
select * from t_user where id =#{value}
</select>
<!--用户名模糊查询用户,${}表示拼接字符串,如果只需要传入简单类型,里面只能传value-->
<select id="findUserByName" parameterType="String" resultType="entiy.User">
select * from t_user where name like '%${value}%'
</select>
<!-- 添加用户,#{}中对应User中的变量 -->
<insert id="addUser" parameterType="entiy.User">
<!--查询刚插入的ID,只对sql的自增适用,id是保存在user中的意思-->
<selectKey keyProperty="id" order="AFTER" resultType="String">SELECT LAST_INSERT_ID()</selectKey>
<!--插入UUID-->
<!--<selectKey keyProperty="id" order="BEFORE" resultType="String">SELECT UUID()</selectKey>-->
insert into t_user (name,address) values (#{name},#{address})
</insert>
<!--删除用户-->
<delete id="deleteUserById" parameterType="int">
delete from t_user where id =#{id}
</delete>
<!-- 更新用户 -->
<update id="updateUser" parameterType="entiy.User">
update t_user set name=#{name},address=#{address} where id=#{id}
</update>
<!-- 用户综合查询 -->
<select id="findUserList" parameterType="entiy.UserQueryVo" resultType="entiy.UserCustom">
select * from t_user
<where>
<if test="usercustom!=null">
<if test="usercustom.address!=null and usercustom.address!=''">
and address = #{usercustom.address}
</if>
</if>
</where>
</select>
<!--自定义的resultMap-->
<resultMap type="entiy.User" id="userResultMap">
<id column="id_" property="id"/>
<result column="name_" property="name"/>
</resultMap>
<!-- 字段查询 -->
<select id="findUserResultMap" parameterType="int" resultMap="userResultMap" >
select id id_,name name_ from t_user where id = #{id}
</select>
</mapper>
3.UserMapper.java(这个名字必须和对应的xml相同)
package Mapper;
import java.util.List;
import entiy.User;
import entiy.UserCustom;
import entiy.UserQueryVo;
public interface UserMapper {
public User findUserById(int id);
public List<User> findUserByName(String name);
public void addUser(User user);
public void deleteUserById(int id);
public List<UserCustom> findUserList(UserQueryVo userQueryVo);
public List<User> findUserResultMap(int id);
}
4.测试类
package 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.jupiter.api.Test;
import Mapper.UserMapper;
import entiy.User;
import entiy.UserCustom;
import entiy.UserQueryVo;
public class mapperTest {
//mapper查询id用户
@Test
public void testMapper() throws IOException {
String resource = "SqlMapConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
//创建SqlsessionFactory
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sessionFactory.openSession();
UserMapper usermapper = sqlSession.getMapper(UserMapper.class);
User test = usermapper.findUserById(2);
System.out.println(test);
}
//mapper名字查询用户集
@Test
public void testfindbyname() throws IOException {
String resource = "SqlMapConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
//创建SqlsessionFactory
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sessionFactory.openSession();
UserMapper usermapper = sqlSession.getMapper(UserMapper.class);
List<User> users = usermapper.findUserByName("胖");
System.out.println(users);
}
//mapper用户综合查询
@Test
public void testfindList() throws IOException {
String resource = "SqlMapConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
//创建SqlsessionFactory
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sessionFactory.openSession();
UserQueryVo userQueryVo = new UserQueryVo();
UserCustom userCustom = new UserCustom();
userCustom.setAddress("珠海");
userQueryVo.setUsercustom(userCustom);
System.out.println(userQueryVo.getUsercustom().getAddress());
UserMapper usermapper = sqlSession.getMapper(UserMapper.class);
List<UserCustom> userCustoms = usermapper.findUserList(userQueryVo);
System.out.println(userCustoms);
}
//resultMap字段查询
@Test
public void testfindUserResultMap() throws IOException {
String resource = "SqlMapConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
//创建SqlsessionFactory
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sessionFactory.openSession();
UserMapper usermapper = sqlSession.getMapper(UserMapper.class);
List<User> users = usermapper.findUserResultMap(2);
System.out.println(users);
}
}
网友评论