CURD and MyBatis profiles

2.1 CURD

Add method in Dao interface

int insert(User user);

int deleteById(@Param("id") int id);

int update(User user);

User selectById(@Param("id") int id);

Add SQL in mapping file

<insert id="insert" parameterType="user">
    insert into user(id,name,pwd) values(#{id},#{name},#{pwd})
</insert>

<delete id="deleteById" parameterType="_int">
    delete from user where id = #{id}
</delete>

<update id="update" parameterType="user">
    update user set name = #{name},pwd = #{pwd} where id = #{id}
</update>

<select id="selectById" parameterType="_int" resultType="user">
    select id,name,pwd from user where id = #{id}
</select>
@Test
public void tets2(){
    SqlSession sqlSession = MyBatisUtil.getSqlSession();
    UserDao userDao = sqlSession.getMapper(UserDao.class);
    userDao.insert(new User(4,"wyz","wyz"));
    sqlSession.close();
}
@Test
public void test3(){
    SqlSession sqlSession = MyBatisUtil.getSqlSession();
    UserDao userDao = sqlSession.getMapper(UserDao.class);
    userDao.update(new User(4,"wyz111","wyz1111"));
    sqlSession.close();
}
@Test
public void test4(){
    SqlSession sqlSession = MyBatisUtil.getSqlSession();
    UserDao userDao = sqlSession.getMapper(UserDao.class);
    userDao.deleteById(4);
    sqlSession.close();
}
@Test
public void test5(){
    SqlSession sqlSession = MyBatisUtil.getSqlSession();
    UserDao userDao = sqlSession.getMapper(UserDao.class);
    User user = userDao.selectById(1);
    System.out.println(user);
    sqlSession.close();
}

2.2 MyBatis configuration file

The MyBatis configuration file contains settings and attribute information that will deeply affect MyBatis behavior. The top-level structure of the configuration document is as follows:

properties

These properties can be configured externally and can be replaced dynamically. You can configure these properties either in a typical Java properties file or in a child element of the properties element.

<properties resource="org/mybatis/example/config.properties">
  <property name="username" value="dev_user"/>
  <property name="password" value="F2Fa3!33TYyg"/>
</properties>

The set attributes can be used in the whole configuration file to replace the attribute values that need to be dynamically configured. For example:

<dataSource type="POOLED">
  <property name="driver" value="${driver}"/>
  <property name="url" value="${url}"/>
  <property name="username" value="${username}"/>
  <property name="password" value="${password}"/>
</dataSource>

If a property is configured in more than one place, MyBatis will be loaded in the following order:

  • First read the properties specified in the properties element body.
  • Then read the property file under the classpath according to the resource attribute in the properties element, or read the property file according to the path specified by the url attribute, and overwrite the previously read property with the same name.
  • Finally, read the attribute passed as a method parameter and overwrite the previously read attribute with the same name.

Therefore, the attributes passed through the method parameters have the highest priority, followed by the configuration file specified in the resource/url attribute, and the attributes specified in the properties element have the lowest priority.

settings

These are extremely important tuning settings in MyBatis, which will change the runtime behavior of MyBatis. The following table describes the meaning and default values of each setting in the setting.

An example of a fully configured settings element is as follows:

<settings>
  <setting name="cacheEnabled" value="true"/>
  <setting name="lazyLoadingEnabled" value="true"/>
  <setting name="multipleResultSetsEnabled" value="true"/>
  <setting name="useColumnLabel" value="true"/>
  <setting name="useGeneratedKeys" value="false"/>
  <setting name="autoMappingBehavior" value="PARTIAL"/>
  <setting name="autoMappingUnknownColumnBehavior" value="WARNING"/>
  <setting name="defaultExecutorType" value="SIMPLE"/>
  <setting name="defaultStatementTimeout" value="25"/>
  <setting name="defaultFetchSize" value="100"/>
  <setting name="safeRowBoundsEnabled" value="false"/>
  <setting name="mapUnderscoreToCamelCase" value="false"/>
  <setting name="localCacheScope" value="SESSION"/>
  <setting name="jdbcTypeForNull" value="OTHER"/>
  <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
</settings>

Type aliases

Type alias sets an abbreviated name for a Java type. It is only used for XML configuration and is intended to reduce redundant fully qualified class name writing. For example:

<typeAliases>
  <typeAlias alias="Author" type="domain.blog.Author"/>
  <typeAlias alias="Blog" type="domain.blog.Blog"/>
  <typeAlias alias="Comment" type="domain.blog.Comment"/>
  <typeAlias alias="Post" type="domain.blog.Post"/>
  <typeAlias alias="Section" type="domain.blog.Section"/>
  <typeAlias alias="Tag" type="domain.blog.Tag"/>
</typeAliases>

When configured in this way, blog can be used in any domain blog. Blog place.

You can also specify a package name. MyBatis will search for the required Java beans under the package name, such as:

<typeAliases>
  <package name="domain.blog"/>
</typeAliases>

Each one is in the package domain The Java Bean in the blog will use the initial lowercase unqualified class name of the bean as its alias without annotation. For example, domain blog. The alias of author is author; If there is an annotation, the alias is its annotation value. See the following example:

@Alias("author")
public class Author {
    ...
}

Here are some built-in type aliases for common Java types. They are case insensitive. Note that in order to deal with the naming repetition of the original type, a special naming style is adopted.

alias Type of mapping
_byte byte
_long long
_short short
_int int
_integer int
_double double
_float float
_boolean boolean
string String
byte Byte
long Long
short Short
int Integer
integer Integer
double Double
float Float
boolean Boolean
date Date
decimal BigDecimal
bigdecimal BigDecimal
object Object
map Map
hashmap HashMap
list List
arraylist ArrayList
collection Collection
iterator Iterator

Environment configurations

MyBatis can be configured to adapt to a variety of environments. This mechanism helps to apply SQL mapping to a variety of databases. In reality, there are many reasons to do so. For example, development, testing and production environments need different configurations; Or you want to use the same SQL mapping in multiple production databases with the same Schema. There are many similar usage scenarios.

However, remember that although multiple environments can be configured, only one environment can be selected for each SqlSessionFactory instance.

Therefore, if you want to connect two databases, you need to create two SqlSessionFactory instances, one for each database. If there are three databases, you need three instances, and so on. It's easy to remember:

  • Each database corresponds to a SqlSessionFactory instance

To specify which environment to create, simply pass it as an optional parameter to SqlSessionFactoryBuilder. The two method signatures that can accept environment configuration are:

SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader, environment);
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader, environment, properties);

