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


    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>
    View Code

    配置类

    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 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.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>
    View Code

    实体类

    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"})

    运行启动类

     

    古人学问无遗力,少壮工夫老始成。 纸上得来终觉浅,绝知此事要躬行。
  • 相关阅读:
    ContentDisposition的使用方法
    winform上传文件解决方案
    C#中的委托和事件
    Sql Update语句使用表别名的方法(多种方法,经典)
    查找在菜单里提交的报表所在职责
    查找在标准请求组里提交的报表所在的职责
    根据报表文件名称关键字查找报表的执行文件名称等信息
    根据窗口名称查找关键字弹性域用到的表,列等信息
    EBS中取profile值的用法
    查找运行请求时间,参数等(可以是某用户的,某个报表)
  • 原文地址:https://www.cnblogs.com/wf-zhang/p/14893274.html
Copyright © 2020-2023  润新知