About the framework Mybatis------A brief introduction to the basics


insert image description here

1. What is Mybatis

  1. mybatis is an excellent java-based persistence layer framework. It encapsulates jdbc internally, so that developers only need to pay attention to the sql statement itself, and do not need to spend energy to deal with complicated processes such as loading drivers, creating connections, and creating statements.

  2. Mybatis configures various statements to be executed through xml or annotations, and generates the final executed sql statement by mapping the java object and the dynamic parameters of sql in the statement.

  3. Finally, the mybatis framework executes sql and maps the result to a java object and returns it. The ORM idea is used to solve the problem of entity and database mapping, and the jdbc is encapsulated to shield the underlying access details of the jdbc api, so that we can complete the persistent operation of the database without dealing with the jdbc api.

2. Quick Start of Mybatis

2.1 MyBatis development steps

  MyBatis official website address

MyBatis development steps:

  ①Add the coordinates of MyBatis

  ②Create user data table

  ③ Write the User entity class

  ④ Write the mapping file UserMapper.xml

  ⑤ Write the core file SqlMapConfig.xml

  ⑥ Write test classes

2.2 Environment Construction

  1. Import MyBatis coordinates and other related coordinates
<!--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.6</version>    
    <scope>runtime</scope>
</dependency>
<!--单元测试坐标-->
<dependency>    
    <groupId>junit</groupId>    
    <artifactId>junit</artifactId>    
    <version>4.12</version>    
    <scope>test</scope>
</dependency>
<!--日志坐标-->
<dependency>    
    <groupId>log4j</groupId>    
    <artifactId>log4j</artifactId>    
    <version>1.2.12</version>
</dependency>
  1. Create user data table

  2. Write User entity

  3. Write UserMapper mapping file

<?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="userMapper">    
	<select id="findAll" resultType="com.itheima.domain.User">        
		select * from User    
	</select>
</mapper>
  1. Write MyBatis core files
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN“ "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>    
	<environments default="development">        
		<environment id="development">            
			<transactionManager type="JDBC"/>            
			<dataSource type="POOLED">                
				<property name="driver" value="com.mysql.jdbc.Driver"/>
				<property name="url" value="jdbc:mysql:///test"/>                
				<property name="username" value="root"/>
				<property name="password" value="123456"/>            
			</dataSource>        
		</environment>    
	</environments>    
	
	<mappers> 
		<mapper resource="com/itheima/mapper/UserMapper.xml"/> 
	</mappers>
</configuration>
  1. write test code
//加载核心配置文件
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
//获得sqlSession工厂对象
SqlSessionFactory sqlSessionFactory = new            
                           SqlSessionFactoryBuilder().build(resourceAsStream);
//获得sqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//执行sql语句
List<User> userList = sqlSession.selectList("userMapper.findAll");
//打印结果
System.out.println(userList);
//释放资源
sqlSession.close();

3. Overview of the mapping file of MyBatis

insert image description here

4. Add, delete, modify and check operations of MyBatis

4.1 Insert data operation of MyBatis

  1. Write UserMapper mapping file
<mapper namespace="userMapper">    
	<insert id="add" parameterType="com.itheima.domain.User">        
		insert into user values(#{id},#{username},#{password})    
	</insert>
</mapper>
  1. Write the code that inserts the entity User
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new 
                        SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
int insert = sqlSession.insert("userMapper.add", user);
System.out.println(insert);
//提交事务
sqlSession.commit();
sqlSession.close();
  1. Insert operation attention problems

  • Insert statements use the insert tag

  • Use the parameterType property in the mapping file to specify the type of data to insert

  • Use #{entity attribute name} to refer to the attribute value in the entity in the Sql statement

  • The API used by the insert operation is sqlSession.insert("namespace.id", entity object);

  • The insert operation involves database data changes, so use the commit transaction displayed by the sqlSession object, ie sqlSession.commit()

4.2 MyBatis modification data operation

  1. Write UserMapper mapping file
<mapper namespace="userMapper">
    <update id="update" parameterType="com.itheima.domain.User">
        update user set username=#{username},password=#{password} where id=#{id}
    </update>
</mapper>

  1. Write the code that modifies the entity User
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
int update = sqlSession.update("userMapper.update", user);
System.out.println(update);
sqlSession.commit();
sqlSession.close();
  1. Modify the operation attention problem

  • Modify statements using the update tag

  • The API used by the modification operation is sqlSession.update("namespace.id", entity object);

4.3 MyBatis delete data operation

  1. Write UserMapper mapping file
<mapper namespace="userMapper">
    <delete id="delete" parameterType="java.lang.Integer">
        delete from user where id=#{id}
    </delete>
</mapper>

  1. Write code to delete data
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
int delete = sqlSession.delete("userMapper.delete",3);
System.out.println(delete);
sqlSession.commit();
sqlSession.close();
  1. Note on deletion

  • To delete statements use the delete tag

  • Use #{any string} to refer to a single parameter passed in the Sql statement

  • The API used by the delete operation is sqlSession.delete("namespace.id", Object);

Knowledge summary

增删改查映射配置与API:
查询数据: List<User> userList = sqlSession.selectList("userMapper.findAll");
    <select id="findAll" resultType="com.itheima.domain.User">
        select * from User
    </select>
添加数据: sqlSession.insert("userMapper.add", user);
    <insert id="add" parameterType="com.itheima.domain.User">
        insert into user values(#{id},#{username},#{password})
    </insert>
修改数据: sqlSession.update("userMapper.update", user);
    <update id="update" parameterType="com.itheima.domain.User">
        update user set username=#{username},password=#{password} where id=#{id}
    </update>
删除数据:sqlSession.delete("userMapper.delete",3);
    <delete id="delete" parameterType="java.lang.Integer">
        delete from user where id=#{id}
    </delete>

5. Overview of MyBatis core configuration files

5.1 MyBatis core configuration file hierarchy

insert image description here

5.2 MyBatis common configuration analysis

  1. environments tab
    insert image description here
    Among them, there are two types of transaction managers :
  • JDBC: This configuration uses JDBC's commit and rollback settings directly, relying on connections from the data source to manage transaction scope.

  • MANAGED: This configuration does almost nothing. It never commits or rolls back a connection, but lets the container manage the entire lifecycle of the transaction (eg, the context of a JEE application server). By default it closes the connection, however some containers don't want this, so set the closeConnection property to false to prevent its default closing behavior.

  Among them, there are three types of data sources :

  • UNPOOLED: The implementation of this data source just opens and closes the connection each time it is requested.

  • POOLED: This data source implementation utilizes the concept of a "pool" to organize JDBC connection objects.

  • JNDI: This data source is implemented for use in containers such as EJBs or application servers, which can configure the data source centrally or externally, and then place a reference to the JNDI context.

  1. mapper tag
该标签的作用是加载映射的,加载方式有如下几种:

•使用相对于类路径的资源引用,例如:
<mapper resource="org/mybatis/builder/AuthorMapper.xml"/>

•使用完全限定资源定位符(URL),例如:
<mapper url="file:///var/mappers/AuthorMapper.xml"/>

•使用映射器接口实现类的完全限定类名,例如:
<mapper class="org.mybatis.builder.AuthorMapper"/>

•将包内的映射器接口实现全部注册为映射器,例如:
<package name="org.mybatis.builder"/>
  1. Properties tab

  In actual development, it is customary to extract the configuration information of the data source into a properties file, which can load additionally configured properties files
insert image description here
4)typeAliases tag
insert image description here
insert image description here

Guess you like

Origin blog.csdn.net/S_yyuan/article/details/124124670
Recommended