Mybatis frame - Core profile tag set, sqlSession factory mode, mapper proxy mode

mybatis framework


Outline

mybatis is an excellent java-based persistence framework, which encapsulates the internal jdbc, so developers only need to focus sql statement itself, without the need to spend energy to handle the loading drive, create a connection, create a statement such as complicated process
face questions: mybatis persistence framework is based on semi ORM Thought - ORM Object Relational mapping: let entity class and generates a mapping relationship table, the operation equivalent to the operation entity type table

Development steps

  1. Create a maven repository project, add dependencies
  2. Write entity class
  3. Write mapping configuration file (the same package with the same name)
  4. Write core configuration file
  5. Write test classes
    • Load Profile
    • Creating sqlSessionFactory
    • Creating sqlSession
    • sqlSession call methods
    • Release resources

      Label Settings core configuration file

      All labels, tags and arranged in accordance with the established order of configuration
      properties ?, settings ?, typeAliases ?, typeHandlers ?, objectFactory ?, objectWrapperFactory ?, reflectorFactory ?, plugins ?, environments ?, databaseIdProvider ?, mappers?

1. properties Tags: load an external configuration file resource properties

Two properties:

  • resource attribute: used to specify the location of the profile properties, required profile must be in class path resource = "jdbcConfig.properties"
  • url attribute: Uniform Resource Locator http://localhost:8080/mystroe/CategoryServlet

    2. typeAliases Tags: custom aliases

    Two definitions:
  • Single alias definitions
    <typeAlias alias="user" type="com.itheima.domain.User"/>
  • Batch alias definitions, scanning the entire package under the category, an alias for the class name (first letter uppercase or lowercase can)
    <package name="com.itheima.domain"/>

    3. environments Tags: configuration database environment and supports multi-environment configuration


<!--.数据源环境-->
    <environments default="development">
        <environment id="development">
            <!--事物类型 jdbc -->
            <transactionManager type="JDBC"></transactionManager>
            <!--使用mybatis提供的连接池-->
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>

<environments default="development">Specify the default environment name
<environments id="development">specifies the name of the current environment
<transactionManager type="JDBC">to specify transaction type is jdbc
<dataSource type="POOLED">specify the current connection pool data source type is
<proprety name= value=>the basic data source configuration parameters

Things Manager (transactionManager) type two

  • JDBC : This configuration is the direct use of JDBC commit and rollback setting, it relies on connections obtained from the data source to manage the scope of things
  • Managed : This configuration almost did not do anything. It never commit or roll back a connection, but let the container to manage the entire life cycle of a transaction (such as context JEE application server). By default, it will close the connection, however, some containers do not want this, so you need to closeConnection property to false to prevent its default behavior is closed.
    Data source (the dataSource) type three
  • unpooled: opening and closing the connection to achieve this but each data source is requested.
  • The POOLED : to achieve using the concept of "pool" of the JDBC connection object to organize.
  • JNDI: In order to achieve such a EJB server application or use of such a container, the container may be centralized or configuration data in an external source, and then placed in a JNDI context reference.

    4. mapper tags: a mapper function: load map

  • Method 1: Use resource with respect to a reference path
    <mapper resource="org/mybatis/builder/AuthorMapper.xml"/>
  • Second way: fully qualified resource locator (URL)
    <mapper url="file:///var/mappers/AuthorMapper.xml"/>
  • Three ways: using the fully qualified class name of the class interface mapper
    <mapper class="org.mybatis.builder.AuthorMapper"/>
  • Four ways: mapping interface within the package as a whole register mapper mapper proxy only in development, equivalent to sweep the package, the package all the specified implementation class conventional manner
    <package name="org.mybatis.builder"/>

MyBatis corresponding API Introduction sqlSession

1.sqlSession plant builder (builder mode)SqlSessionFactory build(InputSream inputStream)

Construction of a SqlSessionFactory object via an input stream file loaded core mybatis

