[MyBatis] Mybatis additions, deletions, modifications and use of configuration files

1. Getting to know MyBatis for the first time

MyBatis official website: MyBatis official website
1. What is MyBatis
MyBatis is a persistence layer framework that supports common sql queries, stored procedures, and advanced mapping . The MyBatis framework is also known as the ORM (Object/Relational Mapping, object-relational mapping) framework .

The main role of ORM is to use object-oriented methods to operate persistent objects in programming, and to correspond object-oriented concepts with tables in the database.
insert image description here

Take a chestnut: I define a class, which corresponds to a table in the database at this time, and an instance of this object corresponds to a record in the table.

Java concepts database concept
kind surface
Attributes field/column
object record/line

2. Features
(1) Lightweight, excellent performance, interface-oriented programming
(2) Separation of sql and Java business codes
(3) XML or annotations can be used for configuration and mapping
3. MyBatis interface-oriented programming is consistent with two :
( 1) The namespace of the mapping file must be consistent with the full class name of the mapper interface
(2) The id of the SQL statement in the mapping file must be consistent with the method name in the mapper interface
insert image description here
4. Execution process of the Mybatis framework
(1) Read the mybatis configuration file ;
(2) Load the mapping file xxxMapper.xml;
(3) Build the session factory SqlSessionFactory;
(4) Build the session object SqlSession;
(5) Executor, perform related operations;
(6) MappedStatement object;
(7) Input mapping;
(8) Output mapping;

@Test
public void insertUser() throws Exception {
    
    
    // 1.读取配置文件
    InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
    // 2.根据配置文件构建SqlSessionFactory
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
    // 3.通过sqlSessionFactory创建SqlSession
    //SqlSession默认不自动提交事务,若需要自动提交,需要设置sqlSessionFactory.openSession(true)即可自动提交
    SqlSession session = sqlSessionFactory.openSession(true);
    // 4.使用SqlSession对象执行映射文件中定义的sql,并返回映射结果
    // 4.1获取mapper接口对象
    UserMapper userMapper = session.getMapper(UserMapper.class);
    // 4.2测试功能
    int result = userMapper.insertUser();
    // 4.3提交事务
    //session.commit();
    // 4.4输出结果
    System.out.println("result="+result);
    //5.关闭SqlSession
    session.close();
}

5. The level of the log4j log is
FATAL (fatal) > ERROR (error) > WARN (warning) > INFO (information) > DEBUG (debug) and
the information printed from left to right becomes more and more detailed.
6. Four import methods of mapper mapping files

<!-- 配置映射文件:用来配置sql语句和结果集类型等 -->
<!--1.使用类路径引入-->
<mappers>
    <mapper resource="com/jd/wds/mappers/ParameterMapper.xml"/>
</mappers>
<!--2.使用本地文件路径引入-->
<mappers>
    <mapper url="file:\\\E:\Spring\Mbatis\mybatis-demo02\src\main\resources\com\jd\wds\mappers\ParameterMapper.xml"/>
</mappers>
<!--3.使用接口类引入-->
<mappers>
    <mapper class="com.jd.wds.mappers.ParameterMapper"/>
</mappers>
<!--4.使用包名引入-->
<mappers>
    <package name="com.jd.wds.mappers"/>
</mappers>

2. Mybatis development instructions

1. Dependencies that need to be introduced

<!-- mybatis依赖 -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.4.0</version>
</dependency>
<!-- MySQL数据库依赖 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.11</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.17</version>
</dependency>

2. The label of the query function must be set to resultType or resultMap
resultType: set the default mapping relationship (field name and attribute name are consistent)
resultMap: set custom mapping relationship (field name and attribute name are inconsistent, many-to-one, one-to-many mapping)
3 . Add, delete, modify and query operations on the user table (UserMapper.xml)

<!--1.插入一条记录-->
<insert id="insertUser">
 insert into user values(null,"小王","男",17,"[email protected]")
