front
word
:
\textcolor{blue} {Preface:}
preface:
💥MyBatis learning source code in gitee 💥 The code used can be found here
8, Annotation development
1. Interface oriented programming
In redevelopment, we generally do not need object-oriented programming, and we often choose interface oriented programming
Root cause: decoupling (the most important), expandable and reusable. In layered development, the upper layer does not care about the specific implementation. Everyone abides by common standards, making the development easy and standardized.
In an object-oriented system, various functions of the system are completed by many different objects. In this case, how each object implements itself is not so important for system designers.
The cooperative relationship between various objects has become the key of system design. From the communication between different classes to the interaction between modules, we should focus on it at the beginning of system design, which is also the main work content of system design. Interface oriented programming refers to programming according to this idea.
- Understanding of interface:
- From a deeper understanding, the interface should be the separation of definition (specification, constraint) and Implementation (the principle of separation of name and reality)
- The interface itself reflects the system designer's abstract understanding of the system.
- There shall be two types of interfaces:
- The first type is the abstraction of an individual, which can correspond to an abstract class
- The second type is the abstraction of an aspect of an individual, that is, the formation of an abstract interface
- An individual may have multiple Abstract faces. Abstract body and abstract surface are distinguished by.
- Three oriented differences
- Object oriented refers to. When we consider the problem, we take the object as the unit and consider its attributes and methods.
- Process oriented means that when we consider a problem, we consider its implementation in a specific process (transaction process).
- Interface design and non interface design are aimed at reuse technology. It is not a problem with object-oriented (process), but the overall architecture of the system.
2. Annotation development
For mapper classes like BlogMapper, there is another way to complete statement mapping. Their mapped statements can be configured using Java annotations instead of XML. For example, the above XML example can be replaced with the following configuration:
package org.mybatis.example; public interface BlogMapper { @Select("SELECT * FROM blog WHERE id = #{id}") Blog selectBlog(int id); }
Using annotations to map simple statements will make the code more concise, but for slightly more complex statements, Java annotations will not only fail, but also make your already complex SQL statements more chaotic. Therefore, if you need to do some very complex operations, it is best to use XML to map statements.
It is entirely up to you and your team to choose how to configure the mapping and whether you think you should unify the form of mapping statement definition. In other words, never stick to one way. You can easily migrate and switch between annotation based and XML based statement mapping.
2.1 annotation is implemented on the interface
import org.apache.ibatis.annotations.Select; import pojo.User; import java.util.List; public interface UserMapper { @Select("select * from user") List<User> getUsers(); }
2.2 mybatis config core configuration file
Binding interface
<?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"> <!--Core profile--> <configuration> <!--Import external profile--> <properties resource="db.properties"/> <settings> <!--Standard log factory implementation--> <setting name="logImpl" value="STDOUT_LOGGING"/> </settings> <!--You can alias an entity class--> <typeAliases> <package name="com.hxl.pojo"/> </typeAliases> <environments default="development"> <environment id="development"> <!--transaction management--> <transactionManager type="JDBC"/> <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> <!--Binding interface--> <mappers> <mapper class="dao.UserMapper"/> </mappers> </configuration>
2.3 testing
@Test public void test(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); //The bottom layer mainly applies reflection UserMapper mapper = sqlSession.getMapper(UserMapper.class); List<User> users = mapper.getUsers(); for (User user : users) { System.out.println(user); } sqlSession.close(); }
At this point we will find. This password is null. This is because if annotation development can only be simple and complex, it still needs xml
2.4 precautions
-
Essence: reflection mechanism implementation
-
Bottom layer: dynamic proxy
Mybatis detailed execution process
3. Note Development CRUD
3.1 implement automatic transaction submission when creating tool classes
public static SqlSession getSqlSession() { return sqlSessionFactory.openSession(true); }
3.2 add notes to interface preparation
public interface UserMapper { @Select("select * from user") List<User> getUsers(); //If the method has multiple parameters, each parameter needs to be preceded by @ Param annotation @Select("select * from user where id = #{id}") User getUserById(@Param("id") int id); //The reference object does not need to write @ Param @Insert("insert into user(id,name,pwd) value(#{id},#{name},#{password})") int addUser(User user); @Update("update user set name=#{name},pwd=#{password} where id = #{id}") int updateUser(User user); //If there is an annotation, follow the one in the annotation, otherwise an error will be reported @Delete("delete from user where id = #{uid}") int deleteUser(@Param("uid") int id); }
3.3 testing
public class UserMapperTest { @Test public void test(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); //The bottom layer mainly applies reflection UserMapper mapper = sqlSession.getMapper(UserMapper.class); /*List<User> users = mapper.getUsers(); for (User user : users) { System.out.println(user); } //check User userById = mapper.getUserById(1); System.out.println(userById); //increase mapper.addUser(new User(4,"Old four "," 123456 "); //to update mapper.updateUser(new User(4,"hh","1234")); */ //Delete mapper.deleteUser(4); sqlSession.close(); } }
-
Attention
We must bind the interface registration to our core configuration file
<!--Binding interface--> <mappers> <!--<mapper resource="com/hxl/dao/*.xml"/>--> <!--If you use interfaces, if there are many mapper You can only register one by one, but if you use resource Through configuration can be carried out in this way--> <mapper class="dao.UserMapper"/> </mappers>
3.4 notes on @ Param()
- Parameters of basic type or String type need to be added
- Reference types do not need to be added
- If there is only one basic type, it can be ignored, but it is recommended to add
- The attribute name set in @ Param() here is referenced in sql
#{} and ${}
-
One precompiled, one different
-
#{} can largely prevent sql injection. ${} cannot
-
${} is generally used to pass in database objects, such as database table names
-
The data passed in with ${} is directly displayed in the generated sql
9, Lombok
brief introduction
​ Project Lombok is a java library that automatically plugs into your editor and build tools, spicing up your java.
Never write another getter or equals method again, with one annotation your class has a fully featured builder, Automate your logging variables, and much more.
Project Lombok is a Java library that automatically inserts your editor and builds tools to add fun to your Java.
Never write another getter or equals method. With a comment, your class will have a fully functional builder, automate your log variables, and so on.
Lombok is a java development plug-in, which enables Java developers to eliminate tedious and tedious code in business engineering through some annotations defined by it, especially for simple java model objects (POJO s) . after using Lombok plug-in in the development environment, Java developers can save a lot of time for repeatedly building methods such as hashCode and equals and accessor and ToString methods of various business object models. For these methods, it can automatically generate these methods for us during compiling source code, without reducing the performance of the program like reflection.
Use steps:
-
Install Lombok in IDEA and restart after installation
-
Import the jar package of Lombok in the project
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.20</version> <scope>provided</scope> </dependency>
-
Annotation on entity class
@Getter and @Setter @FieldNameConstants @ToString @EqualsAndHashCode @AllArgsConstructor, @RequiredArgsConstructor and @NoArgsConstructor @Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog, @Flogger, @CustomLog @Data @Builder @SuperBuilder @Singular @Delegate @Value @Accessors @Wither @With @SneakyThrows @val @var experimental @var @UtilityClass
You don't have to write anymore. Just add a comment.
explain:@Data: Nonparametric structure, get,set,toString,hashcode,equals @AllArgsConstructor: Parametric structure. If there is a parametric structure, there is no nonparametric structure, so we need to add a nonparametric structure @NoArgsConstructor: Parameterless construction. You can annotate or add methods in it
Advantages and disadvantages
advantage:
- It can automatically generate constructors, getters / setters, equals, hashcode, toString and other methods in the form of annotations, which improves the development efficiency
- Make the code more concise and don't pay too much attention to the corresponding methods
- When modifying properties, it also simplifies the maintenance of getter/setter methods generated for these properties
Disadvantages:
- Overloading of multiple parameter constructors is not supported
- Although it saves the trouble of manually creating getter/setter methods, it greatly reduces the readability and integrity of the source code and reduces the comfort of reading the source code
summary
Lombok has many advantages, but it is similar to a Chinese IDEA plug-in, and the project also needs to rely on the corresponding jar package. Lombok relies on the jar package because its annotations are used at compile time. Why is it similar to a plug-in? When using, eclipse and IDEA need to install corresponding plug-ins. During compiler compilation, the bytecode generation is changed by operating AST (abstract syntax tree). In disguise, it is changing java syntax.
It is not a runtime feature like spring dependency injection or mybatis ORM, but a compile time feature.
Use on demand