A main frame: Mybatis frame (3) Mybatis CRUD operations

A: Mybatis agent based CRUD operations Dao

1.CRUD implementation steps:

(1) In the Persistent Layer Interface (IUserDao) adding the corresponding method
, for example:

    /**
     * 用户的持久层接口
     * @author Mango
     */
    public interface IUserDao {
    
        /**
         * 查询所有操作
         * @return
         */
        List<User> findAll();

(2) is then disposed ** user mapping profile (IUserDao.xml) ** in

    <!--    配置查询所有-->
    <!--    dao的方法名称,会把结果集封装到User-->
        <select id="findAll" resultType="com.itheima.domain.User">
            select * from user;
        </select>

Details:
the resultType properties: specifies the result set (return value) type. parameterType property: specifies the arguments passed to type.
sql statement using # {} character: it represents a placeholder, equivalent to the original part jdbc learned? , are replaced by the actual data for the statement is executed. Specific data # {} is determined by the contents inside. # {} In the written content: since the data type is a base type, where it is free to write.

(1) ognl expression:

It is an expression language provided by apache, full name is: Object Graphic Navigation Language object graph navigation language
it is to get the data according to certain syntax. The syntax is the use of the object # {.} Objects manner.

# {User.username} It will first go to the user object, and then locate the object in the user attribute username and calls the getUsername () method of the value taken out. But we parameterType property specified in the entity class name, so you can omit user. The direct write username.

(3) Test Test Class

    private InputStream in;
        private SqlSession sqlSession;
        private IUserDao userDao;
    
        /**
         * 用于在测试方法之前执行
         * @throws Exception
         */
        @Before
        public void init() throws Exception{
            //1.读取环境里面的总体配置文件(里面参数)
            in = Resources.getResourceAsStream("SqlMapConfig.xml");
            //2.创建SqlSessionFactory工厂
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            SqlSessionFactory factory = builder.build(in);
            //3.使用工厂生产一个SqlSession对象
            sqlSession = factory.openSession();
            //4.使用SqlSession创建Dao接口的代理对象
            userDao = sqlSession.getMapper(IUserDao.class);
        }
        /**
         * 用于在测试方法之后执行
         * @throws Exception
         */
        @After
        public void destory() throws Exception{
            //提交事务
            sqlSession.commit();
    
            //6.释放资源
            sqlSession.close();
            in.close();
        }
    
    
        @Test
        public void testFindAll() {
            //使用代理对象执行方法
            List<User> users = userDao.findAll();
            for (User user : users) {
                System.out.println(user);
            }
        }

(2) commit the transaction: session.commit ();

Open Mysql database does not add any records, what is the reason? Jdbc and it is the same, we must go to control the realization of additions and deletions to the transaction submitted , you can use in mybatis in: session.commit (); to implement the transaction commits.

(3) the new user id return value

After the new users, but also returns the id of the current value of new users , because id is the automatic growth of the database to achieve, so we have to be equivalent to the return value will add automatic growth of auto_increment.

<!--   保存用户 -->
    <insert id="saveUser" parameterType="com.itheima.domain.User">
    <!-- 配置插入操作后,获取插入数据的id-->
    <selectKey keyProperty="id" keyColumn="id" resultType="int" order="AFTER">
        select last_insert_id(); //获取最后插入数据的id
    </selectKey>
        insert into user(username,address,sex,birthday)values(#{userName},#{address},#{sex},#{birthday});
    </insert>

The difference (4)} and {#} of {$

    #{} 表示一个占位符号
    通过#{}可以实现 preparedStatement 向占位符中设置值,自动进行 java 类型和 jdbc 类型转换,#{}可以有效防止 sql 注入。 #{}可以接收简单类型值或 pojo 属性值。 如果 parameterType 传输单个简单类型值,#{}括号中可以是 value 或其它名称。
    
    ${}表示拼接字符串
    通过${}可以将 parameterType 传入的内容拼接在 sql中且不进行 jdbc 类型转换,$ {}可以接收简单类型值或 pojo 属性值,如果 parameterType 传输单个简单类型值,${}括号中只能是 value。

Comparative (5) Mybatis programmed with the JDBC

1. Database Link (Connection) creation, release frequent system resources are wasted thus affecting the performance of the system, if you use a database connection pooling solve this problem.
Solution:
Configure Data Link SqlMapConfig.xml pool, use the connection pool management database links.

2.Sql statement written in the code caused the code is not easy to maintain, practical application sql change may be larger, sql changes need to change the java code.
Solution:
The configuration Sql statement separate from the java code XXXXmapper.xml file. Just change the external sql statement

3. The transmission parameters to sql statement trouble , because where conditions are not necessarily the sql statement, may be more or less, placeholders needs and the corresponding parameters.
Solution:
Mybatis java object to automatically map the sql statement, the statement by the definition of the type of input parameters parameterType.

4. The analytical result set trouble, sql parsing code change results in a change, and the need to traverse before parsing, can if a database record for pojo encapsulated
object parsing convenient.

Solution:
Mybatis automatically map an execution result to sql java object, by the statement defines the type of output resultType.

Two: Mybatis parameters depth (parameterType property)

parameterType attribute set. Value of the attribute may be a primitive type, a reference type (e.g.: String Type), it may also be the entity class type (POJO class) . But you can also use a wrapper class entity class (QueryVo)

QueryVo

/**
 * @author Mango
 * 实体类的包装类
 */
public class QueryVo {
    private User user;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

dao layer interface mapping file

<!-- 根据用户名称模糊查询,参数变成一个 QueryVo 对象了 -->
<select id="findByVo" resultType="com.itheima.domain.User"
parameterType="com.itheima.domain.QueryVo">
select * from user where username like #{user.username};
</select>

Three: Mybatis output result of the package

resultType attribute specifies the type of result set , which supports basic types and entity class type .
Note that, as it parameterType, type alias if registered, you can use the alias directly. Not registered must use the fully qualified class name. For example: our entity classes (User) must now be fully qualified class name

Meanwhile, when the entity class name is, there is a requirement, the entity class and property names must match the column names in the query, the package can not be achieved otherwise.

<!--    配置查询所有-->
<!--    dao的方法名称,会把结果集封装到User-->
    <select id="findAll" resultType="com.itheima.domain.User">
        select * from user;
    </select>

resultMap result type

resultMap label ** may establish property names and column names of entity classes queries inconsistent establish the correspondence when. ** in order to achieve encapsulation. ResultMap use property specified in the select tag can be invoked. Meanwhile resultMap query results can be achieved mapped to complex types of pojo, such as including a list pojo and achieve one-to-many query and query in the query results map object.

type attribute: Specifies the solid fully qualified class name of the class member
id attribute: given a unique identifier , a query is to select a reference label used.

<!--    配置查询结果的列名和实体类的属性名的对应关系-->
    <resultMap id="userMap" type="com.itheima.domain.User">
        <!--  主键字段的对应 -->
        <id property="id" column="id"></id>
        <!--  主键字段的对应 -->
        <result property="userName" column="username"></result>
        <result property="address" column="address"></result>
        <result property="sex" column="sex"></result>
        <result property="birthday" column="birthday"></result>
    </resultMap>
<!--    每个dao独立的配置文件-->

<!--    配置查询所有-->
<!--    dao的方法名称,会把结果集封装到User-->
    <select id="findAll" resultMap="userMap">
        select * from user;
    </select>

Four: Mybatis dao implementation class development (understanding)

Dao using Mybatis development, there are usually two methods, i.e., the original development mode Dao Mapper interface agent and the development mode. And now the mainstream development approach is the way to develop interface agent, generally easier this way.

dao interface categories:

/**
 * @author Mango
 * dao 的实现类
 */
public class UserDaoImpl implements IUserDao {
    
    private SqlSessionFactory factory;

    public UserDaoImpl(SqlSessionFactory factory) {
        this.factory = factory;
    }
    @Override
    public List<User> findAll() {
        SqlSession session = factory.openSession();
        List<User> users = session.selectList("com.itheima.dao.IUserDao.findAll");
        session.close();
        return users;
    }

}

Persistence mapping configuration

<!-- 配置查询所有操作 -->
<select id="findAll" resultType="com.itheima.domain.User">
select * from user
</select>
<!-- 根据 id 查询 -->
<select id="findById" resultType="com.itheima.domain.User" parameterType="int">
select * from user where id = #{uid}
</select>

Five: SqlMapConfig.xml profile

(1) properties Properties

When using the properties tab to configure, we can use to specify the configuration properties in two ways.

Jdbc.properties definition file in the classpath

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/xxx
jdbc.username=root
jdbc.password=1234

Can be saved to local, indexed by url

<!--    配置properties  支持放到外部配置文件 然后下面再引用

    resource属性:用于指定配置文件的位置,是按照类路径的写法来写,并且必须存在于类路径下

    url属性:是要求按照url的写法来写地址
    URL:Uniform Resource Locator 统一资源定位符,它是可以唯一表示一个资源的位置
    它的写法:
        http://localhost:8080/mybatisservert/demolServlet
        协议 主机 端口 URI
    URI:Uniform Resource Identifier 统一资源标识符。它是在应用中可以唯一定位一个资源的
    -->
    <properties url="file:///C:/Users/Mango/Desktop/jdbcConfig.properties"></properties>

(2) typeAliases properties

We speak in front of Mybatis default alias support, we can adopt a custom aliases way to develop.
In SqlMapConfig.xml configure:

<!--    使用typeAliases配置别名,它只能配置domain中类的别名-->
    <typeAliases>
<!--        typeAlias用于配置别名。type属性指定的是实体类全限定类名。alias属性指定别名,当指定了别名就别再区分大小写-->
<!--        <typeAlias type="com.itheima.domain.User" alias="user"></typeAlias>-->
        
<!--        用于指定要配置别名的包,当指定之后,该包下的实体类都会注册别名,并且类名就是别名,不再区分大小写-->
        <package name="com.itheima.domain.User"/>
    </typeAliases>
<!--    指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件-->
    <mappers>
<!--        <mapper resource="com/itheima/dao/IUserDao.xml"/>-->
        
<!--        package标签用于指定dao接口所在的包  当指定后不需要再写mapper以及resource或者class-->
        <package name="com.itheima.dao"/>
        
    </mappers>

Note: this method requires mar pper interface name and r mapper mapping file of the same name, and in the same directory.

Published 47 original articles · won praise 18 · views 4878

Guess you like

Origin blog.csdn.net/qq_43605085/article/details/96877069