Mybatis原生框架简单使用和配置

Mybatis

主要使用得jar包:
asm-3.3.1.jar
cglib-2.2.2.jar
commons-logging-1.1.1.jar
javassist-3.17.1-GA.jar
mybatis-3.2.1.jar
mysql-connector-java-8.0.17.jar

加载mybatis主要核心:

​ “Configuration.xml”:主要放在resources资源文件夹下:直接文件名就可以加载.

(取名一般为mybatis-config.xml)

String resource = "Configuration.xml";
Reader reader = Resources.getResourceAsReader(resource);
SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);

​ 一般加载核心对象在工具类(enum MybatisUtil)中构造代码块中加载.在格外提供一个获取SqlSession对象得方法.通过sqlMapper.openSession()方法获取.

Configuration.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">
<!--  
	 -//mybatis.org//DTD Config 3.0//EN  约束得Key 
	 http://mybatis.org/dtd/mybatis-3-config.dtd 约束文件地址 如果下载了就使用本地文件地	
-->
<!--通过这个配置文件,完成mybatis与数据库的连接  -->
<configuration>
<!--加载配置文件  -->
	
	<properties resource="db.properties" ></properties>
	
	<!--取别名  -->
	<typeAliases>
		<typeAlias type="项目路径/Xxx" alias="xx"/> <!--不区分大小写  -->
	</typeAliases>
<!-- 配置环境 -->
	<environments default="development">
		<environment id="development">
			<!--事务使用jdbc  -->
			<transactionManager type="JDBC" />
			<!--选择连接池连接  -->
			<dataSource type="POOLED">
				<property name="driver" value="${driverClassName}" />
				<property name="url" value="${url}" />
				<property name="username" value="${username}" />
				<property name="password" value="${password}" />
			</dataSource>
		</environment>
	</environments>
	<mappers>
        <!-- 连接对应类得映射-->
		<mapper resource="项目路径/XxxMapper.xml" />
	</mappers>
</configuration>
XxxMapper.xml:(一般存在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="cn.ndsaddre.mapper.XxxMapper">

	<!--查询一条数据  -->
	<select id="selectById" parameterType="long" resultType="xx">
		select * from product where id=#{id}
	</select>
	
	<!--查询全部数据  -->
	<select id="selectAll" resultType="xx">
		select * from product 
	</select>
	
	<!-- 插入 -->
	<insert id="insert" parameterType="xx" useGeneratedKeys="true"  keyColumn="id" keyProperty="id">
	insert into product(productName , brand,supplier, salePrice, costPrice, cutoff, dir_id)  values(#{productName} ,#{brand} ,#{supplier} ,#{salePrice} ,#{costPrice} ,#{cutoff}, #{dir_id})
	</insert>
	
	<!--删除  -->
	<delete id="del" parameterType="long">
		delete from product where id=#{id}
	</delete>
	
	<!--更新  -->
	<update id="update" parameterType="xx">
	update product  set productName=#{productName} ,brand = #{brand},supplier =#{supplier} ,salePrice = #{salePrice},costPrice = #{costPrice},cutoff = #{cutoff}, dir_id = #{dir_id} where id=#{id}
	</update>
</mapper>

日志配置文件

​ log4j.properties:自定义配置

​ 需要
​ log4j-1.2.17.jar
​ slf4j-api-1.7.2.jar
​ slf4j-log4j12-1.7.2.jar

#5.控制台输出+自定义布局
log4j.rootLogger=DEBUG,my
#指定输出器
log4j.appender.my=org.apache.log4j.ConsoleAppender
#指定布局器(自定义布局)
#指定布局为自定义布局
log4j.appender.my.layout=org.apache.log4j.PatternLayout
#指定在自定义布局的格式,%d -- 表示当前系统时间,%t -- 执行该业务的线程名称,%p -- 日记器的级别,-5 -- 5表示输出字符的个数,符号表示右对齐
#%c -- 表示指定业务所在的类的完全限定名(包名.类名),%m -- 输出额外信息,%n -- 表示换行
log4j.appender.my.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
#设置package(可以是自定义的包也可以是api的包)输出级别
log4j.logger.org.springframework=info
log4j.logger.cn.itsource=debug
用Dao层操作:
//获取SqlSession对象
SqlSession sqlsession=sqlMapper.openSession();
sqlsession.selectOne("XxxMapper.xml中的nampspace设置的地址.和标签中id名",Object  o);
// o:"传入的对象或基本数据类型数据";在XxxMapper.xml中数据类型对应parameterType="xx"
//返回值 为resultType="xx" 设置的类型,没有取别名就使用全限定名.
不需要建立Dao层操作:
//获取SqlSession对象
SqlSession sqlsession=sqlMapper.openSession();
//获取对应的接口实现类
T mapper = sqlSession.getMapper(T.class);
//其中T的方法由XxxMapper.xml各个id决定     XxxMapper.xml中的namespace必须时接口的全限定名.

$和#的区别:

​ $是拼接字符串,容易造成sql注入,一般用于结构性代码添加,比如limit , order by , group by

​ #是preparedStatment的占位符表示.

主键获取

​ 在XxxMapper.xml中的insert标签中,添加useGeneratedkeys属性,为true,让后在添加keyColumn属性,为数据库对应的列的属性名,最后在添加keyProperty,这是传进来参数对象其中的字段名.

动态SQL

< if >标签:

<if test="条件">执行的sql语句 </if> <!--条件是传入的参数 用and or 拼接 -->  

​ 作用:符合条件执行if中的语句

< where >标签:

<where> 执行的sql</where>

​ 作用:拼接一个where,忽略第一个and或者or,自动加空格.

模糊查询:使用concat函数拼接

and name like  concat('%',#{name},'%')

< foreach >标签:

<foreach collection="遍历的集合类型" item="集合中的一个对象" open="开始添加" close="最后添加" separator="中间最后添加的">
     执行的循序代码           
</foreach>
抽取sql
//抽取出来的sql
<sql id="address">
    <if test='address != null and !"".equals(address.trim())'>
        and address like CONCAT('%',trim(#{address}),'%')
    </if>
</sql>

//调用sql
<include refid="address"></include>
Map映射

结果集映射resultMap:

在select标签中使用resultMap属性:

<select id="" resultMap="resultMap标签id">
<resultMap id="名字" type="返回类型全限定名">
        <id column="数据库主键名字" property="类中对应的字段"/>
        <result column="数据库列命" property="类中对应的字段"/>
    	<result ....>
            
        //多对一的情况
        //方式一
        <association property="类中的对象字段名称" javaType="此对象的全限定名">//类中的对象属性添加  需要sql语句关联表
            <id column="此对象对应的数据库主键别名" property="对象中对应的属性"/>
            <result column="数据库别名" property="对象中对应的属性"/>
        </association>
        //方式二
        <association property="类中的对象字段名称" column="外键列名称" select="select查询id" javaType="此对象的全限定名">//每张表独立查询  select 中的sql需要判断条件
            
         //一对多的情况
         //方式一 需要sql语句关联表
        <collection property="集合类型"  ofType="集合中对象的全限定名">
            <id column="此对象对应的数据库主键别名" property="对象中对应的属性"/>
            <result column="数据库别名" property="对象中对应的属性"/>
        </collection>    
        //方式二 每张表独立查询  select 中的sql需要判断条件
         <collection property="类中的对象字段名称" select="select查询id" column="外键列名称" ofType="此对象的全限定名"/>
</resultMap> 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值