[Mybatis] 根据实体类创建数据库

​ 首先说一下,研究这个的契机是什么,今天刚从github上clone下来一个项目,想跑一下,结果发现没有sql,而这个开源项目又已经很久没更新了,也不太好找维护者,所以,没有办法,只能想办法自己创建数据库,而当我看到成堆的实体类时,,emmm,算了,找个简单的办法吧。

​ 因此,就找到了这个jar包 mybatis-enhance-actable

​ 那么就开始实战吧。

pom文件

<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.4.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<!-- mybatis -->
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.0.1</version>
		</dependency>

    <!-- 生成数据库 -->
		<dependency>
			<groupId>com.gitee.sunchenbin.mybatis.actable</groupId>
			<artifactId>mybatis-enhance-actable</artifactId>
			<version>1.4.1.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.1.18</version>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>8.0.22</version>
		</dependency>

	</dependencies>

Spring配置文件

​ 首先是配置sql信息的配置类MyTableConfig.java

package com.yeafel.evaluation.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

@Configuration
/** 包位置是固定不变的*/
@ComponentScan(basePackages = {"com.gitee.sunchenbin.mybatis.actable.manager.*"})
public class MyTableConfig {
	// mysql所有的配置来自第二章,配置文件
    @Value("${spring.datasource.driver-class-name}")
    private String driver;
	//数据库连接
    @Value("${spring.datasource.url}")
    private String url;
	//数据库账号
    @Value("${spring.datasource.username}")
    private String username;
	//数据库密码
    @Value("${spring.datasource.password}")
    private String password;

  /** 
  * 配置数据源
  */
    @Bean
    public DruidDataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setMaxActive(30);
        dataSource.setInitialSize(10);
        dataSource.setValidationQuery("SELECT 1");
        dataSource.setTestOnBorrow(true);
        return dataSource;
    }

  /**
  * 数据源
  */
    @Bean
    public DataSourceTransactionManager dataSourceTransactionManager() {
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource());
        return dataSourceTransactionManager;
    }

  /**
  * 	
  */
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory() throws Exception{
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource());
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath*:com/gitee/sunchenbin/mybatis/actable/mapping/*/*.xml"));
        sqlSessionFactoryBean.setTypeAliasesPackage("com.yeafel.evaluation.dataobject.entity.*");
        //上述classpath*:com/gitee/sunchenbin/mybatis/actable/mapping/*/*.xml固定的包路径
        //com.xxx.xxx.entity.*替换成你的实体类地址
        return sqlSessionFactoryBean;
    }
}

import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@AutoConfigureAfter(MyTableConfig.class)//上面第一点配置文件类
public class MyBatisMapperScannerConfig {

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() throws Exception{
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
            mapperScannerConfigurer.setBasePackage("com.yeafel.evaluation.dataobjet.mapper.*;com.gitee.sunchenbin.mybatis.actable.dao.*");
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
        //com.xxx.xxx.mapper.*替换成你的mapper地址
        //com.gitee.sunchenbin.mybatis.actable.dao.*固定的包
        return mapperScannerConfigurer;
    }

}

上述配置类中,主要注意的就是两个类中的entity和mapper地址,尤其是mapper地址,只传*mapper.java的位置就可以。

配置文件

配置类中用到的配置,直接放在默认的application.yml中即可

# mysql 配置
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3307/eval_teac?characterEncoding=utf-8&useSSL=false
# mybatis 生成数据库配置
mybatis:
	table:
		auto: update
  model:
    pack: com.**.**.entity // 你的实体类路径
  database:
  	type: mysql

mysql的配置是普通的mysql标准配置,不做解释,那么详细说一下mybatis的配置。

mybatis.table.auto=update自动生成表的方式,其中包含:

update: 每次加载hibernate时根据实体类生成数据库,并且参数属性更新时,表中的属性会同步更新,但是不会覆盖表(不会删除原数据)
create: 每次加载hibernate时根据实体类生成数据库,并且会删除原表重建新表
none: 不做任何操作
add: 只对新增做处理,不会更新原有数据

