Springboot+mybatis如此用才高效(xml和无xm
本文介绍的是idea+springboot+mybatis 在mybatis插件的基础上进行数据库操作。数据库使用Oracle。
首先准备工作需要做好。
1)安装mybatis插件;
2)新建一个demo web工程;
3)新建一个student表;
安装mybatis插件
打开:File -> settings->Plugins , 找到Free MyBatis plugin插件,并进行安装。安装后需要重启idea。
idea新建一个mybatis01的web工程
项目大致目录如上。pom.xml引入mybatis,lombak等依赖。
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.8</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.1</version> </dependency> <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc6</artifactId> <version>11.2.0.3</version> </dependency>
数据库中创建Student表,ID为主键,并使用序列自增
CREATE TABLE "STUDENT" ( "ID" NUMBER NOT NULL ENABLE, "NAME" VARCHAR2(20), "AGE" NUMBER, "SEX" VARCHAR2(20), "SELF_FEATURE" VARCHAR2(100), "CREATETIME" DATE, "REMARK" VARCHAR2(50), CONSTRAINT "STUDENT_PK" PRIMARY KEY ("ID"))
在config目录下进行数据库源进行配置
@Data@Configuration@ConfigurationProperties(prefix = "test.datasource")@PropertySource({ "classpath:db-test-${spring.profiles.active}.properties" })@MapperScan(basePackages = { "com.yujy.mybaits01.test.dao" }, sqlSessionFactoryRef = "testSqlSessionFactory")public class TestDataSourceConfig { private String url; private String username; private String password; private String driverClassName; private String poolName; private int minimumIdle; private int maximumPoolSize; private int idleTimeout; private int maxLifetime; private int connectionTimeout; private String connectionTestQuery; @Bean(name = { "testDataSource" }) public DataSource testDataSource() { HikariDataSource dataSource = new HikariDataSource(); dataSource.setJdbcUrl(this.url); dataSource.setUsername(this.username); dataSource.setPassword(this.password); dataSource.setDriverClassName(this.driverClassName); dataSource.setMinimumIdle(this.minimumIdle); dataSource.setMaximumPoolSize(this.maximumPoolSize); dataSource.setIdleTimeout(this.idleTimeout); dataSource.setMaxLifetime(this.maxLifetime); dataSource.setConnectionTimeout(this.connectionTimeout); dataSource.setConnectionTestQuery(this.connectionTestQuery); dataSource.setPoolName(poolName); return dataSource; } @Bean @ConfigurationProperties(prefix = "mybatis.configuration") public org.apache.ibatis.session.Configuration myBatisCfg() { return new org.apache.ibatis.session.Configuration(); } @Bean(name = { "testSqlSessionFactory" }) public SqlSessionFactory testSqlSessionFactory(@Qualifier("testDataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(dataSource); sessionFactory.setConfiguration(myBatisCfg()); return sessionFactory.getObject(); }}
db-test-${spring.profiles.active}.properties 为测试用数据库的用户密码信息;
resources/db-test-dev.properites对数据库字段配置:
test.datasource.url=jdbc:oracle:thin:@localhost:1521:orcltest.datasource.username=testtest.datasource.password=testtest.datasource.driver-class-name=oracle.jdbc.OracleDrivertest.datasource.minimum-idle=1test.datasource.maximum-pool-size=5test.datasource.pool-name=HikariCPtest.datasource.auto-commit=truetest.datasource.idle-timeout=30000test.datasource.max-lifetime=900000test.datasource.connection-timeout=10000test.datasource.connection-test-query=SELECT 1 FROM DUAL
2.mybatis自动生成bean,dao,xml
通过Database连接上数据库
选择Student表,右键单击选择“mybatis-generator”
选择bena,dao,xml存放路径:
点击0k,生成文件如下:
注意:
这里映射的bean文件中自动将表字段“_”去掉,并转为驼峰命名形式。
需要我们进行mybatis.configuration配置:
mybatis.configuration.map-underscore-to-camel-case=true
Dao中自动生成的基础sql:
public interface StudentDao {int deleteByPrimaryKey(BigDecimal id);int insert(Student record);int insertSelective(Student record);Student selectByPrimaryKey(BigDecimal id);int updateByPrimaryKeySelective(Student record);int updateByPrimaryKey(Student record);}
我们创建cotroller来测试下dao
@RequestMapping(value = "/addStudent", headers = "Content-Type=application/json;charset=UTF-8", method = RequestMethod.POST)public Student addStudent(@RequestBody Map args) { Student student = new Student(); student.setAge(BigDecimal.valueOf(18)); String name = (String) args.get("name"); student.setName(name);int result = studentDao.insertSelective(student); log.info("result:{}",result);return student;}
Postman 测试接口:
表中:
基本功能验证ok。
Mybatis插件帮我们自动生成了一些常用的sql语句,后续其他的就需要自己去编写。这里可以推荐使用无xml模式。直接在Dao中编写sql。
例如我想查询所有学生信息,则可以这样操作:
@Select(value="select *from Student") List<Student> selectAllStudent();
小结:
idea中使用mybatis插件来生成表对应的bean,dao和xml文件,大大节省开发时间,避免了人工拼写字段错误不规范的问题。再加上无xml sql编写,使得功能开发效率大大提升。
源码下载见百度网盘:https://pan.baidu.com/s/1AufvxeIjw885ZAm3wHgZFA
请关注微信公众号“大圣的如意棒”,回复“yyds” 获取提取码。