Mybatis基础

Mybatis基础

Mybatis流程

在这里插入图片描述

Mybati基本使用

1、 pom.xml中导入响应依赖

<dependencies>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.15</version>
    </dependency>

    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.4</version>
    </dependency>
</dependencies>

<build>
    <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.xml</include>
        </includes>
      </resource>
    </resources>
</build>

2、创建一个mybatis全局配置文件

<?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>
	 <!-- 配置MyBatis运⾏环境 -->
 <environments default="development">
 	<environment id="development">
 		<!-- 配置JDBC事务管理 -->
 		<transactionManager type="JDBC"></transactionManager>
 		<!-- POOLED配置JDBC数据源连接池 -->
			<dataSource type="POOLED">
				<property name="driver" value="com.mysql.cj.jdbc.Driver"></property>
 				<property name="url" value="jdbc:mysql://localhost:3306/mybatis?
useUnicode=true&amp;characterEncoding=UTF-8"></property>
 				<property name="username" value="root"></property>
 				<property name="password" value="root"></property>
 			</dataSource>
		</environment>
	</environments>
</configuration>

使用原生接口

1、MyBatis 框架需要开发者⾃定义 SQL 语句,写在 Mapper.xml ⽂件中,开发者需要为每个实体类创建对应的 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.haoxuan.mapper.AccoutMapper">
	<insert id="save" parameterType="com.haoxuan.entity.Account">
		insert into t_account(username,password,age) values(#{username},#{password},#{age})
 	</insert>
</mapper>
  • namespace 通常设置为⽂件所在包+⽂件名的形式。
  • insert 标签表示执⾏添加操作。
  • select 标签表示执⾏查询操作。
  • update 标签表示执⾏更新操作。
  • delete 标签表示执⾏删除操作。
  • id 是实际调⽤ MyBatis ⽅法时需要⽤到的参数。
  • parameterType 是调⽤对应⽅法时参数的数据类型。
    2、在mybatis全局配置文件中注册mapper
<?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>
	 <!-- 配置MyBatis运⾏环境 -->
 <environments default="development">
 	<environment id="development">
 		<!-- 配置JDBC事务管理 -->
 		<transactionManager type="JDBC"></transactionManager>
 		<!-- POOLED配置JDBC数据源连接池 -->
			<dataSource type="POOLED">
				<property name="driver" value="com.mysql.cj.jdbc.Driver"></property>
 				<property name="url" value="jdbc:mysql://localhost:3306/mybatis?
useUnicode=true&amp;characterEncoding=UTF-8"></property>
 				<property name="username" value="root"></property>
 				<property name="password" value="root"></property>
 			</dataSource>
		</environment>
	</environments>

	//注册mapper
	<mappers>
		<mapper resource="com/southwind/mapper/AccountMapper.xml"></mapper>
	</mappers>
</configuration>

3、调用

public class Test {
public static void main(String[] args) {
	//加载MyBatis配置⽂件
	InputStream inputStream =Resource.getResourceAsStream("config.xml");
	SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
	SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
	SqlSession sqlSession = sqlSessionFactory.openSession();
	String statement = "com.southwind.mapper.AccoutMapper.save";
	Account account = new Account(1L,"张三","123123",22);
	sqlSession.insert(statement,account);
	sqlSession.commit();
	}
}

通过Mapper代理实现自定义接口

Mapper接口开发需要遵循以下规范:

  • Mapper.xml文件中的namespace与mapper接口的类路径相同。
  • Mapper接口方法名和Mapper.xml中定义的每个statement的id相同
  • Mapper接口方法的输入参数类型和mapper.xml中定义的每个sql 的parameterType的类型相同
  • Mapper接口方法的输出参数类型和mapper.xml中定义的每个sql的resultType的类型相同

1、创建repository包,创建自定义接口

package com.haoxuan.repository;

import com.southwind.entity.Account;
import java.util.List;

public interface AccountRepository {
	public int save(Account account);
	//public int update(Account account);
	//public int deleteById(long id);
	//public List<Account> findAll();
	//public Account findById(long id);
}

2、创建对应的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.haoxuan.repository.AccountRepository">
	<insert id="save" parameterType="com.haoxuan.entity.Account">
	insert into t_account(username,password,age)values(#{username},#{password},#{age})
	</insert>
	<update id="update" parameterType="com.southwind.entity.Account">
 	update t_account set username = #{username},password = #{password},age = #{age} where id = #{id}
 	</update>
 	<delete id="deleteById" parameterType="int">
 	delete from t_account where id = #{id}
 	</delete>
 	<select id="findAll" resultType="com.southwind.entity.Account">
 	select * from t_account
 	</select>
 	<select id="findById" parameterType="long" resultType="com.southwind.entity.Account">
 	select * from t_account where id = #{id}
	</select>
</mapper>

3、在mybatis全局配置文件中进行注册

<!-- 注册AccountMapper.xml -->
<mappers>
	<mapper resource="com/haoxuan/repository/AccountRepository.xml"></mapper>
</mappers>

注意:
1.在注册映射文件时使用< package name=“包名”>标签时,需要映射文件名和接口名一样,不然会报错。
2.在注册映射文件时使用< mapper class="">mapper标签的class属性时,需要映射文件名和接口名一样,不然会报错。
3.在注册映射文件时使用< mapper resource=“org/xx/demo/mapper/xx.xml”/>,不需要映射文件名和接口名一样
4.在使用MapperScannerConfigurer自动扫描时也需要映射文件名和接口名一样

4、调用

public class Test {
	public static void main(String[] args) {
		InputStream inputStream = Resource..getResourceAsStream("config.xml");
		SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
		SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
		SqlSession sqlSession = sqlSessionFactory.openSession();
		//获取实现接⼝的代理对象
		AccountRepository accountRepository = sqlSession.getMapper(AccountRepository.class);
		Account account = new Account();
		int result = accountRepository.save(account);
		sqlSession.commit();
		sqlSession.close();
		}
	}

Mapper映射标签

<!--column不做限制,可以为任意表的字段,而property须为type 定义的pojo属性-->
<!--jdbcType可以不指定-->
<resultMap id="唯一的标识(自定义)" type="映射的pojo对象">
 	 <id column="表的主键字段,或者可以为查询语句中的别名字段" jdbcType="字段类型" property="映射pojo对象的主键属性" />
	 <result column="表的一个字段(可以为任意表的一个字段)" jdbcType="字段类型" property="映射到pojo对象的一个属性(须为type定义的pojo对象中的一个属性)"/>
	 <association property="pojo的一个对象属性" javaType="pojo关联的pojo对象">
 		<id column="关联pojo对象对应表的主键字段" jdbcType="字段类型" property="关联pojo对象的主席属性"/>
 		<result  column="任意表的字段" jdbcType="字段类型" property="关联pojo对象的属性"/>
	 </association>
	 <!-- (用于一对多或多对多关系)集合中的property须为oftype定义的pojo对象的属性-->
	 <collection property="pojo的集合属性" ofType="集合中的pojo对象">
	 	<id column="集合中pojo对象对应的表的主键字段" jdbcType="字段类型" property="集合中pojo对象的主键属性" />
	 	<result column="可以为任意表的字段" jdbcType="字段类型" property="集合中的pojo对象的属性" />  
	 </collection>
</resultMap>

<select id="方法名" parameterType="参数类型(若有参数则需要指定)" resultMap="result映射(没有可不指定)"
resultType="返回类型(pojo对象需要指定,若有resultMap则不指定)">
...sql
</select>

逆向工程MyBatis Generator

MyBatis 框架需要:实体类、⾃定义 Mapper 接⼝、Mapper.xml

传统的开发中上述的三个组件需要开发者⼿动创建,逆向⼯程可以帮助开发者来⾃动创建三个组件,减轻开发者的⼯作量,提⾼⼯作效率。

MyBatis Generator,简称 MBG,是⼀个专⻔为 MyBatis 框架开发者定制的代码⽣成器,可⾃动⽣成MyBatis 框架所需的实体类、Mapper 接⼝、Mapper.xml,⽀持基本的 CRUD 操作,但是⼀些相对复杂的 SQL 需要开发者⾃⼰来完成。

1、导入依赖

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.15</version>
    </dependency>

    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.4</version>
    </dependency>

    <dependency>
      <groupId>org.mybatis.generator</groupId>
      <artifactId>mybatis-generator-core</artifactId>
      <version>1.4.0</version>
    </dependency>

2、创建 MBG 配置⽂件 generatorConfig.xml

  • jdbcConnection 配置数据库连接信息。
  • javaModelGenerator 配置 JavaBean 的⽣成策略。
  • sqlMapGenerator 配置 SQL 映射⽂件⽣成策略。
  • javaClientGenerator 配置 Mapper 接⼝的⽣成策略。
  • table 配置⽬标数据表(tableName:表名,domainObjectName:JavaBean 类名)。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <context id="DB2Tables" targetRuntime="MyBatis3">
        <!-- 生成mysql带有分页的sql的插件  这个可以自己写,-->
        <plugin type="generator.MysqlPaginationPlugin" />
        <plugin type="org.mybatis.generator.plugins.ToStringPlugin" />
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin" />
        <!-- 自定义的注释规则,继承 DefaultCommentGenerator 重写 一些方法 -->
        <commentGenerator type="generator.NewbatisGenerator">
            <!-- 是否去除自动生成日期的注释 true:是 : false:否 -->
            <property name="suppressDate" value="true"/>
            <!-- 是否去除所有自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://数据库地址"
                        userId="username"
                        password="password">
        </jdbcConnection>
        <!--生成entity类存放位置-->
        <javaModelGenerator targetPackage="包名(com.generator.test.entity)" targetProject="项目地址到\java (D:\workspace\src\main\java)">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!--生成映射文件存放位置-->
        <sqlMapGenerator targetPackage="mapper包名" targetProject="项目地址到\java (D:\workspace\src\main\java)">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <!--生成Dao类存放位置(repository)-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="interface包名"
                             targetProject="项目地址到\java (D:\workspace\src\main\java)">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>
        <table tableName="表名" domainObjectName="生成实体的类名">
        </table>
    </context>
</generatorConfiguration>

3、执行

public class Main {
 	public static void main(String[] args) {
 		List<String> warings = new ArrayList<String>();
		boolean overwrite = true;
 		String genCig = "/generatorConfig.xml";
 		File configFile = new File(Main.class.getResource(genCig).getFile());
 		ConfigurationParser configurationParser = new ConfigurationParser(warings);
 		Configuration configuration = null;
 		try {
 			configuration = configurationParser.parseConfiguration(configFile);
 		} catch (IOException e) {
 			e.printStackTrace();
 		} catch (XMLParserException e) {
 			e.printStackTrace();
 		}
 		DefaultShellCallback callback = new DefaultShellCallback(overwrite);
 		MyBatisGenerator myBatisGenerator = null;
 		try {
 			myBatisGenerator = new MyBatisGenerator(configuration,callback,warings);
 		} catch (InvalidConfigurationException e) {
			e.printStackTrace();
		}
 		try {
 		myBatisGenerator.generate(null);
 		} catch (SQLException e) {
		 	e.printStackTrace();
 		} catch (IOException e) {
 			e.printStackTrace();
 		} catch (InterruptedException e) {
 			e.printStackTrace();
 		}
 	}
}

延迟加载

延迟加载也叫懒加载、惰性加载,使⽤延迟加载可以提⾼程序的运⾏效率,针对于数据持久层的操作,在某些特定的情况下去访问特定的数据库,在其他情况下可以不访问某些表,从⼀定程度上减少了 Java应⽤与数据库的交互次数。

  • 在mybatis全局配置文件中开启延迟加载
<setting>
	<!-- 打印SQL(方便调试)-->
 	<setting name="logImpl" value="STDOUT_LOGGING" />
	<!-- 开启延迟加载 -->
	<setting name="lazyLoadingEnabled" value="true"/>
</setting>
  • 将多表关联查询改为多个单表查询

StudentRepository

public Student findByIdLazy(long id);

StudentRepository.xml

<!--注意association中的select属性,column为需要在关联表查询的数据-->
<resultMap id="studentMapLazy" type="com.southwind.entity.Student">
	<id column="id" property="id"></id>
	<result column="name" property="name"></result>
	<association property="classes" javaType="com.southwind.entity.Classes" select="com.southwind.repository.ClassesRepository.findByIdLazy" column="cid">
	</association>
</resultMap>

<select id="findByIdLazy" parameterType="long" resultMap="studentMapLazy">
 select * from student where id = #{id}
</select>

ClassesRepository

public Classes findByIdLazy(long id);

ClassesRepository.xml

<select id="findByIdLazy" parameterType="long" resultType="com.southwind.entity.Classes">
 select * from classes where id = #{id}
</select>

Mybatis动态SQL

使⽤动态 SQL 可简化代码的开发,减少开发者的⼯作量,程序可以⾃动根据业务参数来决定 SQL 的组
成。

  • if标签
<select id="findByAccount" >
 	select * from t_account where
 	<if test="id!=0">
		id = #{id}
	</if>
 	<if test="username!=null">
 		and username = #{username}
 	</if>
 	<if test="password!=null">
 		and password = #{password}
 	</if>
 	<if test="age!=0">
 		and age = #{age}
 	</if>
</select>

if 标签可以⾃动根据表达式的结果来决定是否将对应的语句添加到 SQL 中,如果条件不成⽴则不添加,
如果条件成⽴则添加。

  • where标签
<select id="findByAccount" >
 	select * from t_account
 	<where>
 		<if test="id!=0">
 			id = #{id}
 		</if>
 		<if test="username!=null">
 			and username = #{username}
 		</if>
 		<if test="password!=null">
 			and password = #{password}
 		</if>
 		<if test="age!=0">
 			and age = #{age}
 		</if>
 	</where>
</select>

where 标签可以⾃动判断是否要删除语句块中的 and 关键字,如果检测到 where 直接跟 and 拼接,则
⾃动删除 and,通常情况下 if 和 where 结合起来使⽤。

  • choose、when标签
<select id="findByAccount" >
 	select * from t_account
 	<where>
 		<choose>
 			<when test="id!=0">
 				id = #{id}
 			</when>
 			<when test="username!=null">
 				username = #{username}
 			</when>
 			<when test="password!=null">
 				password = #{password}
 			</when>
 			<when test="age!=0">
				age = #{age}
 			</when>
 		</choose>
 	</where>
</select>
  • trim标签

trim 标签中的 prefix 和 suffix 属性会被⽤于⽣成实际的 SQL 语句,会和标签内部的语句进⾏拼接,如
果语句前后出现了 prefixOverrides 或者 suffixOverrides 属性中指定的值,MyBatis 框架会⾃动将其删
除。

<select id="findByAccount" >
 	select * from t_account
 	<trim prefix="where" prefixOverrides="and">
 		<if test="id!=0">
 			id = #{id}
 		</if>
 		<if test="username!=null">
 			and username = #{username}
 		</if>
 		<if test="password!=null">
 			and password = #{password}
 		</if>
 		<if test="age!=0">
 			and age = #{age}
 		</if>
 	</trim>
</select>
  • set标签

set 标签⽤于 update 操作,会⾃动根据参数选择⽣成 SQL 语句。

<update id="update" >
 update t_account
 	<set>
 		<if test="username!=null">
 			username = #{username},
 		</if>
 		<if test="password!=null">
 			password = #{password},
 		</if>
 		<if test="age!=0">
 			age = #{age}
 		</if>
 	</set>
 	where id = #{id}
</update>
  • foreach标签

foreach 标签可以迭代⽣成⼀系列值,这个标签主要⽤于 SQL 的 in 语句。

<select id="findByIds" >
 	select * from t_account
 	<where>
 		<foreach collection="ids" open="id in (" close=")" item="id"
separator=",">
 			#{id}
 		</foreach>
 	</where>
</select>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值