Mybatis interview summary (1)

1. What is Mybatis?
1. Mybatis is a semi-ORM (object-relational mapping) framework, which encapsulates JDBC internally. When developing, you
only need to pay attention to the SQL statement itself, and do not need to spend energy to deal with
complicated processes such as loading drivers, creating connections, and creating statements. The programmer directly writes the original ecological SQL, which can strictly control the execution performance of SQL
, and has a high degree of flexibility.
2. MyBatis can use XML or annotations to configure and map native information, and map POJOs to
records in the database, avoiding almost all JDBC codes and manually setting parameters and obtaining result sets.
3. Configure the various statements to be executed through xml files or annotations, and
generate the final executed sql statement through mapping between the java object and the dynamic parameters of sql in the statement.
Finally mybatis framework executes sql and maps the result to java object and return it. (
The process from executing sql to returning result).
2. Advantages of Mybaits:
1. Based on SQL statement programming, it is quite flexible and will not have
any . SQL is written in XML, which decouples sql from program code and facilitates unified management; Provides XML
tags, supports writing dynamic SQL statements, and can be reused.
2. Compared with JDBC, it reduces the amount of code by more than 50%, eliminates a large number of redundant codes of JDBC, and does not need to
manually switch the connection;
3. It is very compatible with various databases (because MyBatis uses JDBC to connect to the database, so as long as
The database MyBatis supported by JDBC is supported).
4. Can be well integrated with Spring;
5. Provide mapping tags, support ORM field relationship mapping between objects and databases; provide object-relational mapping
tags, and support object-relational component maintenance.
3. Disadvantages of the MyBatis framework:
1. The workload of writing SQL statements is relatively large, especially when there are many fields and many associated tables,
there are certain requirements for developers to write SQL statements.
2. SQL statements depend on the database, resulting in poor database portability, and the database cannot be replaced at will.
4. Applicable occasions of the MyBatis framework:
1. MyBatis focuses on SQL itself and is a flexible enough DAO layer solution.
2. MyBatis will be a
good choice for projects with high performance requirements, or projects with frequent changes in requirements, such as Internet projects.

public interface StudentDAO {
    
    
    //添加学生
    public void addStudent(Student stu);
}
//实现类
public class StudentDAOImpl implements StudentDAO {
    
    
    Connection conn=null;
    PreparedStatement pstmt=null;
    ResultSet rs=null;
    @Override
    public void addStudent(Student stu) {
    
    
        String sql="insert into student values (null,?,?,?,?,?)";
        try {
    
    
            conn=DBUtil.getConnection();
            pstmt=conn.prepareStatement(sql);
            pstmt.setString(1, stu.getName());
            pstmt.setInt(2, stu.getAge());
            pstmt.setString(3, stu.getGender());
            pstmt.setString(4, stu.getPhone());
            pstmt.setString(5, stu.getEducation());
            pstmt.executeUpdate();
            System.out.println("添加學生成功!");
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }finally{
    
    
            DBUtil.closeAll(rs, pstmt, conn);
        }
    }
}

5. What are the differences between MyBatis and Hibernate?
1. Unlike hibernate, Mybatis is not completely an ORM framework, because MyBatis requires
programmers to write Sql statements by themselves.
2. Mybatis directly writes the original ecological sql, which can strictly control the execution performance of sql, and has high flexibility. It is very
suitable for software development that does not have high requirements for relational data models, because the requirements of such software change frequently, and once
the requirements it requires rapid output results . But the premise of flexibility is that mybatis cannot be database-independent.
If you need to implement software that supports multiple databases, you need to customize multiple sets of sql mapping files, which is a heavy workload.
3. Hibernate has strong object/relational mapping capabilities and good database independence. For
software that requires high relational models, if you use hibernate to develop, you can save a lot of code and improve efficiency.
HibernateHibernate is an ORM framework, the full name is Object_Relative DateBase-Mapping, which establishes a certain mapping between Java objects and relational databases to achieve direct access to Java objects!
6. What is the difference between #{} and KaTeX parse error: Expected 'EOF', got '#' at position 12: {}? #̲{} is precompilation processing, and {} is string replacement.
When Mybatis processes #{}, it will replace #{} in sql with a ? number, and call the
set method of PreparedStatement to assign a value;
when Mybatis processes , it means {}, that is, is to replace {} with the value of the variable.
Using #{} can effectively prevent SQL injection and improve system security.
7. What should I do if the attribute name in the entity class is different from the field name in the table?
Type 1: By defining the alias of the field name in the sql statement of the query, the alias of the field name is
consistent with the attribute name of the entity class.