//String resource = "org/mybatis/builder/mybatis-congfig.xml";
InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();//构建者设计模式
SqlSessionFactory factory = builder.build(inputStream);

2.sqlSession factory object (factory mode)

The role of the factory is to build sqlSession session object. The factory pattern is to decouple and

How to create all SqlSessionFactory SqlSession instance method. Commonly used are the following two:
| method | interpretation |
|: ------: |: ------------ |
| openSession | enabled by default for a transaction, but the transaction does not automatically submitted, which means you need to manually submit the transaction, update data will be persisted to the database |
| openSession (boolean autoCommit) | argument is whether to automatically submit, true (automatic commit) |

3.sqlSession session object (important)

SqlSession instance is the most powerful class in MyBatis in. Here you will see all the statement is executed commit or rollback transactions and acquire mapper instances method.

SqlSession sqlSession = sqlSessionFactory.openSession(true);

  • Sql statement execution method:
//查询
<T> T selectOne(String statement, Object parameter) 
<E> List<E> selectList(String statement, Object parameter) 
//增 删 改
int insert(String statement, Object parameter) 
int update(String statement, Object parameter) 
int delete(String statement, Object parameter)
  • Method of operating a transaction:
void commit()  
void rollback() 

mapper proxy mode

1.Mybatis of Dao layer implementation in two ways:

1-传统开发方式: 手动对Dao层进行实现,在Dao层编写接口,接口实现类,实现方法
2-代理开发方式: 编写Mapper 接口(相当于Dao 接口),由Mybatis 框架根据接口定义创建接口的动态代理对象,代理对象的方法体同上边Dao接口实现类方法。

2.mapper agent development requirements (specification):

mapper interface development need to follow norms Examples
1- interfaces and mapping files for the same package with the same name java.cn.ppvir.dao.UserMapper.java and resources / cn / ppvir / dao / UserMapper.xml
2- persistence mapping configuration namespace attribute value mapper tag must be fully qualified class name of the interface persistence layer public interface Usermapper{}---<mapper namespace='cn.ppvir.dao.UserMapper'>
3-sql statement label configuration <select><insert><delete><update>id attribute must be durable layer interface and a method of the same name User findById(Int id)---<select id="findById">
4-parameterType to pass parameters and the same type of interface User findById(int id)---<select parameterType="int">
5-resultType and return value of the result to the same type interface User findById(int id)---<select resultType="user">

3. code shows (using the mapper proxy Development)

Distinguish fuzzy query $ {} and {} of #

#{}表示一个占位符
#{}可以实现prepareStatment向占位符中设置值,自动进行JDBC和java类型转换,防止sql注入
#{}可以接收简单类型值或pojo属性值,如果parameterType传输基本数据类型,值随便写

${}表示拼接sql串
${}是将传入的参数原样拼接在sql中,不进行jdbc类型转换
${}可以接收简单类型值或pojo属性值,如果parameterType传输基本数据类型,${}括号中只能是value

  1. pom
  2. Core configuration file sqlMapConfig.xml
<?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>
<!--1.引入配置文件-->
    <properties resource="jdbc.properties"/>
<!--2.别名typeAliases-->
    <typeAliases>
        <!--单个别名定义-->
        <typeAlias type="it.ppvir.domain.User" alias="user"></typeAlias>
        <!--批量别名定义-->
        <package name="it.ppvir.domain"/>
    </typeAliases>
<!--3.数据源环境-->
    <environments default="develop">
        <environment id="develop">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
<!--4.加载映射文件-->
    <mappers>
        <!--方式一:    使用相对于类路径的资源引用-->
        <mapper resource="it/ppvir/dao/UserMapper.xml"/>
        <!--方式四:将包内的映射器接口实现全部注册为映射器-->
        <!--<package name="it.ppvir.dao"/>-->
    </mappers>
</configuration>
  1. Entity classes get set toString