The environments element defines how the environment is configured.

<environments default="development">
  <environment id="development">
    <transactionManager type="JDBC">
      <property name="..." value="..."/>
    </transactionManager>
    <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>

Note some key points:

  • The default environment ID (for example, default="development").
  • The environment ID defined by each environment element (for example: id="development").
  • Configuration of transaction manager (for example: type="JDBC").
  • Configuration of data source (for example: type="POOLED").

The default environment and environment ID are as the name suggests. The environment can be named at will, but make sure that the default environment ID matches one of the environment IDs.

Transaction manager

There are two types of transaction managers in MyBatis (that is, type="[JDBC|MANAGED]):

  • JDBC – this configuration directly uses JDBC's commit and rollback facility, which relies on the connection obtained from the data source to manage the transaction scope.
  • MANAGED – this configuration does little. It never commits or rolls back a connection, but lets the container manage the whole life cycle of the transaction (such as the context of JEE application server). By default, it closes the connection. However, some containers do not want the connection to be closed, so you need to set the closeConnection property to false to prevent the default closing behavior.

Data source

The dataSource element uses the standard JDBC data source interface to configure the resources of the JDBC connection object.

  • Most MyBatis applications configure the data source as shown in the example. Although the data source configuration is optional, you must configure the data source if you want to enable the delayed load feature.

There are three built-in data source types (that is, type="[UNPOOLED|POOLED|JNDI])

mappers

Now that the behavior of MyBatis has been configured by the above elements, we will now define the SQL mapping statement. But first, we need to tell MyBatis where to find these statements. Java does not provide a good solution for automatically finding resources, so the best way is to directly tell MyBatis where to find the mapping file.

<!-- Use resource references relative to Classpaths -->
<mappers>
  <mapper resource="org/mybatis/builder/AuthorMapper.xml"/>
  <mapper resource="org/mybatis/builder/BlogMapper.xml"/>
  <mapper resource="org/mybatis/builder/PostMapper.xml"/>
</mappers>
<!-- Use fully qualified resource locators( URL) -->
<mappers>
  <mapper url="file:///var/mappers/AuthorMapper.xml"/>
  <mapper url="file:///var/mappers/BlogMapper.xml"/>
  <mapper url="file:///var/mappers/PostMapper.xml"/>
</mappers>
<!-- Use the mapper interface to implement the fully qualified class name of the class -->
<mappers>
  <mapper class="org.mybatis.builder.AuthorMapper"/>
  <mapper class="org.mybatis.builder.BlogMapper"/>
  <mapper class="org.mybatis.builder.PostMapper"/>
</mappers>
<!-- Register all the mapper interface implementations in the package as mappers -->
<mappers>
  <package name="org.mybatis.builder"/>
</mappers>

Keywords: Mybatis

Added by LanHorizon on Sun, 06 Mar 2022 12:22:23 +0200