Day 43 学习分享 - Maven 和 Mybatis

什么是Maven
Maven是一个专注于项目构建和依赖管理的项目管理工具
他包含了一个项目对象模型(POM:Project Object Model),
一组标准集合, 一个项目生命周期, 一个依赖管理系统和用来运行定义在生命周期阶段中插件目标的逻辑
Maven的作用
Maven可以集中管理所有依赖(jar包)
Maven可以构建项目(项目自动编译、运行、打包、部署、发布...)
Maven可以创建聚合工程(Maven聚合、继承等等...)

核心思想:
	约定优于配置:
		按照Maven的约定, 无需手动配置
		Maven有很多事先约定的规则, 满足规则以进行项目开发
Maven配置
1. 配置环境变量:
	M2_HOME: 安装路径
	PATH: 安装路径\bin
	cmd命令输入mvn -v验证安装是否正确
2. 修改本地仓库
	conf\settings.xml中
	<localRepository>[本地仓库路径]</localRepository>
3. IDEA环境配置
	setting和other setting ---> Build Tools ---> Maven
	修改最下方地址
4. 配置阿里云镜像站点
	conf\settings.xml中
	<mirror>  
      <id>alimaven</id>  
      <name>aliyun maven</name>  
      <url>http://maven.aliyun.com/nexus/content/groups/public/</url>  
      <mirrorOf>central</mirrorOf>          
	</mirror> 
	
如果创建Maven项目缓慢的话, 加上参数archetypeCatalog = internal
依赖的范围问题
compile:
	默认的依赖范围, 会被使用在编译、测试、运行
provided:
	在编译和测试时需要, 在运行时不需要
	如:servlet api被tomcat容器提供, 如果使用compile依赖范围, 就会产生冲突
runtime:
	在运行和测试时需要, 但是在编译时不需要
test:
	测试阶段可用, 编译和运行时不需要
system:
	不推荐使用此依赖

在这里插入图片描述

Mybatis概念
Mybatis是一个基于Java的持久层框架
Mybatis消除了几乎所有的JDBC代码和参数的手工设置以及对结果集的检索封装
Mybatis还可以使用简单的XML或注解用于配置和原始映射,将接口和Java的POJO映射成数据库中的记录
Mybatis提供一种半自动化的ORM实现
	(ORM: Object Relation Mapping 对象关系映射)
POM.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.bruceliu.mybatis</groupId>
    <artifactId>mybatis-20190902</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!--导入MyBatis开发环境的依赖-->
    <dependencies>

        <!-- myBatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>

        <!-- mysql驱动包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>

        <!-- Junit测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

        <!--Log4J日志工具  打印运行日志用的!-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.14</version>
        </dependency>

    </dependencies>


    <!--如果是WEB项目,那么不用创建bulid标签-->
    <build>
        <!--编译的时候同时也把包下面的xml同时编译进去-->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>


</project>
mybatis-config.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>

	<!-- 引入外部配置文件 -->
	<properties resource="jdbc.properties"/>
    
    <typeAliases>
    	<package name="com.mybatis.bean">
    </typeAliases>

	<!-- 环境 -->
	<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>
    

    <!--映射Mapper文件-->
     <!--引入映射文件-->
    <mappers>
        <package name="com.mybatis.mapper"/>
    </mappers>

</configuration>
接口Mapper文件配置
<?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.mybatis.UserMapper">
    
    <!-- 返回值类型 -->
    <select id="getList" resultType="com.bruceliu.bean.User">
       select * from user
    </select>
 
</mapper>
封装工具类获取SqlSession
public class MyBatisUtils {

    /**
     * 01-获取SqlSession
     * @return
     */
    public static SqlSession getSession(){
        SqlSession session=null;
        InputStream inputStream=null;
        try {
            //配置文件的路径
            String resource = "mybatis-config.xml";
            //加载配置文件,得到一个输入流
            inputStream = Resources.getResourceAsStream(resource);
            //获取MyBatis的Session工厂
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            //通过session工厂获取到一个session (此session非Servlet中Session,这个Session表示MyBatis框架和数据库的会话信息)
            //获取到session就表示MyBatis连接上数据库啦!!类似于JDBC中 Connection对象
            session = sqlSessionFactory.openSession(true);//自动提交事务
            //调用session的查询集合方法
            return session;
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            } 
        }
        return null;
    }

    /**
     * 02-关闭SqlSession
     * @param session
     */
    public static void closeSession(SqlSession session){
        if(session!=null){
            session.close();
        }
    }
}
MapperXML文件CRUD
select :
	    <select id="getById" parameterType="int" resultType="User">
          select * from user where id=#{id}
    </select>

