Mybatis uses xml for addition, deletion, modification, and query code parsing. mybatisxml

Source: Internet
Author: User

Mybatis uses xml for addition, deletion, modification, and query code parsing. mybatisxml

MyBatis is a persistent layer framework that supports common SQL queries, stored procedures, and advanced ing.

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

MyBatis can use simple XML or annotations for configuration and original ing, and map interfaces and Java POJO (Plain Old Java Objects common Java Objects) into records in the database.

Each Mybatis application is centered on an instance of a sqlSessionFactory object.

An instance of the sqlSessionFactory object can be obtained through the sqlSessionFactoryBuilder object. The sqlSessionFactoryBuilder object can be used to build the sqlSessionFactory object through the xml Configuration file or from the Configuration class instance prepared in the previous use management.

[Example: Use the configuration class to obtain sqlSessionFactory]
DataSource dataSource = BlogDataSourceFactory. getBlogDataSource (); TransactionFactory transactionFactory = new JdbcTransactionFactory (); // Environment environment Environment = new environment ("development", transactionFactory, dataSource); Configuration configuration Configuration = new Configuration (Environment ); // class configuration. addMapper (BlogMapper. class); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder (). build (configuration );

Note that in this case, the configuration is to add the Mapper class. The er Class is a Java class that contains the annotation of the SQL ing statement to avoid dependency on the xml file. However, xml ing is still required for most advanced mappings (such as nested join ing.

For this reason, if an xml configuration file exists, MyBatis will automatically find and load a peer-to-peer XML file (in this case, it is based on BlogMapper in the class path. class name, then BlogMapper. xml will be loaded-that is, the class and XML are in the same file directory. If not, you need to manually configure and load xml ).

[1] add, delete, modify, and query xml configurations
<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE mapper PUBLIC "-// mybatis.org//DTD Mapper 3.0 //" http://mybatis.org/dtd/mybatis-3-mapper.dtd "> <mapper namespace =" com. web. mapper. userMapper "> <! -- Solve the inconsistency between the model attribute name and the column name in the data table. jdbcType must be capitalized --> <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> <! -- Note the result here. If column = property, Java object can be directly returned. If the attribute name is different from the column name, the solution is as follows: 1. use resultMap; 2. returns hashmap; 3. query statement alias --> <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 = "insertU Ser "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 to mybatis. xml [this configuration file is not 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 object class alias --> <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] obtain the session through SqlSessionFactory

Here, we use the xml file to obtain 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); // Manual submission by default;/* two solutions: 1. factory. opensession (true); 2. session. commit ();*/
[3] add, delete, modify, and query 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

In conclusion, mybatis automatically parses and encapsulates the data based on the parameter type and result type.

[Basic Extension 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, longpolling, latitude from tb_site -- use 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> -- add a sort <if test = "sortname! = Null and sortname! = ''And sortorder! = Null and sortorder! = ''"> Order by $ {sortname }$ {sortorder} </if> -- add pagination limit $ {(page-1) * pagesize }, $ {pagesize} </select>
[2] Delete method-based on object or Id

If the parameter is pojo, mybatis automatically obtains the 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] deleting data based on the id list
<Delete id = "deleteByIds"> delete from tb_user where id in -- use foreach <foreach collection = "list" item = "id" open = "(" separator = ", "close =") ">#{ id} </foreach> </delete>
[4] getRows

It is usually used together with getListPage.

<select id="getRows" parameterType="hashmap" resultType="long">    select count(*) from tb_sys_role    <if test="keySysRole!= null">      <trim prefix="WHERE" prefixOverrides="AND |OR ">        <if test="keySysRole.id!= null">        and id = #{keySysRole.id}        </if>        <if test="keySysRole.name!= null and keySysRole.name!=''">        and name = #{keySysRole.name}        </if>        <if test="keySysRole.available!= null and keySysRole.available!=''">        and available = #{keySysRole.available}        </if>      </trim>    </if>  </select>
Summary

The above is all the content about how to use xml to add, delete, modify, and query code parsing in mybatis. I hope this will help you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.