mybatis uses xml to add delete and check code parsing

  • 2021-01-25 07:34:49
  • OfStack

MyBatis is a persistence layer framework that supports normal sql queries, stored procedures, and high-level mapping.

MyBatis eliminates almost all manual setting of JDBC code and parameters and the retrieval encapsulation of result sets.

MyBatis can use simple XML or annotations for configuration and raw mapping to map interfaces and Java's POJO(Plain Old Java Objects plain Java objects) to records in the database.

Each Mybatis application has an instance of an sqlSessionFactory object at its core.

Instances of sqlSessionFactory objects are available through sqlSessionFactoryBuilder objects. sqlSessionFactoryBuilder objects can be built from an xml configuration file or from an instance of the Configuration class prepared in previous usage management.

[Example: Getting sqlSessionFactory using configuration class]


DataSource dataSource = BlogDataSourceFactory.getBlogDataSource();
TransactionFactory transactionFactory = new JdbcTransactionFactory();
// The environment 
Environment environment = new Environment("development", transactionFactory, dataSource);
Configuration configuration = new Configuration(environment);
// Mapper class 
configuration.addMapper(BlogMapper.class);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);

Note that the configuration in this case is to add the mapper class. The mapper classes are Java classes. These classes contain annotations for SQL mapping statements to avoid dependencies on xml files, but xml mappings are still required for most high-level mappings (e.g., nested join mappings).

For this reason, if xml configuration file exists, MyBatis will automatically find and load one peer XML files (in this case, based on the classpath BlogMapper. class class name of the class, then BlogMapper. xml will be loaded � class and XML in with a file directory. If not, you need to manually configure to load xml).

[1] basic add, delete and change check xml configuration


