Let’s start with our first example: Hello World
Create a Java project and set maven dependencies
Create a Maven project, set the compilation level of the project to Java8 and above, and introduce the Fluent Mybatis dependency package.Copy the code
<dependencies>
<! Fluent-mybatis; scope: compile ->
<dependency>
<groupId>com.github.atool</groupId>
<artifactId>fluent-mybatis</artifactId>
<version>1.4.5</version>
</dependency>
<! Provider provider provider provider provider provider provider provider provider provider provider provider
<dependency>
<groupId>com.github.atool</groupId>
<artifactId>fluent-mybatis-processor</artifactId>
<version>1.4.5</version>
</dependency>
</dependencies>
Copy the code
Create a new database structure for the demonstration
create schema fluent_mybatis_tutorial;
create table hello_world
(
id bigint unsigned auto_increment primary key,
say_hello varchar(100) null,
your_name varchar(100) null,
gmt_create datetime DEFAULT NULL COMMENT 'Creation time',
gmt_modified datetime DEFAULT NULL COMMENT 'Update Time',
is_deleted tinyint(2) DEFAULT 0 COMMENT 'Logical deletion or not'
) ENGINE = InnoDB
CHARACTER SET = utf8 comment 'Simple Demo Table';
Copy the code
Create an Entity class for the database table
Create the Entity class for the database table: HelloWorldEntity. Simply do 3 actions:Copy the code
- Name the Entity class and fields according to the camel name rule
- HelloWorldEntity inherits the IEntity interface class
- Annotate @FluentMyBatis on the HelloWorldEntity class
@FluentMybatis
public class HelloWorldEntity implements IEntity {
private Long id;
private String sayHello;
private String yourName;
private Date gmtCreate;
private Date gmtModified;
private Boolean isDeleted;
// Get, set, toString methods
}
Copy the code
Here, you do not need to configure any Mybatis XML file, nor do you need to write any Mapper interface, but you already have a powerful add, delete, change and check function, and Fluent API, let us write a test to witness the magic power of Fluent Mybatis!
Run the test to see the magic of Fluent Mybatis
To run the tests, we also need JUnit and Spring Test related configurations.
Configure the Spring Bean definition
- DataSource DataSource configuration
- Mapper scan path of Mybatis
- The mybatis SqlSessionFactoryBean
@ComponentScan(basePackages = "cn.org.atool.fluent.mybatis.demo1")
@MapperScan("cn.org.atool.fluent.mybatis.demo1.entity.mapper")
@Configuration
public class HelloWorldConfig {
/** * Sets the dataSource property **@return* /
@Bean
public DataSource dataSource(a) {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/fluent_mybatis_tutorial? useUnicode=true&characterEncoding=utf8");
dataSource.setUsername("root");
dataSource.setPassword("password");
return dataSource;
}
/** * Define mybatis SqlSessionFactoryBean **@param dataSource
* @return* /
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
returnbean; }}Copy the code
Use Junit4 and spring-test to perform tests
- Initialize the Spring container with spring-test
- Inject HelloWorldEntity into Mapper class: HelloWorldMapper. This class is generated when Fluent Mybatis is compiled.
- Use HelloWorldMapper to delete, insert, query, modify operations.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = HelloWorldConfig.class)
public class HelloWorldTest {
/**
* fluent mybatis编译时生成的Mapper类
*/
@Autowired
HelloWorldMapper mapper;
@Test
public void testHelloWorld(a) {
/** * delete data */ for demonstration purposes
mapper.delete(mapper.query()
.where.id().eq(1L).end());
/** * insert data */
HelloWorldEntity entity = new HelloWorldEntity();
entity.setId(1L);
entity.setSayHello("hello world");
entity.setYourName("fluent mybatis");
entity.setIsDeleted(false);
mapper.insert(entity);
/** * query data where id = 1 */
HelloWorldEntity result1 = mapper.findOne(mapper.query()
.where.id().eq(1L).end());
/** * The console directly prints the query result */
System.out.println("1. HelloWorldEntity:" + result1.toString());
/** * Update record */ with id = 1
mapper.updateBy(mapper.updater()
.update.sayHello().is("say hello, say hello!")
.set.yourName().is("fluent mybatis is powerful!").end()
.where.id().eq(1L).end()
);
/** * query data where id = 1 */
HelloWorldEntity result2 = mapper.findOne(mapper.query()
.where.sayHello().like("hello")
.and.isDeleted().eq(false).end());
/** * The console directly prints the query result */
System.out.println("2. HelloWorldEntity:"+ result2.toString()); }}Copy the code
Execute Junit4 test method, console output
1. HelloWorldEntity:HelloWorldEntity{id=1, sayHello='hello world', yourName='fluent mybatis', gmtCreate=null, gmtModified=null, isDeleted=false} 2. HelloWorldEntity:HelloWorldEntity{id=1, sayHello='say hello, say hello! ', yourName='fluent mybatis is powerful! ', gmtCreate=null, gmtModified=null, isDeleted=false}Copy the code
Amazing!!!! Let’s go back to the database and look at the results
Now, we have demonstrated the powerful functions of Fluent Mybatis through a simple example. Before introducing more powerful functions of Fluent Mybatis, we reveal why we only write an Entity class corresponding to a data table, but have a series of database operation methods of add, delete, change and check.
Entity class @FluentMybatis; Entity class @FluentMybatis; Entity class
- Core interface classes that you need to know when using
- Mapper /*Mapper: Mybatis mapper defines a set of general data manipulation interface methods.
- Dao /*BaseDao: Dao implements the base class, and all DaoImpl DaoImpl inherits its base class. In accordance with the principle of hierarchical coding, we will not use the Mapper class directly in the Service class, but reference the DAO class. We implement concrete data manipulation methods based on conditions in the Dao implementation class.
- Wrapper /*Query: Fluent mybatis core class, used to construct dynamic SQL, conditional Query.
- Wrapper /*Updater: Fluent mybatis core class used to dynamically construct update statements.
- *EntityHelper: An Entity helper class that implements an Entity and a Map conversion method
- Auxiliary implementation, the realization of Fluent Mybatis dynamic SQL assembly and fluent API internal used classes, use without understanding
In use, we’ll mainly touch on the five generated Java classes mentioned above. In order to realize dynamic splicing and Fluent API functions, a series of auxiliary classes are generated by Fluent Mybatis.
- Helper /*Mapping: Defines classes for Mapping table fields and Entity properties
- Helper /*SqlProviderP: Mapper interface dynamic SQL provider
- Helper / * WrapperHelper: Query and Updater specific functions, contains several implementation: select, where, group by, having by, order by, limit
Fluent Mybatis source code, Gitee
Fluent Mybatis documentation & examples
Fluent Mybatis source, Github