Hibernate根据注解实体类建表--只负责建表

直接上代码

1.sql生成类

package cn.edu.nyist.secondhandbook.hibernate;

import cn.edu.nyist.secondhandbook.entity.*;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.boot.registry.internal.StandardServiceRegistryImpl;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.ImprovedNamingStrategy;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.tool.hbm2ddl.SchemaUpdate;

@Slf4j
public class HibernateAnnoGeneratorCode {
    public static void main(String[] args) {
        /**
         *
         *
         * <dependency>
             <groupId>org.projectlombok</groupId>
             <artifactId>lombok</artifactId>
             <version>1.16.16</version>
             <scope>provided</scope>
           </dependency>
         * <dependency>
             <groupId>org.hibernate</groupId>
             <artifactId>hibernate-core</artifactId>
             <version>4.3.0.Final</version>
          </dependency>
         *
         */

        Configuration cfg =new Configuration()
                //使用自己改写的继承自ImprovedNamingStrategy的命名策略
                //即 java属性userId --> 数据库表字段USER_ID,如果不需要下一行注释掉即可
                .setNamingStrategy(new NamingStrategy())
                //注解类配置(多个类的话就继续add)
                .addAnnotatedClass(THandUser.class)
                //数据库配置
                .setProperty(AvailableSettings.URL,"jdbc:mysql://localhost:3306/test")
                .setProperty(AvailableSettings.DRIVER,"com.mysql.jdbc.Driver")
                .setProperty(AvailableSettings.USER,"root")
                .setProperty(AvailableSettings.PASS,"root")
                .setProperty(AvailableSettings.DIALECT,"org.hibernate.dialect.MySQL5Dialect")
                //create||update||create-drop||validate
                .setProperty(AvailableSettings.HBM2DDL_AUTO,"update")

                //以下是固定配置
                .setProperty(AvailableSettings.C3P0_MAX_SIZE,"20")
                .setProperty(AvailableSettings.C3P0_MIN_SIZE,"1")
                .setProperty(AvailableSettings.C3P0_TIMEOUT,"5000")
                .setProperty(AvailableSettings.C3P0_MAX_STATEMENTS,"100")
                .setProperty(AvailableSettings.C3P0_IDLE_TEST_PERIOD,"3000")
                .setProperty(AvailableSettings.C3P0_ACQUIRE_INCREMENT,"2")
                .setProperty(AvailableSettings.SHOW_SQL,"true")
                .setProperty(AvailableSettings.FORMAT_SQL,"true")
                .setProperty(AvailableSettings.USE_SECOND_LEVEL_CACHE,"false")
                .setProperty("hibernate.temp.use_jdbc_metadata_defaults","false");

        StandardServiceRegistryImpl serviceRegistry = null;
        try {
            serviceRegistry = (StandardServiceRegistryImpl) new StandardServiceRegistryBuilder()
                                                           .applySettings(cfg.getProperties())
                                                           .build();
            if ("update".equals(cfg.getProperty(AvailableSettings.HBM2DDL_AUTO))){
                SchemaUpdate schemaUpdate = new SchemaUpdate( serviceRegistry, cfg );
                schemaUpdate.setOutputFile("E:\\demo.sql");
                schemaUpdate.setFormat(true);
                schemaUpdate.execute(false, true);
            }else {
                SchemaExport schemaExport = new SchemaExport( serviceRegistry, cfg );
                //sql脚本存放位置
                schemaExport.setOutputFile("E:\\demo.sql");
                //第一个参数:控制台打印sql脚本信息  上边cfg已经允许打印了,这里无需再打印
                //第二个参数:导出脚本信息
                //第二个参数:只删除表
                //第二个参数:只创建表
                schemaExport.execute(false,true,false,false);
            }

        }catch (Exception e){
           log.warn("异常信息为:{}", e.getMessage());
        }finally {
            if (serviceRegistry!=null){serviceRegistry.destroy();}
        }
    }

    //自定义命名策略
    private static class NamingStrategy extends ImprovedNamingStrategy{

        private static final long serialVersionUID = 1L;

        @Override
        public String tableName(String tableName) {
            return super.tableName( tableName ).toUpperCase();
        }

        @Override
        public String columnName( String columnName ) {
            return super.columnName( columnName ).toUpperCase();
        }

        @Override
        public String propertyToColumnName( String propertyName ) {
            return super.propertyToColumnName( propertyName ).toUpperCase();
        }

        @Override
        public String classToTableName(String className) {
            return super.classToTableName(className).toUpperCase();
        }
    }
}

2.注解实体类

package cn.edu.nyist.secondhandbook.entity;

import lombok.Data;
import org.hibernate.annotations.ColumnDefault;

import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;

/**
 * @author fengzi
 */
@Entity
@Table(name = "T_HAND_USER")
@Data
public class THandUser implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer userId;

    @ColumnDefault("CURRENT_TIMESTAMP")
    private Date createTime;

    @ColumnDefault("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP(0)")
    private Date modifyTime;

    /** Other fields */
}

3.生成的SQL

 create table T_HAND_USER (
        USER_ID integer not null auto_increment,
        CREATE_TIME datetime default CURRENT_TIMESTAMP,
        MODIFY_TIME datetime default CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP(0),
        primary key (USER_ID)
    )

极大的方便了开发。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值