首页 > 数据库 >java通过实体类生成数据库表 并生成注释

java通过实体类生成数据库表 并生成注释

时间:2023-06-05 15:56:54浏览次数:44  
标签:实体类 java springframework 生成 dataSource org mybatis import com

java通过实体类生成数据库表 并生成注释

 

方式一     使用A.C.Table

 

A.C.Table是对Mybatis做的增强功能,实现了mybatis自动建表的能力

官方地址:https://gitee.com/sunchenbin/mybatis-enhance

文档地址:https://www.yuque.com/sunchenbin/actable/ag3y1y

 

项目结构

 

 

 

pom文件

<dependencies>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>

<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>

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

<!--创建表的插件-->
<dependency>
<groupId>com.gitee.sunchenbin.mybatis.actable</groupId>
<artifactId>mybatis-enhance-actable</artifactId>
<version>1.5.0.RELEASE</version>
</dependency>

<!--druid数据源-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.21</version>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>
</dependencies>


复制代码
<dependencies>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.0</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

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

        <!--创建表的插件-->
        <dependency>
            <groupId>com.gitee.sunchenbin.mybatis.actable</groupId>
            <artifactId>mybatis-enhance-actable</artifactId>
            <version>1.5.0.RELEASE</version>
        </dependency>

        <!--druid数据源-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.21</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.13</version>
        </dependency>
    </dependencies>
复制代码

 

 

配置类

package com.example.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 DataSourceConfig {

@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 PropertiesFactoryBean configProperties() throws Exception{
PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
propertiesFactoryBean.setLocations(resolver.getResources("classpath*:application.yml"));
return propertiesFactoryBean;
}

@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.example.entity.*");
return sqlSessionFactoryBean;
}
}

DataSourceConfig


复制代码
package com.example.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 DataSourceConfig {

    @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 PropertiesFactoryBean configProperties() throws Exception{
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        propertiesFactoryBean.setLocations(resolver.getResources("classpath*:application.yml"));
        return propertiesFactoryBean;
    }

    @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.example.entity.*");
        return sqlSessionFactoryBean;
    }
}
复制代码

package com.example.config;

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(DataSourceConfig.class)
public class MyBatisMapperScannerConfig {

@Bean
public MapperScannerConfigurer mapperScannerConfigurer() throws Exception{
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setBasePackage("com.example.mapper.*;com.gitee.sunchenbin.mybatis.actable.dao.*");
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
return mapperScannerConfigurer;
}

}

MyBatisMapperScannerConfig

复制代码
package com.example.config;

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(DataSourceConfig.class)
public class MyBatisMapperScannerConfig {

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() throws Exception{
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setBasePackage("com.example.mapper.*;com.gitee.sunchenbin.mybatis.actable.dao.*");
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
        return mapperScannerConfigurer;
    }

}
复制代码

 

 

 

 

实体类

复制代码
package com.example.entity;

import com.gitee.sunchenbin.mybatis.actable.annotation.Column;
import com.gitee.sunchenbin.mybatis.actable.annotation.IsAutoIncrement;
import com.gitee.sunchenbin.mybatis.actable.annotation.IsKey;
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 lombok.Data;
import java.util.Date;

@Data
@Table(name = "my_user22",comment = "测试表")//设置表名  注释
public class User extends BaseModel {

    @IsAutoIncrement   //自增
    @IsKey             //主键
    @Column(comment = "用户ID")//字段注释
    private Long id;

    @Column(comment = "昵称",length = 20)
    private String nickName;

    @Column(comment = "头像",length = 100)
    private String avatar;

    @Column(comment = "用户名",length = 50)
    private String username;

    @Column(comment = "密码",length = 200)
    private String password;

    @Column(comment = "邮箱",length = 100)
    private String email;

    @Column(name = "create_time",type = MySqlTypeConstant.DATETIME,comment = "创建时间")
    private Date createTime;

    @Column(name = "update_time",type = MySqlTypeConstant.DATETIME,comment = "修改时间")
    private Date updateTime;
}
复制代码

 

配置文件yml

复制代码
server:
  port: 8082
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/mydemo?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8&useSSL=false
    username: root
    password: password
mybatis:
  table:
    auto: add
    #create        系统启动后,会将所有的表删除掉,然后根据model中配置的结构重新建表,该操作会破坏原有数据。
    #update        系统会自动判断哪些表是新建的,哪些字段要修改类型等,哪些字段要删除,哪些字段要新增,该操作不会破坏原有数据。
    #none         系统不做任何处理。
    #add        新增表/新增字段/新增索引/新增唯一约束的功能,不做修改和删除 (只在版本1.0.9.RELEASE及以上支持)。
  model:
    pack: com.example.entity #扫描用于创建表的对象的包名,多个包用“,”隔开
  database:
    type: mysql #数据库类型 目前只支持mysql
复制代码

 

运行启动类

 

 

数据库

 

 

 

 

 

 方式二     使用SpringData-JPA

 

项目结构

 

 

pom文件

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

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>


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


复制代码
  <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
复制代码

 

实体类

复制代码
package com.example.entity;

import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import org.springframework.format.annotation.DateTimeFormat;
import javax.persistence.*;
import java.util.Date;