mybatis.model.pack=com.**.**.entity实体类的路径,如项目在java下有com.exccedy.test.entity,那么这里就要替换为上述路径,该配置的作用时指明实体类的位置,加载时进行加载,同时需要注意,实体类中也需要做配置,配置稍后在实体类代码时标注。

mybatis.database.type=mysql表明要创建的是什么类型的数据库,还有很多可以选择,这里简单说一下,毕竟是以mysql为主的文章。

oracle
sqlserver
postgresql
mysql

实体类

实体类主要是注解的配置

import com.gitee.sunchenbin.mybatis.actable.annotation.IsAutoIncrement;
import com.gitee.sunchenbin.mybatis.actable.annotation.Column;
import com.gitee.sunchenbin.mybatis.actable.annotation.Table;

import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;

@Table(name = "test")
@Data // lombok
public class Test{

  
	@Column(name="action_id",type=MySqlTypeConstant.BIGINT, length = 11, isKey = true, isAutoIncrement = true,isNull = false)
    private Long actionRoleId;

    /** 角色id */
    private Long roleId;

    /** 功能id */
    private Long actionId;
}

这是第一种使用方式,是比较直观的。那么说一下配置的含义。

  • @Table 表明这是需要扫描的类,并生成name中的表,如name=“test”,那么就会生成test的数据库表。

  • @Column 显而易见这是列,其中的参数有很多,就不一一列举,只说一下文中用到。

    • name 列名
    • type 参数类型
    • length 参数长度,默认255
    • isKey 是否是主键,默认false
    • isAutoIncrement 是否自增,默认false
    • isNull 是否为空,默认true

还有第二种方式,注解拆分

import com.gitee.sunchenbin.mybatis.actable.annotation.Column;
import com.gitee.sunchenbin.mybatis.actable.annotation.ColumnType;
import com.gitee.sunchenbin.mybatis.actable.annotation.IsAutoIncrement;
import com.gitee.sunchenbin.mybatis.actable.annotation.Table;
import com.gitee.sunchenbin.mybatis.actable.command.BaseModel;
import com.gitee.sunchenbin.mybatis.actable.constants.MySqlTypeConstant;
import javax.persistence.Id;
import java.util.Date;

/**
 * 第二种定义方式,使用@Table和@Column定义字段,具体内容用具体注解定义
 * 例如@Id,@IsNotNull,@isAutoIncrement等等
 * 如果没有设置name,会直接把变量名按照驼峰规则转换,如果没有设置类型也会自动转换Java的类型到SQL类型
 *
 */
@Table(name = "test1")
public class Test1 extends BaseModel {

    @Id
    @IsAutoIncrement
    @Column
    private Integer    id;
  
  	@Column
  	private String name;
  
  	@Column
  	@ColumnType(value = MySqlTypeConstant.VARCHAR, length=11)
  	private String address;
}
  • @Column 表明是列
  • @ColumnType 表明参数类型,不使用后自动加载,
    • value 类型
    • length 长度,默认255

第三种方式,是最简单的方式,全部交给自动加载,自动加载会更佳驼峰规则转换

import com.gitee.sunchenbin.mybatis.actable.annotation.IsAutoIncrement;
import com.gitee.sunchenbin.mybatis.actable.annotation.IsKey;
import com.gitee.sunchenbin.mybatis.actable.annotation.Table;

/**
 * 第三种定义方式,懒人定义,按照驼峰规则转换
 * 不需要对每个字段设置@Column
 * 这里没有继承BaseModel,因为BaseModel离有OrderBy等参数,也会对其进行构建字段
 *
 * @author 徐森威
 * @date 2020/12/24
 */

@Table(isSimple = true)
public class UserLogin {

   @IsKey
   @IsAutoIncrement
   private Integer    id;

   private String name;

   private String type;
}

运行结果

日志打印如下,即为成功
在这里插入图片描述

同时观察数据库

在这里插入图片描述

至此,实体类转化为数据库成功!

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AntvictorPlus

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值