新建maven工程,设置项目编译级别为Java8及以上,引入fluent mybatis依赖包。
<dependencies>
<!-- 引入fluent-mybatis 运行依赖包, scope为compile -->
<dependency>
<groupId>com.github.atool</groupId>
<artifactId>fluent-mybatis</artifactId>
<version>1.9.7</version>
</dependency>
<!-- 引入fluent-mybatis-processor, scope设置为provider 编译需要,运行时不需要 -->
<dependency>
<groupId>com.github.atool</groupId>
<artifactId>fluent-mybatis-processor</artifactId>
<version>1.9.7</version>
</dependency>
</dependencies>
create schema fluent_mybatis;
create table hello_world
(
id bigint unsigned auto_increment primary key,
say_hello varchar(100) null,
your_name varchar(100) null,
gmt_created datetime DEFAULT NULL COMMENT '创建时间',
gmt_modified datetime DEFAULT NULL COMMENT '更新时间',
is_deleted tinyint(2) DEFAULT 0 COMMENT '是否逻辑删除'
) ENGINE = InnoDB
CHARACTER SET = utf8 comment '简单演示表';
创建数据库表对应的Entity类: HelloWorldEntity, 你只需要简单的做3个动作:
@FluentMybatis
public class HelloWorldEntity extends RichEntity {
private Long id;
private String sayHello;
private String yourName;
private Date gmtCreated;
private Date gmtModified;
private Boolean isDeleted;
// get, set, toString 方法
@Override
public Class<? extends IEntity> entityClass() {
return HelloWorldEntity.class;
}
}
执行编译:
检查你的Entity工程是否包含了 fluent-mybatis-processor jar包
IDE 编译
Maven编译 mvn clean compile
gradle编译 gradle clean compile
很简单吧,在这里,你即不需要配置任何mybatis xml文件, 也不需要写任何Mapper接口, 但你已经拥有了强大的增删改查的功能,并且是Fluent API,让我们写一个测试来见证一下Fluent Mybatis的魔法力量!
为了运行测试, 我们还需要进行JUnit和Spring Test相关配置。
@ComponentScan(basePackages = "cn.org.atool.fluent.mybatis.demo1")
@MapperScan("cn.org.atool.fluent.mybatis.demo1.entity.mapper")
@Configuration
public class HelloWorldConfig {
/**
* 设置dataSource属性
*
* @return
*/
@Bean
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/fluent_mybatis?useUnicode=true&characterEncoding=utf8");
dataSource.setUsername("root");
dataSource.setPassword("password");
return dataSource;
}
/**
* 定义mybatis的SqlSessionFactoryBean
*
* @param dataSource
* @return
*/
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
return bean;
}
@Bean
public MapperFactory mapperFactory() {
return new MapperFactory();
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = HelloWorldConfig.class)
public class HelloWorldTest {
/**
* fluent mybatis编译时生成的Mapper类
*/
@Autowired
HelloWorldMapper mapper;
@Test
public void testHelloWorld() {
/**
* 为了演示方便,先删除数据
*/
mapper.delete(mapper.query()
.where.id().eq(1L).end());
/**
* 插入数据
*/
HelloWorldEntity entity = new HelloWorldEntity();
entity.setId(1L);
entity.setSayHello("hello world");
entity.setYourName("fluent mybatis");
entity.setIsDeleted(false);
mapper.insert(entity);
/**
* 查询 id = 1 的数据
*/
HelloWorldEntity result1 = mapper.findOne(mapper.query()
.where.id().eq(1L).end());
/**
* 控制台直接打印出查询结果
*/
System.out.println("1. HelloWorldEntity:" + result1.toString());
/**
* 更新id = 1的记录
*/
mapper.updateBy(mapper.updater()
.set.sayHello().is("say hello, say hello!")
.set.yourName().is("fluent mybatis is powerful!").end()
.where.id().eq(1L).end()
);
/**
* 查询 id = 1 的数据
*/
HelloWorldEntity result2 = mapper.findOne(mapper.query()
.where.sayHello().like("hello")
.and.isDeleted().eq(false).end()
.limit(1)
);
/**
* 控制台直接打印出查询结果
*/
System.out.println("2. HelloWorldEntity:" + result2.toString());
}
}
执行Junit4测试方法,控制台输出
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}
神奇吧! 我们再到数据库中查看一下结果
现在,我们已经通过一个简单例子演示了fluent mybatis的强大功能, 在进一步介绍fluent mybatis更强大功能前,我们揭示一下为啥我们只写了一个数据表对应的Entity类, 却拥有了一系列增删改查的数据库操作方法。
fluent mybatis根据Entity类上@FluentMybatis注解在编译时, 会在target目录class目录下自动编译生成一系列文件:
Вы можете оставить комментарий после Вход в систему
Неприемлемый контент может быть отображен здесь и не будет показан на странице. Вы можете проверить и изменить его с помощью соответствующей функции редактирования.
Если вы подтверждаете, что содержание не содержит непристойной лексики/перенаправления на рекламу/насилия/вульгарной порнографии/нарушений/пиратства/ложного/незначительного или незаконного контента, связанного с национальными законами и предписаниями, вы можете нажать «Отправить» для подачи апелляции, и мы обработаем ее как можно скорее.
Опубликовать ( 0 )