MyBatis is a persistence layer framework that supports ordinary SQL queries, stored procedures and advanced mapping.
MyBatis eliminates manual settings of almost all JDBC code and parameters and search encapsulation of the result set.
MyBatis can use simple XML or annotations for configuration and original mapping, mapping interfaces and Java's POJO (Plain Old Java Objects) into records in the database.
Each Mybatis application takes an instance of the sqlSessionFactory object as the core.
An instance of the sqlSessionFactory object can be obtained through the sqlSessionFactoryBuilder object. The sqlSessionFactoryBuilder object can be built through the XML configuration file or from the Configuration class instance prepared in previous usage management.
DataSource dataSource = BlogDataSourceFactory.getBlogDataSource();TransactionFactory transactionFactory = new JdbcTransactionFactory();//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 in this case the configuration is to add the mapper class. Mapper classes are Java classes, which contain annotations of SQL mapping statements to avoid dependencies in xml files, but xml mapping is still required in most advanced mappings (such as nested join mapping).
For this reason, if an xml configuration file exists, MyBatis will automatically find and load a peer XML file (in this case, based on the class name of the BlogMapper.class class under the class path, then BlogMapper.xml will be loaded that is, class and XML are in the same file directory. If it is not, you need to manually configure the loading of xml).
<?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"> <!-- It can solve the problem that the model property name is inconsistent with the column 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, you can directly return the Java object. If the attribute name is inconsistent with the column name, the solution is as follows: 1. Use resultMap; 2. Return hashmap; 3. Use alias for the query statement--> <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 to mybatis.xml [When combined with spring, this configuration file will not be required]
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 entity class alias--> <typeAliases> <!-- <typeAlias type="com.web.model.User" alias="User"/> --> <package name="com.web.model"/> </typeAliases><!-- development: Development mode work: Work 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/> </mappers></configuration>Here we use the xml file to get the 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 manually submit;/* Two solutions: 1.factory.opensession(true); 2.session.commit(); */ /*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();}parameterType and resultType are hashmap:
<select id="getUserForMap" parameterType="hashmap" resultType="hashmap"> select * from c_user where id=#{id}; </select> @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());} effect rows..{id=1, age=12, name=luli} ,class :class java.util.HashMapTo sum up, it can be seen that mybatis will automatically parse and encapsulate according to the parameter type and result type.
<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 --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 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 sort<if test="sortname!= null and sortname!='' and sortorder!= null and sortorder!= null and sortorder!=''"> order by ${sortname} ${sortorder} </if> --Add paging limit ${(page-1)*pagesize},${pagesize} </select>If the parameter is pojo, mybatis will automatically obtain 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> <delete id="deleteByIds"> delete from tb_user where id in --Use foreach <foreach collection="list" item="id" open="(" separator=","close=")"> #{id} </foreach> </delete>Usually used in conjunction 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>The above is all the content of this article about mybatis using xml for code analysis. I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!