小蔡学Java

MyBatis(一):入门SQL语句的编写

2023-05-12 15:21 641 0 SSM / SpringBoot 框架篇 MybatisMySQL

一、 Mybatis概述

是一款优秀的持久层 半自动ORM 框架,它支持定制化SQL、存储过程以及高级映射。

MyBatis避免了几乎所有的JDBC代码和手动设置参数以及获取结果集。

MyBatis可以使用简单的XML或注解来配置和映射原生信息,将接口和Java的POJO(普通的Java对象)映射成数据库中的记录。

Configration会去找全局配置文件,然后sesssion工厂去找sqlsession。

Sqlsession就是myBatis中最核心的了。它去加载mappedStatment。然后去执行TransAction。

二、 Mybatis快速入门

1.创建SpringBoot项目

2.引入依赖

	 <dependency>
		<groupId>org.mybatis.spring.boot</groupId>
		<artifactId>mybatis-spring-boot-starter</artifactId>
		<version>2.1.4</version>
	 </dependency>
	 <dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<scope>runtime</scope>
	</dependency>

3.在application.properties中配置数据库连接参数

	spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
	spring.datasource.url=jdbc:frowning://localhost:3306/jdbcDemo
	spring.datasource.username=root
	spring.datasource.password=123456

4.创建实体类com/whitecamellia/entity/Person,并创建相应的数据库表

	public class Person {
		private Integer id;
		private String name;
		private Integer age;
		// getters and setters
	}

创建com/whitecamellia/mapper接口

	@Mapper
	public interface PersonMapper {
		List<Person> findAll();
	}

resources中添加映射文件com.whitecamellia.mapper.PersonMapper.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" >
	<mapper namespace="com.whitecamellia.mapper.PersonMapper">
	   <select id="findAll" resultType="com.whitecamellia.entity.Person">
			select *
			from person
		</select>
	</mapper>

5.测试

	@SpringBootTest
	class MybatisDemoApplicationTests {
	 @Autowired
		private PersonMapper personMapper;
		@Test
		void contextLoads() {
			List<Person> list = personMapper.findAll();
			for (Person person : list) {
				System.out.println(person);
			}
		}
	}

三、 statement详解

Mybatis的核心是SQL,一个statement代表着一个SQL,因此,statement的配置即是我们通过Mybatis操作数据库的核心。

statement分为四个标签:<insert><delete><update><select>,分别代表对数据的增删改查。

标签中定义的便是原生的SQL语句,需要新掌握的是标签上的属性:

  • id

每个statement都有,且为必选属性,id为statement提供唯一标识,以保证该statement可以被成功定位并执行。不能重复。

  • resultType

只有select语句有该属性,代表SQL返回结果的类型,查询用户可以指定为entity.Person类型

比如查询数据总条数,可以指定resultType为long类型,

	<select id="findAll" resultType="com.whitecamellia.entity.Person">
			select *
			from person
	</select>
	
	<select id="selectTotal" resultType="java.lang.Integer">
			select count(*)
			from person
	</select>
  • ** parameterType**

如果SQL中需要传入参数,则可以通过该属性指定参数类型,如果不指定,Mybatis会自动判断,因此该属性没有实质作用。

	<select id="findById" parameterType="int" resultType="com.whitecamellia.entity.Person">
			select *
			from person
			where id = #{id}
	</select>
parameterType指定是什么数据类型,但是Mybatis会自动判断,故可以省略
  • ** resultMap**

只有select语句有,当SQL结果集不能自动映射到实体类属性时使用,

比如数据库字段为person_id,而Person类中属性为personId,此时Mybatis不能自动映射,需要手动映射。

以下为实例,id标签指定主键属性,result标签指定普通属性,column属性对应表中字段名,

property属性对应类中属性名,autoMapping自动映射。可选

		<resultMap id="personMap" type="com.whitecamellia.entity.Person" autoMapping="true">
			<id property="id" column="id"></id>
			<!--        <result property="age" column="age"></result>-->
			<!--        <result property="name" column="name"></result>-->
			<result property="loveColor" column="love_color"></result>
		</resultMap>

		<select id="findAll" resultMap="personMap">
			select *
			from person
		</select>
  • insert插入
	<insert id="insert">
		insert into person(id,name,age,love_color)
		 values
		(null,"zl",26,"紫色")
	</insert>
  • update更新
	<update id="updateById">
		update person
		set name ='petrel'
		where id = 203
	</update>
  • delete删除
	<delete id="deleteById">
			delete
			from person
			where id = 204
	</delete>

传入的参数可以有多种类型

  • 基本类型( int,String,double,long,date……) 在SQL中获取这类请求参数可以使用#{}表达式,{}中可以填任意字符串,但应该保证可读性,比如:
		<select id="findAllById" resultType="com.whitscamellia.entity.Person">
			select * from person where id = #{ids}
		</select>

#{ids} 内部名字id自定义,只是一个占位符

但是也可以指定参数

List<Person> selectByAge(@Param("age1") int a, @Param("age2") int b);
		<select id="selectByAge" resultMap="personMap">
        select *
        from person
        where age >= #{age1}
          and age &lt;= #{age2}
    	</select>
  • POJO 即传入实体类,比如一个Person:
		 <insert id="insert" parameterType="com.whitecamellia.entity.Person">
			insert into person (id, name, age, love_color)
			values (null, #{name}, #{age}, #{loveColor})
		</insert>

注意#{内部字段名是POJO实体类的成员变量名称}

多个参数传递问题 其中有一个参数时java对象,我们需要指定时对象的哪项属性,防止与其他类型参数进行混淆

int i = personMapper.updateById(1, person);
	<update id="updateById">
			update person
			set name  = #{person.name},
				age = #{person.age},
				love_color = #{person.loveColor}
			where id = #{id}
	</update> 

评论( 0 )

  • 博主 Mr Cai
  • 坐标 河南 信阳
  • 标签 Java、SpringBoot、消息中间件、Web、Code爱好者

文章目录