public class User {
    private int id;
    private String username;
    private String password;
  1. Mapping configuration file UserMapper.xml resources / it / ppvir / dao / Usermapper.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="it.ppvir.dao.UserMapper">
<!--查询所有 List<User> findAll();-->
    <select id="findAll" resultType="user">
        select * from users;
    </select>
<!--通过id 查询用户User findUserById(int id);-->
    <select id="findUserById" parameterType="int" resultType="user">
        select * from users where id=#{id}
    </select>

<!--添加user void addUser(User user);-->
    <insert id="addUser" parameterType="user">
          <!--keyProperty:将添加成功后的id值查询出来封装到那个实体属性上
           resultType:主键类型
           order:SELECT LAST_INSERT_ID()执行时机是在insert后面-->
        <selectKey keyProperty="id" keyColumn="id" resultType="int" order="AFTER">
            SELECT LAST_INSERT_ID()
        </selectKey>
        insert into users VALUES (#{id},#{username},#{password})
    </insert>

<!--删除用户  void delUserById(int id);-->
    <delete id="delUserById" parameterType="int">
        DELETE FROM users where id=#{id}
    </delete>

<!--修改用户信息  void modUserById(int id);-->
    <update id="modUserById" parameterType="user">
        UPDATE  users SET username=#{username} where id=#{id}
    </update>

<!--模糊查询  List<User> findUserByLikeUsername(String username);-->
    <select id="findUserByLikeUsername" resultType="user" parameterType="String">
        select * from users where username like '${value}'
    </select>
</mapper>
  1. Interface package interfaces with the same name and the method name mapping id and returns the same value and the value resultType same parameter and the same ParameterType
public interface UserMapper {
    //插入数据 addUser
    void addUser(User user);
    //查询所有用户 findAll
    List<User> findAll() throws IOException;
    //查询用户通过id findUserById
    User findUserById(int id);
    //通过Id删除用户 delUserById
    void delUserById(int id);
    //通过id修改用户信息 modUserById
    void modUserById(User user);
    //模糊查询
    List<User> findUserByLikeUsername(String username);
}
  1. Test category
public class UserMapperTest {
    /**
     * 接口实现类测试 传统方法
     * @throws IOException
     */
    @Test
    public void test01() throws IOException {
        UserMapper userMapper = new UserMapperImpl();
        List<User> users = userMapper.findAll();
        System.out.println(users);
    }
    /**
     *   mapper代理方式 实现findAll方法
     */
    @Test
    public void test02() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = factory.openSession();

        //使用mapper代理方式
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);//通过接口获取mapper代理对象
        List<User> users = mapper.findAll();//使用代理对象调用接口的方法
        System.out.println(users);
    }
    @Test
    /**
     *  mapper代理方式 实现 User findUserById(int id)
     */
    public void test03() throws IOException {
        InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //mapper代理
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.findUserById(19);
        System.out.println(user);
    }
    @Test
    /**
     *  mapper代理方式   添加用户void addUser(User user); 并且获取到添加后user 的id
     */
    public void test04() throws IOException {
        InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //封装实体类
        User user = new User();
        user.setUsername("euuruqwo");
        user.setPassword("123123");
        System.out.println("添加前"+user);

        //mapper代理
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.addUser(user);
        sqlSession.commit();
        System.out.println("添加后"+user);
    }
    @Test
    /**
     *  mapper代理方式 删除用户
     */
    public void test05() throws IOException {
        InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //mapper代理
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.delUserById(25);
    }
    @Test
    /**
     *  mapper代理方式 修改用户
     */
    public void test06() throws IOException {
        InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //封装实体类
        User user = new User();
        user.setId(2);
        user.setUsername("2222222");
        //mapper代理
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.modUserById(user);
    }
    //模糊查询测试
    @Test
    public void queryLike() throws IOException {
        InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = build.openSession();

        //mapper代理对象
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> users = mapper.findUserByLikeUsername("%张%");
        for (User user : users) {
            System.out.println(user);
        }
    }
}

Guess you like

Origin www.cnblogs.com/ppvir/p/11432612.html