Mybatis框架学习笔记

1.Mapper代理开发

要满足的要求:
1.定义与SQL映射文件同名的Mapper接口,并且将Mapper接口和SQL映射文件放置在同一目录下
2.设置SQL映射文件的namespace属性为Mapper接口全限定名

<!--加载sql映射文件-->
<!-- <mapper resource="com/mybatis/mapper/UserMapper.xml"/>-->
如果Mapper接口名称和SQL映射文件名称相同,且在同一目录下,可以使用包扫描的方式进行SQL映射文件的加载。
<mappers>
<!--Mapper代理方式-->
<package name="com.itheima.mapper"/>
</mappers>

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"/>
    <!--驼峰式命名规则,全局配置-->
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="org/mybatis/example/BlogMapper.xml"/>
    </mappers>
</configuration>
2.类型别名 typeAliases
<typeAliases>
<!--name属性的值是实体类所在包-->
<package name="com.mybatis.pojo"/>
</typeAliases>
<!---配置完类型别名后,映射配置文件可以简化-->
<mapper namespace="com.mybatis.mapper.UserMapper">
<select id="selectAll" resultType="user">
select * from user;
</select>
</mapper>
3.利用mybatis写查询测试类方法步骤:
  1. 编写接口方法 interface
  2. 在mapper.xml文件下编写sql语句
  3. 编写测试方法
  4. junit代码
 private SqlSessionFactory sessionFactory;
    
    @Before
    public void init() throws IOException {
        // 1.创建SqlSessionFactory对象
        // ①声明Mybatis全局配置文件的路径
        String mybatisConfigFilePath = "mybatis-config.xml";
    
        // ②以输入流的形式加载Mybatis配置文件
        InputStream inputStream = Resources.getResourceAsStream(mybatisConfigFilePath);
    
        // ③基于读取Mybatis配置文件的输入流创建SqlSessionFactory对象
        sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    
    }@Test
    public void testSelectEmployee() throws IOException {
    
        SqlSession session = sessionFactory.openSession();
    
        
    
        session.close();
    }
4.log4j的配置文件加入

先加入加入依赖

<!-- log4j日志 -->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

具体配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
    
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    
    <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
        <param name="Encoding" value="UTF-8" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m  (%F:%L) \n" />
        </layout>
    </appender>
    <logger name="java.sql">
        <level value="debug" />
    </logger>
    <logger name="org.apache.ibatis">
        <level value="info" />
    </logger>
    <root>
        <level value="debug" />
        <appender-ref ref="STDOUT" />
    </root>
</log4j:configuration>
5.关联外部属性文件

jdbc.properties 配置文件

在mybatis全局配置文件中指定外部jdbc.properties 配置文件的位置

<properties resource="jdbc.properties"/>

<dataSource type="POOLED">
    
    <!-- 建立数据库连接的具体信息(引用了外部属性文件中的数据) -->
    <property name="driver" value="${driver}"/>
    <property name="url" value="${url}"/>
    <property name="username" value="${username}"/>
    <property name="password" value="${password}"/>
</dataSource>
6.数据输入
1.单个简单类型参数

接口:
User selectuser(Integer id);
SQL语句:

<select id="selectuser" resultType="com.mybatis.entity.User">
    select user_id empId,user_name empName where user_id=#{userId}
</select>
2.实体类类型参数

接口:
User insertUser(User user);
SQL语句:

<insert id="insertUser">
    insert into td_user(user_name) values(#{userName})
</insert>
3.零散简单类型

接口
int updateUser(@Param("userId") Integer userId, @Param("userName") String userName);
SQL语句:

 <update id="updateUser">
        update td_user set user_name=#{userName} where user_id=#{userId}
    </update>
4.Mao类型参数

接口
int updateUser(Map<String , Object> paramMap);
SQL语句:

 <update id="updateUser">
        update td_user set user_name=#{userNameKey} where user_id=#{userIdKey}
    </update>

junit测试:

@Test
public void testUpdateUserByMap() {
    SqlSession session = sessionFactory.openSession();
    
    UserMapper mapper = session.getMapper(UserMapper .class);
    
    Map<String, Object> paramMap = new HashMap<>();
    
    paramMap.put("userNameKey", 'lisi');
    paramMap.put("userIdKey", 1);
    
    int result = mapper.updateUserByMap(paramMap);
    
    System.out.println("result = " + result);
    
    session.commit();
    
    session.close();
}

为什么不用实体类而用Map?
有很多零散的参数需要传递,但是没有对应的实体类类型可以使用。使用@Param注解一个一个传入又太麻烦了。所以都封装到Map中。

7.数据输出
1.返回单个简单类型数据

接口
int selectUserCount();
SQL:语句:

<select id="selectUserCount" resultType="int">
    select count(*) from tb_user
</select>

junit测试:

 @Test
    public void testEmpCount() {
    
        SqlSession session = sessionFactory.openSession();
    
       	UserMapper mapper = session.getMapper(UserMapper .class);	
    
        int count = userMapper.selectEmpCount();
    
        System.out.println("count = " + count);
    
        session.commit();
    
        session.close();
    }
2.返回实体类对象
User selectUser(Integer userId);

SQL语句
<!-- 编写具体的SQL语句,使用id属性唯一的标记一条SQL语句 -->
<!-- resultType属性:指定封装查询结果的Java实体类的全类名 -->
<select id="selectEmployee" resultType="com.atguigu.mybatis.entity.Employee">
    <!-- Mybatis负责把SQL语句中的#{}部分替换成“?”占位符 -->
    <!-- 给每一个字段设置一个别名,让别名和Java实体类中属性名一致 -->
    select user_id userId,user_name userName from td_user where user_id=#{1}
</select>
3.返回Map类型

接口:
Map<String , Object> select
语句:
<select id="selectEmpNameAndMaxSalary" resultType="map">

4.返回List类型

List<User> selectAll();

<select id="selectAll" resultType="com.atguigu.mybatis.entity.Employee">

5.返回自增主键

int insertUser(User user);

<!-- useGeneratedKeys属性字面意思就是“使用生成的主键” -->
<!-- keyProperty属性可以指定主键在实体类对象中对应的属性名,Mybatis会将拿到的主键值存入这个属性 -->
<insert id="insertUser" useGeneratedKeys="true" keyProperty="empId">

**

Mybatis是将自增主键的值设置到实体类对象中,而不是以Mapper接口方法返回值的形式返回

**

8.全局配置自动识别 驼峰式命名规则

Mybatis 配置:

<!-- 使用settings对Mybatis全局进行设置 -->
<settings>
    <!-- 将xxx_xxx这样的列名自动映射到xxXxx这样驼峰式命名的属性名 -->
    <setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
9resultMap使用

resultMap来定义字段和属性的映射关系

<resultMap id="ResultMap" type="brand">
<!--
id:完成主键字段的映射
column:表的列名
property:实体类的属性名
result:完成一般字段的映射
column:表的列名
property:实体类的属性名
-->
<result column="name" property="Name"/>
<result column="sex" property="Sex"/>
</resultMap>
<!--resulttype要改成resultMap-->
<select id="selectAll" resultMap="ResultMap">
select *
from user;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值