@Entity
@javax.persistence.Table(name = "my_user") //设置表名
@org.hibernate.annotations.Table(appliesTo = "my_user", comment = "测试信息")//设置表注释
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)  //mysql自动增长
    @Column(name ="id",nullable = false,columnDefinition = "int(11) COMMENT '用户ID'")
    private Long id;

    @Column(name ="avatar",nullable = false,columnDefinition = "varchar(100) COMMENT '头像'")
    private String avatar;

    @Basic
    @Column(name ="username",nullable = false,columnDefinition = "varchar(50) COMMENT '用户名'")
    private String username;

    @Column(name ="password",nullable = false,columnDefinition = "varchar(50) COMMENT '密码'")
    private String password;

    @Column(name ="nickName",nullable = false,columnDefinition = "varchar(20) COMMENT '昵称'")
    private String nickName;

    @Column(name ="email", columnDefinition = "varchar(20) COMMENT '邮箱'")
    private String email;

    @CreationTimestamp
    @Column(name ="create_time",nullable = false,columnDefinition = "DATETIME COMMENT '创建时间'")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date createTime;

    @UpdateTimestamp
    @Column(name ="update_time",nullable = false,columnDefinition = "DATETIME COMMENT '修改时间'")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date updateTime;

}
复制代码

 

配置文件yml

复制代码
server:
  port: 8082

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/mydemo?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8&useSSL=false
    username: root
    password: password

    #jpa配置  更新或自动生成表  控制台打印sql
  jpa:
    database: mysql
    show-sql: true
    hibernate:
      ddl-auto: update
复制代码

 

启动类需要扫描实体类所在的包   

@EntityScan(basePackages={"com.example.entity"})

 

 

运行启动类

 

 

 

 

 

 

标签:实体类,java,springframework,生成,dataSource,org,mybatis,import,com
From: https://www.cnblogs.com/Amos-Turing/p/17457954.html

相关文章

  • Java体系面试题(2022)(三)
    全部试题及答案下载多线程&并发篇1、说说Java中实现多线程有几种方法创建线程的常用三种方式:1.继承Thread类2.实现Runnable接口3.实现Callable接口(JDK1.5>=)4.线程池方式创建通过继承Thread类或者实现Runnable接口、Callable接口都可以实现多线程,不过实现Runnable接......
  • java基础语法02-面向对象编程
    1面向对象基础1.1方法1.2构造方法1.3方法重载1.4继承1.5多态1.6抽象类1.7接口1.8静态字段和静态方法1.9包1.10作用域1.11内部类1.12classpath和jar1.13class版本1.14模块2java核心类......
  • java实现:根据 map的value值获取key值
    /***根据map的value值获取key值*@parammap*@paramvalue*@return*/publicstaticStringgetKeyFromValue(Map<String,String>map,Stringvalue){StringmKey="";Set<String>keySet=......
  • Java表达式引擎
    执行效率在本地简单测试这几种表达式的执行时间,在频繁执行中mvel表现较好,以下数据仅供参考,未取平均值。次数ognlmvelspeljexlgroovy效率排序10次耗时(毫秒)677215164547jexl>ognl>mvel>spel>groovy100次耗时(毫秒)8377168801487mvel>jexl>ognl>spel>gr......
  • 【程序人生】Java Web 开发脚手架调研
    文章目录GiteeMostValueProject铭飞BootDoRuoYijeecg-bootrenren-fast调研时间2019.06.18GiteeMostValueProject铭飞/MCMS4.7.0bootdoruoyi3.4jeecg-bootrenren-fast托管仓库https://gitee.com/mingSoft/MCMShttps://gitee.com/lcg0124/bootdohttps://gitee.com/y_pro......
  • Java之基于注解的Excel导出
    数据库Excel导出操作代码过于冗长惨不忍睹,无法复用。【推荐使用阿里巴巴组件:关于Easyexcel|EasyExcel】目录第一步:自定义注解:第二步:实体类:第三步:解析工具类:第四步:使用:依赖:<dependency><groupId>cn.afterturn</groupId><artifactId>easypoi-base<......
  • 【JAVA 8】 List 使用Lambda表达式操作对象字段进行升序、降序
    总结使用Lambda表达式轻松对集合进行排序1、需要排序的对象implementsComparable接口,并重写compareTo方法指明默认排序的字段2、使用java8的API轻松实现对List的排序代码中也涉及了一些java8的语法嘻嘻,对新语法我也不熟悉Mainpublicstaticvoidmain(String[]args){......
  • 【IDE】IntelliJ IDEA 插件之Alibaba Java Coding Guidelines - 阿里巴巴Java代码检测
    一、安装进入插件安装界面|-File |-Settings |-Plugins输入alibabainstallAlibabaJavaCodingGuidelines重启IDEA,开始使用二、使用编码规范扫描该插件在扫描代码后,将不符合《java开发手册》的代码按Blocker/Critical/Major三个等级进行显示在Snoar中对代码规则有五......
  • 【JAVA】集合、JUC包结构图
    发现Java基础还是不踏实,需要好好修炼一段时间,就从下面的三张图开始学习吧,加油!一、集合框架二、JUC包三、Socket......
  • 【JavaScript】想在JS中使用换行符,我该怎么操作呢?
    使用'\n'换行,而不是'\n'注意前后空格实战demo:$('#text').val('hello'+'\n'+'world');......