本文主要是介绍MyBatis:概念简章,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1. hello world
配置文件:mybatis-config.xml(核心配置文件,用于配置连接的数据库信息)(一般一个)XxxMapper.xml 该文件用于操作表(执行sql语句)(一张表一个) 细节:执行的sql语句";"可以省略一般有resource这个单词都会从类的根路径开始扫描文件
- 配置mybatis-config.xml文件
- 配置配置xxxMapper.xml文件
- 对数据库进行CRUD操作
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//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.cj.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/study"/><property name="username" value="root"/><property name="password" value="123456"/></dataSource></environment></environments><!--路径映射,要操作的表--><mappers><mapper resource="mapper/EmployeeMapper.xml"/></mappers>
</configuration>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--要进行CURD操作的表-->
<mapper namespace="EmployeeMapper"><!--<select id="selectUser" resultType="Blog">select * from Blog where id = 1</select>--><insert id="insertEmployee">insert into emp value (null, '姬如雪', 18, 2, '佛山');</insert>
</mapper>
@Testpublic void testInsert() throws IOException {//获取对应的数据库配置信息(即要操作哪个数据库)InputStream is = Resources.getResourceAsStream("mybatis-config.xml");//Resources.getResourceAsStream默认从类的根路径开始寻找文件//获取SqlSessionFactoryBuilder(通过该对象创建工厂)(一般一个数据库对应一个SqlSessionFactory)SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();//获取SqlSessionFactory(通过该工厂创建SqlSession:Java程序和数据库之间的会话)SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);//获取SqlSession执行sql语句(即要操作哪张表)SqlSession sqlSession = sqlSessionFactory.openSession();//执行sql语句int rows = sqlSession.insert("insertEmployee");//提交事务sqlSession.commit();System.out.println("rows:" + rows);}
上面测试代码的严谨写法
@Testpublic void testSelectComplete() {SqlSession sqlSession = null;try {//获取SqlSessionFactoryBuild对象SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();//获取SqlSessionFactory工厂SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(Resources.getResourceAsStream("mybatis-config.xml"));//获取SqlSession会话sqlSession = sqlSessionFactory.openSession();int rows = sqlSession.insert("insertEmployee");sqlSession.commit();System.out.println("rows:" + rows);} catch (IOException e) {if (sqlSession != null) {sqlSession.rollback();}e.printStackTrace();} finally {if (sqlSession != null) {sqlSession.close();}}}
2. 封装工具类SqlSessionUtil
由于每次都需要创建SqlSessionFactoryBuilder、SqlSessionFactory、SqlSession对象,可以直接封装成工具类方便调用
public class SqlSessionUtil {private static SqlSessionFactory sqlSessionFactory;static {try {sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));} catch (IOException e) {throw new RuntimeException(e);}}public static SqlSession openSession() {return sqlSessionFactory.openSession();}}
@Testpublic void testSqlSessionUtil() {SqlSession sqlSession = SqlSessionUtil.openSession();int rows = sqlSession.insert("insertEmployee");sqlSession.commit();sqlSession.close();System.out.println("rows:" + rows);}
3. CRUD操作
3.1 增
#{} 占位符 1.如果传map对象:占位符里面的参数要和map集合中的键相一致才能获取map集合中的value值 2.如果传bean对象:占位符里面的参数要和bean对象的属性名保持一致才能获取bean对象的数据
<mapper namespace="EmployeeMapper"><insert id="insertEmployee">insert into emp values (null, #{name}, #{age}, #{deptId}, #{address})</insert>
</mapper>
方式一:通过传map对象
@Testpublic void tesInsertEmployee() {SqlSession sqlSession = SqlSessionUtil.openSession();Map<String, Object> map = new HashMap<>();map.put("name", "肚肚龙");map.put("age", 3);map.put("deptId", 1);map.put("address", "广东");//执行sql语句 底层执行sql语句时会根据map集合的键占位符相匹配,若一致就将值赋给占位符#{}sqlSession.insert("insertEmployee", map);sqlSession.commit();sqlSession.close();}
方式二:通过传bean对象
public class Employee {private Integer id;private String name;private Integer age;private Integer deptId;private String address;
@Testpublic void tesInsertEmployee() {SqlSession sqlSession = SqlSessionUtil.openSession();//执行sql语句 底层执行sql语句时会根据map集合的键占位符相匹配,若一致就将值赋给占位符#{}sqlSession.insert("insertEmployee", map);Employee e = new Employee(null, "肥奶龙", 2, 6, "江门");sqlSession.insert("insertEmployee", e);sqlSession.commit();sqlSession.close();}
3.2 删
<mapper namespace="EmployeeMapper"><delete id="deleteEmployee">delete from emp where id = #{id}</delete>
</mapper>
@Testpublic void testDeleteEmployee() {//获取sql会话SqlSession sqlSession = SqlSessionUtil.openSession();//执行sql语句,由于删除只需要一个参数,故随便传即可,他会自动识别int rows = sqlSession.delete("deleteEmployee", 10028);sqlSession.commit();sqlSession.close();System.out.println("rows:" + rows);}
3.3 改
<mapper namespace="EmployeeMapper"><update id="updateEmployee">update emp set name = #{name}, age= #{age}, dept_id = #{deptId}, address = #{address} where id = #{id}</update>
</mapper>
@Testpublic void testUpdateEmployee() {//获取sql会话SqlSession sqlSession = SqlSessionUtil.openSession();Employee e = new Employee(10027, "胖胖龙", 1, 9, "长沙");//执行sql语句int rows = sqlSession.update("updateEmployee", e);sqlSession.commit();sqlSession.close();System.out.println("rows:" + rows);}
3.4 查
注意:因为查询的列大多要和bean对象的字段进行反射映射匹配赋值,故列要起别名保证和bean对象字段名一致 查询还有返回类型,要指定给查询标签,通过类型反射赋值为防止id冲突,需要引用命名空间,所有语句执行正确的写法为namespace.id
查询单个结果
<mapper namespace="EmployeeMapper"><select id="selectById" resultType="com.itgyl.mybatis.pojo.Employee">select id, name, age, dept_id deptId, address from emp where id = #{id}</select>
</mapper>
@Testpublic void testSelectEmployeeById() {//获取sql会话SqlSession sqlSession = SqlSessionUtil.openSession();//执行sql语句 selectOne查询返回一个bean对象Object employee = sqlSession.selectOne("selectById", 1);sqlSession.close();System.out.println(employee);}
查询所有结果
<mapper namespace="EmployeeMapper"><select id="selectAll" resultType="com.itgyl.mybatis.pojo.Employee">select id, name, age, dept_id deptId, address from emp</select>
</mapper>
@Testpublic void testSelectEmployeeAll() {SqlSession sqlSession = SqlSessionUtil.openSession();/*查询所有bean对象存入list集合中并返回 最严谨写法:namespace.id*/List<Object> employeeList = sqlSession.selectList("EmployeeMapper.selectAll");for (Object o : employeeList) {System.out.println(o);}sqlSession.close();}
4. mybatis-config.xml文件概述
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--配置连接的数据库信息-->
<configuration><!--environments标签:环境可以有多个即可以同时配置多个数据库数据库不唯一,可以配置多个数据库信息即可以创建多个SqlSessionFactory工厂default的值为:不指定创建哪个SqlSessionFactory时默认使用id为default值的数据库--><environments default="development"><environment id="development"><!--在 MyBatis 中有两种类型的事务管理器(也就是 type="[JDBC|MANAGED]"):transactionManage标签:事务管理器1.作用:指定mybatis用什么方式进行管理事务2.有两个type类型:1.JDBC:使用原生的jdbc管理容器coon.setAutoCommit(false)...coon.commit()2.MANAGED:mybatis不再管理事务,将事务管理器交给其他容器管理如javaEE容器进行管理(spring)--><transactionManager type="JDBC"/><!--dataSource 元素使用标准的 JDBC 数据源接口来配置 JDBC 连接对象的资源。datasource:数据源1.作用:为程序提供Connection对象(但凡为程序提供Connection对象的都称为数据源)2.常见的数据源组件(常见的数据库连接池):druid等3.有三种内建的数据源类型(也就是 type="[UNPOOLED|POOLED|JNDI]"):1.UNPOOLED– 这个数据源的实现会每次请求时打开和关闭连接。2.POOLED:使用mybatis自带的数据库连接池3.JNDI:集成其他第三方连接池--><dataSource type="POOLED"><property name="driver" value="com.mysql.cj.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/study"/><property name="username" value="root"/><property name="password" value="123456"/></dataSource></environment></environments><!--Mappers标签:路径映射,要操作的表表不唯一,可以同时配置多个表进行操作即可以创建多少SqlSession--><mappers><mapper resource="mapper/EmployeeMapper.xml"/></mappers>
</configuration>
这篇关于MyBatis:概念简章的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!