【ssm】mybatis快速入门

MyBatis官网地址:http://www.mybatis.org/mybatis-3/

案例需求:

通过mybatis查询数据库user表的所有记录,封装到User对象中,打印到控制台上

  1. 创建数据库及user表
  2. 创建maven工程,导入依赖(MySQL驱动、mybatis、junit)
  3. 编写User实体类
  4. 编写UserMapper.xml映射配置文件(ORM思想)
  5. 编写SqlMapConfig.xml核心配置文件
    数据库环境配置
    映射关系配置的引入(引入映射配置文件的路径)
  6. 编写测试代码
    // 1.加载核心配置文件
    // 2.获取sqlSessionFactory工厂对象
    // 3.获取sqlSession会话对象
    // 4.执行sql
    // 5.打印结果
    // 6.释放资源

1. 创建数据库及user表

CREATE DATABASE `mybatis_db`;
USE `mybatis_db`;
CREATE TABLE `user` (
`id` int(11) NOT NULL auto_increment,
`username` varchar(32) NOT NULL COMMENT '用户名称',
`birthday` datetime default NULL COMMENT '生日',
`sex` char(1) default NULL COMMENT '性别',
`address` varchar(256) default NULL COMMENT '地址',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- insert....
insert into `user`(`id`,`username`,`birthday`,`sex`,`address`) values (1,'子
慕','2020-11-11 00:00:00','男','北京海淀'),(2,'应颠','2020-12-12 00:00:00','男','北
京海淀');

2. 创建maven工程,导入依赖(MySQL驱动、mybatis、junit)

<!--指定编码和版本-->
<properties>
	<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
	<java.version>1.11</java.version>
	<maven.compiler.source>1.11</maven.compiler.source>
	<maven.compiler.target>1.11</maven.compiler.target>
</properties>
<!--mybatis坐标-->
<dependency>
	<groupId>org.mybatis</groupId>
	<artifactId>mybatis</artifactId>
	<version>3.5.4</version>
</dependency>
<!--mysql驱动坐标-->
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<version>5.1.6</version>
	<scope>runtime</scope>
</dependency>
<!--单元测试坐标-->
<dependency>
	<groupId>junit</groupId>
	<artifactId>junit</artifactId>
	<version>4.12</version>
	<scope>test</scope>
</dependency>

3. 编写User实体类

public class User {
	private Integer id;
	private String username;
	private Date birthday;
	private String sex;
	private String address;
	// getter/setter 略
}

4. 编写UserMapper.xml映射配置文件(ORM思想)

<?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="UserMapper">
<!--查询所有-->
<select id="findAll" resultType="com.lagou.domain.User">
	select * from user
</select>
</mapper>

5. 编写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>
<!--环境配置-->
<environments default="mysql">
	<!--使用MySQL环境-->
	<environment id="mysql">
		<!--使用JDBC类型事务管理器-->
		<transactionManager type="JDBC"></transactionManager>
		<!--使用连接池-->
		<dataSource type="POOLED">
			<property name="driver" value="com.mysql.jdbc.Driver"></property>
			<property name="url" value="jdbc:mysql:///mybatis_db"></property>
			<property name="username" value="root"></property>
			<property name="password" value="root"></property>
		</dataSource>
	</environment>
</environments>
<!--加载映射配置-->
<mappers>
	<mapper resource="com/lagou/mapper/UserMapper.xml"></mapper>
</mappers>
</configuration>

6. 编写测试代码

@Test
public void testFindAll() throws Exception {
	// 加载核心配置文件
	InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
	// 获取SqlSessionFactory工厂对象
	SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
	// 获取SqlSession会话对象
	SqlSession sqlSession = sqlSessionFactory.openSession();
	// 执行sql
	List<User> list = sqlSession.selectList("UserMapper.findAll");
	for (User user : list) {
		System.out.println(user);
	}
	// 释放资源
	sqlSession.close();
}

映射文件讲解:

在这里插入图片描述

一、Mybatis增删改查

1. 新增

1.1 编写映射文件UserMapper.xml
<!--新增-->
<insert id="save" parameterType="com.lagou.domain.User">
	insert into user(username,birthday,sex,address)
	values(#{username},#{birthday},#{sex},#{address})
</insert>
1.2 编写测试类
	 @Test
    public void testSave() throws Exception {
        // 加载核心配置文件
        InputStream is = Resources.getResourceAsStream("config/SqlMapConfig.xml");
        // 获取SqlSessionFactory工厂对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        // 获取SqlSession会话对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        // 执行sql
        User user = new User();
        user.setUsername("怪咖");
        user.setBirthday(new Date());
        user.setSex("男");
        user.setAddress("北京海淀");
        sqlSession.insert("com.cyh.dao.UserMapper.save", user);
        // DML语句,手动提交事务
        sqlSession.commit();
        // 释放资源
        sqlSession.close();
    }

新增、注意事项

  • 插入语句使用insert标签
  • 在映射文件中使用parameterType属性指定要插入的数据类型
  • Sql语句中使用#{实体属性名}方式引用实体中的属性值
  • 插入操作使用的API是sqlSession.insert(“命名空间.id”,实体对象);
  • 插入操作涉及数据库数据变化,所以要使用sqlSession对象显示的提交事务,即sqlSession.commit()

2.修改

2.1 编写映射文件UserMapper.xml
    <!--
    修改
        sqlSession.update("UserMapper.update", user);
    -->
    <update id="update" parameterType="com.cyh.pojo.User">
        update user set username = #{username},birthday = #{birthday},
        sex = #{sex},address = #{address} where id = #{id}
    </update>
2.2 编写测试类
	@Test
    public void testUpdate() throws Exception {
        // 加载核心配置文件
        InputStream is = Resources.getResourceAsStream("config/SqlMapConfig.xml");
        // 获取SqlSessionFactory工厂对象
        SqlSessionFactory sqlSessionFactory = new
                SqlSessionFactoryBuilder().build(is);
        // 获取SqlSession会话对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        // 执行sql
        User user = new User();
        user.setId(4);
        user.setUsername("lucy");
        user.setBirthday(new Date());
        user.setSex("女");
        user.setAddress("北京朝阳");
        sqlSession.update("com.cyh.dao.UserMapper.update", user);
        // DML语句,手动提交事务
        sqlSession.commit();
        // 释放资源
        sqlSession.close();
    }·

修改、注意事项

  • 修改语句使用update标签
  • 修改操作使用的API是sqlSession.update(“命名空间.id”,实体对象);

3.删除

3.1 编写映射文件UserMapper.xml
    <!--
    删除
        sqlSession.delete("UserMapper.delete", 4);
    -->
    <delete id="delete" parameterType="java.lang.Integer">
        delete from user where id = #{id}
    </delete>
3.2 编写测试类
	@Test
    public void testDelete() throws Exception {
        // 加载核心配置文件
        InputStream is = Resources.getResourceAsStream("config/SqlMapConfig.xml");
        // 获取SqlSessionFactory工厂对象
        SqlSessionFactory sqlSessionFactory = new
                SqlSessionFactoryBuilder().build(is);
        // 获取SqlSession会话对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        // 执行sql
        sqlSession.delete("com.cyh.dao.UserMapper.delete", 4);
        // DML语句,手动提交事务
        sqlSession.commit();
        // 释放资源
        sqlSession.close();
    }

删除、注意事项

  • 删除语句使用delete标签
  • Sql语句中使用#{任意字符串}方式引用传递的单个参数
  • 删除操作使用的API是sqlSession.delete(“命名空间.id”,Object);

二、Mybatis 常用配置解析

1. environments标签

数据库环境的配置,支持多环境配置
在这里插入图片描述

  1. 其中,事务管理器(transactionManager)类型有两种:
  • JDBC
    这个配置就是直接使用了JDBC 的提交和回滚设置,它依赖于从数据源得到的连接来管理事务作用域。
  • MANAGED:(配置几乎没做什么)
    这个配置几乎没做什么。它从来不提交或回滚一个连接,而是让容器来管理事务的整个生命周期。
    例如:mybatis与spring整合后,事务交给spring容器管理。
  1. 其中,数据源(dataSource)常用类型有三种:
  • UNPOOLED
    这个数据源的实现只是每次被请求时打开和关闭连接。
  • POOLED
    这种数据源的实现利用“池”的概念将 JDBC 连接对象组织起来。
  • JNDI :
    这个数据源实现是为了能在如 EJB 或应用服务器这类容器中使用,容器可以集中或在外部配置数据源,然后放置一个 JNDI 上下文的数据源引用

2. properties标签

实际开发中,习惯将数据源的配置信息单独抽取成一个properties文件,该标签可以加载额外配置的

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///mybatis_db
jdbc.username=root
jdbc.password=root

在这里插入图片描述

3. typeAliases标签

类型别名是为 Java 类型设置一个短的名字。
为了简化映射文件 Java 类型设置,mybatis框架为我们设置好的一些常用的类型的别名:

别名数据类型
stringString
longLong
intInteger
doubleDouble
booleanBoolean
… …… …

在这里插入图片描述

	<!--设置别名-->
    <typeAliases>
        <!--方式一:给单个实体起别名-->
        <typeAlias type="com.cyh.pojo.User" alias="user"></typeAlias>
        <!--方式二:批量起别名 别名就是类名,且不区分大小写-->
        <package name="com.cyh.pojo"/>
    </typeAliases>

4. mappers标签

该标签的作用是加载映射的,加载方式有如下几种:

  1. 使用相对于类路径的资源引用,例如:

    <mapper resource="org/mybatis/builder/userMapper.xml"/>
    
  2. 使用完全限定资源定位符(URL),例如:

    <mapper url="file:///var/mappers/userMapper.xml"/>
    

    《下面两种mapper代理开发中使用:暂时了解》

  3. 使用映射器接口实现类的完全限定类名,例如:

    <mapper class="org.mybatis.builder.userMapper"/>
    
  4. 将包内的映射器接口实现全部注册为映射器,例如:

    <package name="org.mybatis.builder"/>
    

配置文件总结

environments标签:数据源环境配置

<environments default="development">
	<environment id="development">
		<transactionManager type="JDBC"/>
		<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>

properties标签:该标签可以加载外部的properties文件

<properties resource="jdbc.properties"></properties>

typeAliases标签:设置类型别名

<typeAlias type="com.lagou.domain.User" alias="user"></typeAlias>

mappers标签:加载映射配置

<mapper resource="com/lagou/mapper/UserMapping.xml"></mapper>

三、Mybatis基本原理介绍

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
苹果公司所用字体大全苹果公司所用字体大全苹果公司所用字体大全苹果公司所用字体大全苹果公司所用字体大全,苹果公司所用字体大全,苹果公司所用字体大全,苹果公司所用字体大全,苹果公司所用字体大全,苹果公司所用字体大全,苹果公司所用字体大全,苹果公司所用字体大全,苹果公司所用字体大全,苹果公司所用字体大全,苹果公司所用字体大全,苹果公司所用字体大全,苹果公司所用字体大全,苹果公司所用字体大全,苹果公司所用字体大全,苹果公司所用字体大全,苹果公司所用字体大全,苹果公司所用字体大全,苹果公司所用字体大全,苹果公司所用字体大全,苹果公司所用字体大全,苹果公司所用字体大全,苹果公司所用字体大全,苹果公司所用字体大全,苹果公司所用字体大全,苹果公司所用字体大全,苹果公司所用字体大全,苹果公司所用字体大全,苹果公司所用字体大全,苹果公司所用字体大全,苹果公司所用字体大全,苹果公司所用字体大全,苹果公司所用字体大全,苹果公司所用字体大全,苹果公司所用字体大全,苹果公司所用字体大全,苹果公司所用字体大全,苹果公司所用字体大全,苹果公司所用字体大全,苹果公司所用字体大全,苹果公司所用字体大全,苹果公司所用字体大

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值