</insert>
<!--2.删除一条记录-->
<delete id="deleteUser">
delete from user where id = #{id}
</delete>
<!--3.修改一条记录-->
<update id="updateUserById">
update user set name = "小张" where id = #{id}
</update>
<!--4.查询一条记录-->
<select id="findUserById" resultType="com.jd.wds.pojo.User" >
select * from user where id = #{id}
</select>
<!--5.查询所有记录-->
<select id="findAllUser" resultType="com.jd.wds.pojo.User">
select * from user
</select>

4. Description of mybatis core configuration file 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>
    <!-- 1.引入外部资源文件 -->
    <properties resource="jdbc.properties"></properties>
    <!-- 2.设置驼峰匹配 -->
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <!-- 3.设置包扫描(别名) -->
    <typeAliases>
        <package name="cn.itcast.pojo"/>
    </typeAliases>
    <!-- 4.配置环境:可以配置多个环境,default:配置某一个环境的唯一标识,表示默认使用哪个环境 -->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <!-- 配置连接信息 -->
                <property name="driver" value="${jdbc.driverClass}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <!-- 5.配置映射文件:用来配置sql语句和结果集类型等 -->
    <mappers>
        <mapper resource="UserMapper.xml"/>
    </mappers>
</configuration>

3. Mybatis obtains parameter values ​​in two ways

There are two ways for Mybatis to obtain parameter values: #{} and ${}
#{} Essence: Placeholder? Assignment
${} Essence: String splicing
(1) The method parameter of the mapper interface is a single literal type, which can be Get the parameter value with any name through #{} and ${} (${} need to add single quotes)

<select id="findUserByName" resultType="com.jd.wds.pojo.User">
    select * from user where name = '${name}'
    <!--select * from user where name = #{name}-->
</select>

(2) When there are multiple parameters of the mapper interface method, store them in two ways:
① use 0, 1... as the key, and use the parameter as the value;
② use param1, param2 as the key, and use the parameter as the value;
at this time, only Use {arg0} or {param1} to access the value (${} need to add single quotes)

<select id="checkLogin" resultType="com.jd.wds.pojo.User">
    select * from user where username=#{0} and password=#{1}
    <!--select * from user where username='${param1}' and password='${param2}'-->
</select>

(3) When there are multiple parameters of the mapper interface method, these parameters can be manually stored in a map collection, and only need to access the value in the form of a key through #{} and ${} ( ${} needs to be added apostrophe)

<select id="checkLoginByMap" resultType="com.jd.wds.pojo.User">
    <!--select * from user where username = #{username} and password = #{password}-->
    select * from user where username = '${username}' and password = '${password}'
</select>
@Test
public void checkLoginByMap(){
    
    
    SqlSession sqlSession = SqlSessionUtils.getSqlSession();
    ParameterMapper parameterMapper = sqlSession.getMapper(ParameterMapper.class);
    Map<String, Object> hashMap = new HashMap<>();
    hashMap.put("username","小张");
    hashMap.put("password","2356");
    User user = parameterMapper.checkLoginByMap(hashMap);
    System.out.println(user);
}

(4) The parameters of the mapper interface method are parameters of the entity type, and only need to access the attribute value through #{} or ${} ( ${} needs to be added with single quotes)

<insert id="insertUser" >
    <!--insert into user values(null,#{username},#{password},#{age},#{email})-->
    insert into user values(null,'${username}','${password}','${age}','${email}')
</insert>

(5) Use the @Param annotation to name the parameters. At this time, mybatis will put these parameters in a map collection and store them in two ways: ①
Use the value of the @param annotation as the key and the parameter as the value;
② Use param1, param2... is the key, and the parameter is the value;
at this time, you only need to use {arg0} or {param1} to access the value ( ${} needs to be enclosed in single quotes)

User checkLoginByParam(@Param("username")String username,@Param("password") String password);
<select id="checkLoginByParam" resultType="com.jd.wds.pojo.User">
    <!--select * from user where username = #{username} and password = #{password}-->
    select * from user where username = #{param1} and password = #{param2}
</select>

Guess you like

Origin blog.csdn.net/weixin_46081857/article/details/123286914