insert:
	    <!-- 增删改返回的都是int值 不用写返回值 -->
    <insert id="addUser">
       INSERT INTO USER VALUES (null,#{username},#{birthday},#{sex},#{address})
    </insert>

insert:(获得自增ID)
	    <!-- 增删改返回的都是int值 不用写返回值 -->
    <insert id="addUser" parameterType="User" useGeneratedKeys="true" keyProperty="id">
       INSERT INTO USER VALUES (null,#{username},#{birthday},#{sex},#{address})
    </insert>


	<insert id="addUser" parameterType="User">
       <selectKey keyProperty="id" resultType="int" order="AFTER">
	        SELECT LAST_INSERT_ID() 
       </selectKey>
       <!--SELECTKEY语句必须和INSERT语句一起使用-->
        INSERT INTO USER VALUES (null,#{username},#{birthday},#{sex},#{address})
    </insert>

Update:
	<update id="updateUser" >
       update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id}
    </update>

delete:
	    <delete id="deleteUser" parameterType="int">
         delete from user where id=#{id}
    </delete>
#和$的区别:
{}:相当于占位符		
	{id}:其中的id可以表示输入参数的名称,如果是简单类型名称可以任意
	
${}:表示拼接sql语句
	${value}:表示输入参数的名称,如果参数是简单类型,参数名称必须是value
	
	# {} 实现的是sql语句的预处理参数,之后执行sql中用?号代替,使用时不需要关注数据类型,Mybatis自动实现数据类型的转换。并且可以防止SQL注入。
	
	${} 实现是sql语句的直接拼接,不做数据类型转换,需要自行判断数据类型。不能防止SQL注入。
	
	# {} 占位符,用于参数传递。
	${}用于SQL拼接。
Mybatis动态SQL
三大主要语句:

IF + WHERE:
	<select id="selectUserByUsernameAndSex" resultType="User"
		parameterType="User">
		select * from user
		<where>
			<if test="username != null">
				username=#{username}
			</if>
			<if test="sex != null">
				and sex=#{sex}
			</if>
		</where>
	</select>

IF + SET:
	<update id="updateUserById" parameterType="User">
		update user u
		<set>
			<if test="username != null and username != ''">
				u.username = #{username},
			</if>
			<if test="sex != null and sex != ''">
				u.sex = #{sex},
			</if>
		</set>
		where id=#{id}
	</update>

FOREACH:
	(a): 单参数List的类型
	<select id="dynamicForeachTest" resultType="User">
		select * from user where id in
		<foreach collection="list" index="index" item="item" open="("
			separator="," close=")">
			#{item}
		</foreach>
	</select>
	(b): 单参数Array的类型
	<select id="dynamicForeach2Test" resultType="User">
		select * from user where id in
		<foreach collection="array" index="index" item="item" open="("
			separator="," close=")">
			#{item}
		</foreach>
	</select>
关联映射
一对一:

<?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.mybatis.mapper.ClassMapper">
    <!-- 
        select * from class c, teacher t where c.teacher_id=t.t_id and c.c_id=1
    -->
    <select id="getClass1" parameterType="int" resultMap="ClassResultMap1">
        select * from class c, teacher t where c.teacher_id=t.t_id and c.c_id=#{id}
    </select>
    <!-- 使用resultMap映射实体类和字段之间的一一对应关系 -->
    <resultMap type="Classes" id="ClassResultMap1">
        <id property="id" column="c_id"/>
        <result property="name" column="c_name"/>
        <association property="teacher" javaType="Teacher">
            <id property="id" column="t_id"/>
            <result property="name" column="t_name"/>
        </association>
    </resultMap>
</mapper>
	property:对象属性的名称
	javaType:对象属性的类型
	column:所对应的外键字段名称
	select:使用另一个查询封装的结果
一对多:

	<?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.bruceliu.mapper.ClassesMapper">

    <!--配置1对多 结果集映射-->
    <resultMap id="classMap" type="Classes">
        <!--主键-->
        <id property="cId" column="C_ID"/>
        <result property="cName" column="c_name"/>
        <!--配置一个包含关系 “有很多”关系 -->
        <collection property="students" ofType="Student">
            <id property="sId" column="s_id"/>
            <result property="sName" column="s_name"/>
            <result property="sAge" column="s_age"/>
            <result property="sEmail" column="s_email"/>
            <result property="classId" column="class_id"/>
        </collection>

    </resultMap>
    <select id="getById" resultMap="classMap">
        SELECT C.*,S.* FROM classes C INNER JOIN student S on C.c_id=S.class_id where C.c_id=#{classId}
    </select>
</mapper>

	MyBatis中使用collection标签来解决一对多的关联查询,ofType属性指定集合中元素的对象类型。
多对多:
	
	<?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.bruceliu.mapper.UserMapper">
    <resultMap id="userMap" type="User">
        <id property="uId" column="u_id"/>
        <result property="uAge" column="u_age"/>
        <result property="uName" column="u_name"/>
        <result property="uSex" column="u_sex"/>
        <!--一个用户多个角色-->
        <collection property="roles" ofType="Role">
            <id property="rId" column="r_id"/>
            <result property="rName" column="r_name"/>
        </collection>
    </resultMap>
    <select id="getUserByid" resultMap="userMap">
        SELECT * FROM `user` U INNER JOIN role_user RU ON U.u_id=RU.uu__id INNER JOIN role R ON RU.rr_id=R.r_id
where U.u_id=#{uid}
    </select>
</mapper>
MybatisPlus配置
1. 导入MybatisPlus依赖
2. Mapper接口继承BaseMapper<T>
3. 修改工具类SqlSessionFactoryBuilder
	变为MybatisSqlSessionFactoryBuilder
4. 在Mybatis-config.xml文件中配置MybatisPlus分页插件
	<plugins>
    	<plugin interceptor="com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor"/>
	</plugins>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值