<?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.web.mapper.userMapper">

   <!--  Can be solved model Property name and data table column The column name is not 1 To the question  jdbcType1 Need to uppercase  -->  
   <resultMap type="User" id="UserMap">
    <id property="id" column="id" javaType="int" jdbcType="INTEGER"/>
    <result property="name" column="username" javaType="string" jdbcType="VARCHAR"/>
    <result property="age" column="age" javaType="int" jdbcType="INTEGER"/>
   </resultMap>

   <!--
    Notice that this is result If the column == property  You can just return it Java object . 
    If the property name is different from the column name 1 The solution is as follows: 
   1.  use resultMap; 
   2. return hashmap ; 
   3. Query statements use aliases 
   -->
   <select id="getUser" parameterType="int" resultMap="UserMap">
    select * from t_user where id=#{id}
   </select>

   <delete id="deleteUser" parameterType="int" >
    delete from t_user where id=#{id}
   </delete>


   <update id="updateUser" parameterType="User" >
    update t_user set username=#{name},age=#{age} where id=#{id}
   </update>

   <insert id="insertUser" parameterType="User" >
    insert into t_user(username,age) values(#{name},#{age})
   </insert>

   <!-- model's attr(name) different from column(username), so the result use UserMap -->

   <select id="getUsers" resultMap="UserMap">
    select * from t_user
   </select>
</mapper>

Register with mybatis.xml [this configuration file will not be required when combined with spring]

mybatis configuration file


<?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"/>

  <!--  Configure the alias for the entity class  -->
  <typeAliases>
    <!-- <typeAlias type="com.web.model.User" alias="User"/> -->
    <package name="com.web.model"/>
  </typeAliases>
<!-- 
  development :  Development mode 
  work :  Working mode 
 -->
  <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="com/web/mapper/userMapper.xml"/>
    <mapper resource="com/web/mapper/orderMapper.xml"/>
    <mapper class="com.web.mapperClass.UserMapper"/>
  </mappers>
</configuration>

[2] Get session through SqlSessionFactory

The xml file is used here to get sqlSessionFactory and sqlSession.


public static SqlSessionFactory getFactory(){
	/* flow the src dir*/
	String resource = "mybatis.xml";
	/*MybatisUtils.class.getResourceAsStream(resource)----- it's wrong !!!!
     * please distinguish the two up and down 
     * */
	InputStream inputStream = MybatisUtils.class.getClassLoader().getResourceAsStream(resource);
	SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
	return factory;
}
SqlSession session = factory.openSession(true);
// Default manual submission; 
/*
   Two solutions: 
  1.factory.opensession(true);
  2.session.commit();
  */

[3] add, delete and change check the background test code


/*use sql xml not annotation*/
@Test
  public void testAdd(){
	SqlSession session = MybatisUtils.getFactory().openSession();
	String statement = "com.web.mapper.userMapper.insertUser";
	/*return the effect rows*/
	int insert= session.insert(statement, new User("tom5", 15));
	/*default is not auto commit*/
	session.commit(true);
	session.close();
	System.out.println("effect rows.."+insert);
}
@Test
  public void testSelect(){
	/*set auto commit ,which equals to the above*/
	SqlSession session = MybatisUtils.getFactory().openSession(true);
	String statement = "com.web.mapper.userMapper.getUser";
	/*return the effect rows*/
	User user = session.selectOne(statement, 3);
	System.out.println("effect rows.."+user);
}
@Test
  public void testUpdate(){
	SqlSession session = MybatisUtils.getFactory().openSession(true);
	String statement = "com.web.mapper.userMapper.updateUser";
	/*return the effect rows*/
	int update= session.update(statement, new User(3,"tom4", 13));
	System.out.println("effect rows.."+update);
}
@Test
  public void testDelete(){
	SqlSession session = MybatisUtils.getFactory().openSession();
	String statement = "com.web.mapper.userMapper.deleteUser";
	/*return the effect rows*/
	int delete= session.delete(statement, 6);
	/* commit by yourself*/
	session.commit();
	System.out.println("effect rows.."+delete);
	session.close();
}
@Test
  public void testGetUsers(){
	SqlSession session = MybatisUtils.getFactory().openSession();
	String statement = "com.web.mapper.userMapper.getUsers";
	/*return the List<User>*/
	List<User> users= session.selectList(statement);
	session.commit();
	System.out.println("effect rows.."+users);
	session.close();
}

Tips:

parameterType and resultType are hashmap:

mapper.xml :

<select id="getUserForMap" parameterType="hashmap" resultType="hashmap">
    select * from c_user where id=#{id};
  </select>
test code :

@Test
  public void getUserForMap(){
	SqlSession session = MybatisUtils.getFactory().openSession();
	String statement = "com.web.mapper.userMapper.getUserForMap";
	HashMap<String, Object> map = new HashMap<String, Object>();
	map.put("id", 1);
	/*return the effect rows*/
	Object selectOne = session.selectOne(statement, map);
	/*default is not auto commit*/
	session.commit(true);
	session.close();
	System.out.println("effect rows.."+selectOne+" ,class :"+selectOne.getClass());
}
result as follows :

effect rows..{id=1, age=12, name=luli} ,class :class java.util.HashMap

To sum up, ES96en will automatically parse and encapsulate according to parameter types and result types.

[Extend the basic method]

[1] Paging list


 <select id="getListPage" parameterType="hashmap" resultMap="siteExtendDaoMap">
    select id,site_id,site_name,site_number,province,city,area,address,internal_number,longitude,latitude
    from tb_site
    -- Using dynamic sql
    <trim prefix="where" prefixOverrides="AND |OR "> 
      <if test="checkState!= null and checkState!=''">
        and check_state = #{checkState,jdbcType=INTEGER}
      </if>
      <if test="siteId!= null and siteId!=''">
        and site_id like concat('%',#{siteId},'%')
      </if>
      <if test="siteName!= null and siteName!=''">
        and site_name like concat('%',#{siteName},'%')
      </if>
      <if test="siteNumber!= null and siteNumber!=''">
        and site_number like concat('%', #{siteNumber},'%')
      </if>
      <if test="province!= null and province!=''">
        and province = #{province}
      </if>
      <if test="city!= null and city!=''">
        and city = #{city}
      </if>
      <if test="area!= null and area!=''">
        and area = #{area}
      </if>
    </trim> 
    -- To add sorting 
    <if test="sortname!= null and sortname!='' and sortorder!= null and sortorder!=''">
      order by ${sortname} ${sortorder}
    </if>
    -- Add paging 
    limit ${(page-1)*pagesize},${pagesize}
 </select>

【 2 】 � delete method based on object or Id

If the argument is pojo,mybatis will automatically fetch id from the object;


  <delete id="delete" parameterType="User">
    delete from tb_user
    where
    id = #{id} 
  </delete>

  <delete id="deleteById" parameterType="long">
    delete from tb_user
    where
    id = #{id} 
  </delete>

[3] delete data according to id list


<?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.web.mapper.userMapper">

   <!--  Can be solved model Property name and data table column The column name is not 1 To the question  jdbcType1 Need to uppercase  -->  
   <resultMap type="User" id="UserMap">
    <id property="id" column="id" javaType="int" jdbcType="INTEGER"/>
    <result property="name" column="username" javaType="string" jdbcType="VARCHAR"/>
    <result property="age" column="age" javaType="int" jdbcType="INTEGER"/>
   </resultMap>

   <!--
    Notice that this is result If the column == property  You can just return it Java object . 
    If the property name is different from the column name 1 The solution is as follows: 
   1.  use resultMap; 
   2. return hashmap ; 
   3. Query statements use aliases 
   -->
   <select id="getUser" parameterType="int" resultMap="UserMap">
    select * from t_user where id=#{id}
   </select>

   <delete id="deleteUser" parameterType="int" >
    delete from t_user where id=#{id}
   </delete>


   <update id="updateUser" parameterType="User" >
    update t_user set username=#{name},age=#{age} where id=#{id}
   </update>

   <insert id="insertUser" parameterType="User" >
    insert into t_user(username,age) values(#{name},#{age})
   </insert>

   <!-- model's attr(name) different from column(username), so the result use UserMap -->

   <select id="getUsers" resultMap="UserMap">
    select * from t_user
   </select>
</mapper>
0

[4] getRows

Usually used in conjunction with getListPage.


<?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.web.mapper.userMapper">

   <!--  Can be solved model Property name and data table column The column name is not 1 To the question  jdbcType1 Need to uppercase  -->  
   <resultMap type="User" id="UserMap">
    <id property="id" column="id" javaType="int" jdbcType="INTEGER"/>
    <result property="name" column="username" javaType="string" jdbcType="VARCHAR"/>
    <result property="age" column="age" javaType="int" jdbcType="INTEGER"/>
   </resultMap>

   <!--
    Notice that this is result If the column == property  You can just return it Java object . 
    If the property name is different from the column name 1 The solution is as follows: 
   1.  use resultMap; 
   2. return hashmap ; 
   3. Query statements use aliases 
   -->
   <select id="getUser" parameterType="int" resultMap="UserMap">
    select * from t_user where id=#{id}
   </select>

   <delete id="deleteUser" parameterType="int" >
    delete from t_user where id=#{id}
   </delete>


   <update id="updateUser" parameterType="User" >
    update t_user set username=#{name},age=#{age} where id=#{id}
   </update>

   <insert id="insertUser" parameterType="User" >
    insert into t_user(username,age) values(#{name},#{age})
   </insert>

   <!-- model's attr(name) different from column(username), so the result use UserMap -->

   <select id="getUsers" resultMap="UserMap">
    select * from t_user
   </select>
</mapper>
1

conclusion

The above is this article about mybatis using xml to add, delete and check the code analysis of all the content, I hope to help you. Interested friends can continue to refer to the site of other related topics, if there are shortcomings, welcome to leave a message to point out. Thank you for your support!


Related articles: