Mybatis often meet questions
# {} and ${}
What is the difference between?
What is the difference between #{} and ${}?
In Mybatis, there are two placeholders
# {}
Parse the parameter data passed in- ${} concatenates the parameters passed in as is in SQL
- #{} is precompiled processing, and ${} is string substitution.
- Using #{} can effectively prevent SQL injection and improve system security.
What if the attribute name in the entity class is different from the field name in the table?
What if the attribute name in the entity class is different from the field name in the table?
The first is to make the alias of the field name consistent with the attribute name of the entity class by defining the alias of the field name in the SQL statement of the query
<select id="Selectorder" parametertype="Int" resultetype="Me. Gacl. Domain. The order">
select order_id id, order_no orderno ,order_price price form orders where order_id=#{id};
</select>
Copy the code
The second is to map the one-to-one correspondence 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. The order" id="Orderresultmap">
<! -- Map primary key fields with id attributes -->
<id property="Id" column="Order_id">
<! - Use the result attribute to map non-primary key fields, property is the name of the entity class attribute, column is the attribute in the data table ->
<result property = "Orderno" column ="Order_no" />
<result property="Price" column="Order_price" />
</reslutMap>
Copy the code
I think the second way is better.
How do I get automatically generated (primary) key values?
How do I get automatically generated (primary) key values?
If we normally insert data, if we want to know what the primary key of the data we just inserted is, we can do the following
Requirements:
- After the User object is inserted into the database, the primary key of the new record is returned through the User object, through which the primary key value is obtained.
Solution:
- To obtain the value of the newly inserted record’s auto-increment primary key, use 1299445. After the INSERT statement, execute SELECT 1299445.
mysql:
<insert id="insertUser" parameterType="cn.itcast.mybatis.po.User">
<selectKey keyProperty="id" order="AFTER" resultType="int">
select 1299445
</selectKey>
INSERT INTO USER(username,birthday,sex,address) VALUES(#{username},#{birthday},#{sex},#{address})
</insert>
Copy the code
oracle:
Implementation idea:
- Query the sequence to get the primary key, set the primary key to the user object, and insert the User object into the database.
<! Nextval () from dual Set the maximum value of the sequence to the id attribute of the user object -->
<insert id="insertUser" parameterType="cn.itcast.mybatis.po.User">
<selectKey keyProperty="id" order="BEFORE" resultType="int">Nextval () from dual</selectKey>INSERT INTO USER (id, username, birthday, sex, address) VALUES (sequence. Nextval (), # {username}, # {birthday}, # {sex}, # {address})</insert>
Copy the code
How do I pass multiple parameters in Mapper?
How do I pass multiple parameters in Mapper?
First: the idea of using placeholders
-
Use #{0} in the mapping file, where #{1} represents the number of arguments passed in
-
** Use the @param annotation to name the parameter **
-
# # {0}, {1}
#{0} represents the first parameter in the DAO layer. #{1} represents the second parameter in the DAO layer.<select id="selectUser"resultMap="BaseResultMap">
select * fromuser_user_t whereuser_name = #{0} anduser_area=#{1}
</select>
Copy the code
- @param annotation
public interface usermapper {
user selectuser(@ param (" username ") string username,
@param(" hashedpassword ") string hashedpassword);
}
Copy the code
<select id="Selectuser" resulttype="User">
select id, username, hashedpassword
from some_table
where username = #{username}
and hashedpassword = #{hashedpassword}
</select>
Copy the code
Second: load with a Map collection as a parameter
try{
// Map file namespace. The ID of the SQL fragment can call the SQL in the corresponding mapping file
/** * Since we have more than two arguments and only one Object argument collection in the method *, we use the Map collection to load our arguments */
Map<String, Object> map = new HashMap();
map.put("start", start);
map.put("end", end);
return sqlSession.selectList("StudentID.pagination", map);
}catch(Exception e){
e.printStackTrace();
sqlSession.rollback();
throw e;
}finally{
MybatisUtil.closeSqlSession();
}
Copy the code
<! -- Paging query -->
<select id="pagination" parameterType="map" resultMap="studentMap">Value */ select * from students limit #{start},#{end};</select>
Copy the code
What does Mybatis dynamic SQL do? What is the dynamic SQL? Can you briefly explain how dynamic SQL is executed?
What does Mybatis dynamic SQL do? What is the dynamic SQL? Can you briefly explain how dynamic SQL is executed?
- Mybatis dynamic SQL allows us to compile dynamic SQL in the form of tags in Xml mapping files, complete logical judgment and dynamic splicing SQL functions.
- Mybatis provides nine dynamic SQL tags: trim | where | set | foreach | if | choose | s | otherwise | bind.
- Its implementation principle is to use OGNL to calculate the value of the expression from the SQL parameter object, according to the value of the expression dynamic splicing SQL, to complete the function of dynamic SQL.
For details, please refer to my other articles:
- Zhongfucheng.bitcron.com/post/mybati…
In the Xml mapping files of Mybatis, can the IDS of different Xml mapping files be repeated?
In the Xml mapping files of Mybatis, can the IDS of different Xml mapping files be repeated?
If a namespace is configured, it can be repeated, because our Statement is actually a namespace+ ID
If a namespace is not configured, the same ID will cause overwriting.
Mybatis semi-automatic ORM mapping tool What’s the difference between it and automatic?
Mybatis semi-automatic ORM mapping tool What’s the difference between it and automatic?
- Hibernate is a fully automated ORM mapping tool. When using Hibernate to query associated objects or associated collection objects, it can be directly retrieved based on the object relational model, so it is fully automated.
- While Mybatis needs to write SQL manually when querying associated objects or associated collection objects, so it is called semi-automatic ORM mapping tool.
Usually an Xml mapping file will write a Dao interface corresponding to it. What is the working principle of this Dao interface? Can methods in the Dao interface be overloaded if their parameters are different?
Usually an Xml mapping file will write a Dao interface corresponding to it. What is the working principle of this Dao interface? Can methods in the Dao interface be overloaded if their parameters are different?
- Dao interface is also known as Mapper interface. The full name of the interface is the value of namespace in the mapping file, the method name of the interface is the ID value of MappedStatement in the mapping file, and the parameters in the interface method are the parameters passed to SQL.
- The Mapper interface has no implementation class. When an interface method is called, the interface full name + method name concatenation string is used as the key value to uniquely locate an MappedStatement
For example:
Com. Mybatis3. Mappers. StudentDao. FindStudentById, Can only find the namespace for the com. Mybatis3. Mappers. StudentDao id = findStudentById MappedStatement below. In Mybatis, every one<select>,<insert>,<update>,<delete>Tag, will be parsed into an MappedStatement object.Copy the code
Methods in the Dao interface cannot be overridden because of the save and find policy of the full name + method name.
The working principle of Dao interface is JDK dynamic proxy. Mybatis will use JDK dynamic proxy to generate proxy objects for Dao interface. Proxy object proxy intercepts interface methods, executes SQL represented by MappedStatement, and returns SQL execution results.
Please refer to:
- www.cnblogs.com/soundcode/p…
What are the major improvements to Mybatis over IBatis
What are the major improvements to Mybatis over IBatis
- A. Interface binding, including annotation binding SQL and XML binding SQL,
- B. Dynamic SQL from the original node configuration into OGNL expression,
- C. Association is introduced in one-to-one and one-to-many mode, and collection node is introduced in one-to-many mode, but they are configured in resultMap
Interface binding can be implemented in several ways. How are they implemented?
Interface binding can be implemented in several ways. How are they implemented?
Interface binding can be implemented in two ways:
- One way is to bind by annotation, which is to add @Select@Update and other annotations to the interface methods that contain Sql statements to bind
- The other option is to bind by writing SQL in XML. In this case, to specify the namespace in the XML mapping file must be the full path name of the interface.
How does Mybatis paginate? How does paging plug-ins work?
How does Mybatis paginate? How does paging plug-ins work?
Mybatis uses the RowBounds object for paging, which is memory paging for ResultSet result sets, rather than physical paging. You can write physical paging parameters directly in SQL to complete physical paging, or you can use paging plug-ins to complete 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 to intercept the SQL to be executed in the interception method of the plug-in, and then rewrite the SQL to add the corresponding physical paging statement and physical paging parameters according to the dialect.
Select t.* from (select * from student) t limit 0,10
Paging plug-in usage References:
- www.cnblogs.com/kangoroo/p/…
- Blog.csdn.net/yuchao2015/…
- www.cnblogs.com/ljdblog/p/6…
Describe the operation principle of Mybatis plug-in, and how to write a plug-in
Describe the operation principle of Mybatis plug-in, and how to write a plug-in
Only ParameterHandler, ResultSetHandler, StatementHandler, and Executor interfaces can be used as plugins in Mybatis. The interface method interception function is implemented by generating proxy objects for the interface to be intercepted. Each of the four methods of the interface object is invoked, specifically the Invoke () method of InvocationHandler, which, of course, only intercepts those methods that you specify to be intercepted.
Implementation of Mybatis Interceptor interface and autotype intercept () method, and then to the plug-in to write notes, specify which interface to intercept method which can, remember, don’t forget to you write a plug-in that is configured in the configuration file.
Does Mybatis support lazy loading? If so, how does it work?
Does Mybatis support lazy loading? If so, how does it work?
Mybatis only supports lazy loading of association associative objects and collection associative objects. Association refers to one-to-one and collection refers to one-to-many queries. In Mybatis configuration file, you can configure whether to enable lazy-loading lazyLoadingEnabled = true | false.
The principle is that CGLIB is used to create a proxy object for the target object. When the target method is called, the interceptor method is entered, such as a.geb ().getName(). The interceptor invoke() method finds that A.geb () is null. A. setb (); a.getName (); a.getname (); a.getb (); a.getname (); This is the basic principle of lazy loading.
Of course, not only Mybatis, almost all including Hibernate, support lazy loading principle is the same.
What Executor executors does Mybatis have? What’s the difference between them?
What Executor executors does Mybatis have? What’s the difference between them?
Mybatis has three basic Executor executors: SimpleExecutor, ReuseExecutor, and BatchExecutor.
- SimpleExecutor: Every time an Update or select is performed, a Statement object is opened and the Statement object is closed immediately.
- ReuseExecutor: If the Statement object exists, use it. If the Statement object does not exist, create it. After the Statement object is used, place it in Map
,>
for next use. In short, the Statement object is reused.
- BatchExecutor: Update (no SELECT, JDBC batch does not support SELECT), add all SQL to the batch (addBatch()), and wait for execution (executeBatch()), which caches multiple Statement objects. Each Statement object is addBatch() and waits for the executeBatch() batch to be executed one by one. Same as JDBC batch processing.
Scope: These Executor features are strictly limited to the SCOPE of the SqlSession lifecycle.
What are the differences between MyBatis and Hibernate?
What are the differences between MyBatis and Hibernate?
Unlike Hibernate, Mybatis is not a complete ORM framework because it requires programmers to write their own Sql statements. However, Mybatis can flexibly configure the Sql statements to be run through XML or annotations, and map Java objects and Sql statements to generate the Sql to be executed. Finally, the results of SQL execution are mapped to generate Java objects.
Mybatis learning threshold is low, easy to learn, raw SQL programmers write directly, can strictly control the SQL execution performance, high flexibility, very suitable for low requirements for relational data model of software development, such as the Internet software, business software, because this kind of software requirements changes frequently, a change but demand for output results quickly. However, the premise of flexibility is that Mybatis cannot achieve database independence. If the software supporting a variety of databases needs to be implemented, multiple sets of SQL mapping files need to be customized, and the workload is heavy.
Hibernate has strong object/relational mapping capability and good database independence. For software with high requirements on relational model (such as customized software with fixed requirements), developing with Hibernate can save a lot of code and improve efficiency. The downside of Hibernate, however, is that there is a high bar to learn, a high bar to master, and a lot of experience and competence in how to design O/R mappings, how to trade off performance and object models, and how to use Hibernate well. In short, in accordance with the needs of users in the limited resource environment, as long as it can make maintainability, good scalability of the software architecture is a good architecture, so the framework only suitable is the best.
The last
References:
- Blog.csdn.net/eaphyy/arti…
- Blog.csdn.net/frankaqi/ar…
- Blog.csdn.net/gcxzflgl/ar…
If the article has the wrong place welcome to correct, everybody exchanges with each other. Students who are used to reading technical articles on wechat and want to get more Java resources can follow the wechat public account :Java3y