<select id=”selectorder” parametertype=int” resultetype=
me.gacl.domain.order> 
select order_id id, order_no orderno ,order_price price form 
orders where order_id=#{id}; 
</select> 

Type 2: Mapping the one-to-one relationship between field names and entity class attribute names.

<select id="getOrder" parameterType="int" 
resultMap="orderresultmap"> 
select * from orders where order_id=#{id} 
</select> 
<resultMap type=”me.gacl.domain.order” id=”orderresultmap”> 
<!–用 id 属性来映射主键字段–> 
<id property=”id” column=”order_id”> 
<!–用 result 属性来映射非主键字段,property 为实体类属性名,column 
为数据表中的属性–> 
<result property = “orderno” column =”order_no”/> 
<result property=”price” column=”order_price” /> 
</reslutMap>

8. How to write the fuzzy query like statement?

1 种:在 Java 代码中添加 sql 通配符。 
string wildcardname =%smi%; 
list<name> names = mapper.selectlike(wildcardname); 
<select id=”selectlike”> 
select * from foo where bar like #{value} 
</select>2 种:在 sql 语句中拼接通配符,会引起 sql 注入 
string wildcardname = “smi”; 
list<name> names = mapper.selectlike(wildcardname); 
<select id=”selectlike”> 
select * from foo where bar like "%"#{value}"%" 
</select>

9. Usually an Xml mapping file will write a Dao interface corresponding to it. Excuse me, what is the working principle of this Dao interface? The method in the Dao interface, when the parameters are different, can the method be overloaded?
The Dao interface is the Mapper interface. The fully qualified name of the interface is the namespace value in the mapping file;
the method name of the interface is the id value of Mapper's Statement in the mapping file; the parameters in the interface method
are the parameters passed to sql.
The Mapper interface does not have an implementation class. When calling an interface method, the full interface name + method name concatenated string is used
as the key value, which can uniquely locate a MapperStatement. In Mybatis, each

,,, and tags will be parsed into a
MapperStatement object.
For example: com.mybatis3.mappers.StudentDao.findStudentById, you can uniquely
find
the MapperStatement whose namespace is com.mybatis3.mappers.StudentDao and whose id is findStudentById.
The methods in the Mapper interface cannot be overloaded, because the full-qualified name + method name is used to save and find
the strategy.
The working principle of the Mapper interface is the JDK dynamic proxy. Mybatis will use the JDK dynamic proxy to generate a proxy object proxy for the Mapper interface during runtime . The proxy object will intercept the interface method,
execute the sql represented by the MapperStatement, and then return the sql execution result.
10. How does Mybatis paginate? What is the principle of the pagination plugin? Mybatis uses the RowBounds object for paging, which is memory paging
performed on the ResultSet result set , rather than physical paging.
You can directly write parameters with physical paging in sql to complete the physical paging
function, or you can use the paging plug-in to complete the physical paging.
The basic principle of the paging plug-in is to use the plug-in interface provided by Mybatis to implement a custom plug-in,
intercept the sql to be executed in the interception method of the plug-in, then rewrite the sql, and add the corresponding
physical .

Supongo que te gusta

Origin blog.csdn.net/AzirBoDa/article/details/125480445
Recomendado
Clasificación