当前位置: 首页 > 知识库问答 >
问题:

Hibernate代码生成:创建抽象/具体模型类对

田马鲁
2023-03-14

给出了什么:

  • 我使用Hibernate代码生成生成我的模型类(Hibernate工具 4)
  • 我想要为每个数据库表提供一个抽象基类,以及一个具体的扩展
  • 基类应包含所有数据库字段(获取/设置)
  • 具体类应从基层开始延伸,对于跨站字段应为空
  • 我用阿帕奇·马文处理我的图书馆
  • 我有一个爪哇配置的SpringMVC环境

我听说您可以覆盖Hibernate工具JAR中的Freemarker模板。但是当我使用Maven时,这是不可能的。?

因为我使用一个java配置的SpringMVC环境,所以如果没有xml的解决方案存在,那就太好了。

解决方案应执行以下操作:

    < li >为MySQL数据库中的每个表创建一个类对 < li >我不是舒尔,但是添加< code>@MappedSuperclass注释?

示例:抽象基类

@Entity
@MappedSuperclass
@Table(name = "employee", catalog = "test", uniqueConstraints = @UniqueConstraint(columnNames = "E_MAIL"))
public abstract class EmployeeBase implements java.io.Serializable {

    private Integer id;

    public Employee() {
    }

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "ID", unique = true, nullable = false)
    public Integer getId() {
        return this.id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

示例:混凝土等级

public class Employee extends EmployeeBase {
   // my transistent fields, for example getFirstAndLastName();
}

共有1个答案

萧秋月
2023-03-14

溶液:

  1. 创建两个反向工程策略(基础和混凝土)
  2. 从Hibernate工具更新免费标记模板.jar
  3. 在 Eclipse(Hibernate插件)中创建代码生成配置,并设置策略和自定义模板。
  4. 切换逆向工程策略并运行两次。

来源:

BaseClassStrategy:

public class BaseClassStrategy extends DelegatingReverseEngineeringStrategy {

    public BaseClassStrategy(ReverseEngineeringStrategy delegate) {
        super(delegate);
    }

    @Override
    public Map<String, MetaAttribute> tableToMetaAttributes(TableIdentifier tableIdentifier) {

        @SuppressWarnings("unchecked")
        Map<String, MetaAttribute> metaAttributes = super.tableToMetaAttributes(tableIdentifier);
        if (metaAttributes == null) {
            metaAttributes = new HashMap<String, MetaAttribute>();
        }

        // Update modifier
        if (!metaAttributes.containsKey("scope-class")) {
            MetaAttribute metaAttribute = new MetaAttribute("scope-class");
            metaAttribute.addValue("public abstract");
            metaAttributes.put(metaAttribute.getName(), metaAttribute);
        }

        // Update class name
        if (!metaAttributes.containsKey("generated-class")) {
            MetaAttribute metaAttribute = new MetaAttribute("generated-class");
            metaAttribute.addValue(tableToAbstractClassName(tableIdentifier));
            metaAttributes.put(metaAttribute.getName(), metaAttribute);
        }

        return metaAttributes;
    }   

    private String tableToAbstractClassName(TableIdentifier tableIdentifier) {
        String className = super.tableToClassName(tableIdentifier);
        int dotIndex = className.lastIndexOf('.');
        return className.substring(0, dotIndex + 1) + className.substring(dotIndex + 1) + "Base";
    }
}

具体班级策略:

public class ConcreteClassStrategy extends DelegatingReverseEngineeringStrategy {

    public ConcreteClassStrategy(ReverseEngineeringStrategy delegate) {
        super(delegate);
    }

    @Override
    public Map<String, MetaAttribute> tableToMetaAttributes(TableIdentifier tableIdentifier) {

        @SuppressWarnings("unchecked")
        Map<String, MetaAttribute>  metaAttributes = super.tableToMetaAttributes(tableIdentifier);
        if (metaAttributes == null) {
            metaAttributes = new HashMap<String, MetaAttribute>();
        }


        String className = super.tableToClassName(tableIdentifier);
        int dotIndex = className.lastIndexOf('.');
        String abstractClassName = className.substring(dotIndex + 1) + "Base";

        // Update extends modifier
        if (!metaAttributes.containsKey("scope-class")) {
            MetaAttribute metaAttribute = new MetaAttribute("extends");
            metaAttribute.addValue(abstractClassName);
            metaAttributes.put(metaAttribute.getName(), metaAttribute);
        }

        return metaAttributes;
    }
}

Hibernate模板:

将以下文件夹结构添加到您的项目中:

src/main/resources
|-> hibernate-templates
    |-> dao
    |-> pojo

从Hibernate工具复制 pojo 和 dao 文件夹.jar并更新以下文件。它只会工作,如果你添加两个文件夹!

Ejb3TypeDeclaration.ftl

<#if ejb3?if_exists>
<#if pojo.isComponent()>
@${pojo.importType("javax.persistence.Embeddable")}
<#else>
@${pojo.importType("javax.persistence.Entity")}
@${pojo.importType("javax.persistence.Table")}(name="${clazz.table.name}"
<#if clazz.table.schema?exists>
    ,schema="${clazz.table.schema}"
</#if><#if clazz.table.catalog?exists>
    ,catalog="${clazz.table.catalog}"
</#if>
<#assign uniqueConstraint=pojo.generateAnnTableUniqueConstraint()>
<#if uniqueConstraint?has_content>
    , uniqueConstraints = ${uniqueConstraint} 
</#if>)
</#if>
</#if>

Ejb3TypeDeclaration.ftl

<#if ejb3?if_exists>
<#if pojo.isComponent()>
@${pojo.importType("javax.persistence.Embeddable")}
<#else>
@${pojo.importType("javax.persistence.MappedSuperclass")}
</#if>
</#if>

波乔.ftl

${pojo.getPackageDeclaration()}
// Generated ${date} by Hibernate Tools ${version}
<#assign classbody>
<#include "PojoTypeDeclaration.ftl"/> {

<#if !pojo.isInterface()>

<#if pojo.getDeclarationName()?ends_with("Base")>
<#include "PojoFields.ftl"/>
</#if>

<#include "PojoConstructors.ftl"/>

<#if pojo.getDeclarationName()?ends_with("Base")>

<#include "PojoPropertyAccessors.ftl"/>

<#include "PojoToString.ftl"/>

<#include "PojoEqualsHashcode.ftl"/>
</#if>

<#else>
<#include "PojoInterfacePropertyAccessors.ftl"/>

</#if>
<#include "PojoExtraClassCode.ftl"/>

}
</#assign>

${pojo.generateImports()}
${classbody}

PojoConstructor.ftl

<#--  /** default constructor */ -->
public ${pojo.getDeclarationName()}() {}

<#if pojo.needsMinimalConstructor()>    
<#-- /** minimal constructor */ -->
public ${pojo.getDeclarationName()}(${c2j.asParameterList(pojo.getPropertyClosureForMinimalConstructor(), jdk5, pojo)}) {
    <#if pojo.getDeclarationName()?ends_with("Base")>
        <#foreach field in pojo.getPropertiesForMinimalConstructor()>
        this.${field.name} = ${field.name};
        </#foreach>
    <#else>
        super(${c2j.asArgumentList(pojo.getPropertyClosureForMinimalConstructor())});        
    </#if>
}
</#if>    

<#if pojo.needsFullConstructor()>
<#-- /** full constructor */ -->
public ${pojo.getDeclarationName()}(${c2j.asParameterList(pojo.getPropertyClosureForFullConstructor(), jdk5, pojo)}) {
    <#if pojo.getDeclarationName()?ends_with("Base")>
        <#foreach field in pojo.getPropertiesForFullConstructor()> 
        this.${field.name} = ${field.name};
        </#foreach>
    <#else>
        super(${c2j.asArgumentList(pojo.getPropertyClosureForFullConstructor())});        
    </#if>
}
</#if>    
 类似资料:
  • 我想在我即将完成的一些工作中使用builder模式,它在一个层次结构中有几个类。基类将至少有9个字段要启动,各个子类可能会添加2-4个字段。这会很快失控,而builder模式正是出于这个原因吸引了我。我在书籍和文章中初步接触了builder模式。他们是有帮助的,但没有关于如何扩展这种模式。我试图自己实现这一点,但是我在每个子类的构造函数中遇到了麻烦,因为我不知道如何将构建器中收集的数据传递给超级类

  • 问题内容: 据我所知,创建一个动态Java代理需要一个接口来处理该代理。但是,Hibernate似乎可以管理其动态代理生成,而无需为实体类提供一个写接口。它是如何做到的?Hibernate文档的唯一线索是这样的事实,即类必须至少具有一个包可见的构造函数才能生成代理。 Hibernate是否使用自定义类加载器进行运行时字节码工程设计?该文档表明情况并非如此。那么他们如何围绕具体实体对象创建代理包装器

  • 本文向大家介绍java验证码生成具体代码,包括了java验证码生成具体代码的使用技巧和注意事项,需要的朋友参考一下 本文实例为大家分享了java验证码生成的示例代码,供大家参考,具体内容如下 以上就是本文的全部内容,希望对大家的学习有所帮助。

  • 无效: 有效: (运输是抽象的) 顺便说一句,我的所有jaxb类都在同一个包中,并且我的JaxbContext是针对这个包配置的。

  • 我正在尝试使用eclipse gmf创建一个基于uml模型的图形编辑器, 为此,我基于我的uml模型创建了一个.gnemodel文件,但在生成的.ecore文件中没有关联

  • 是否有任何JAXB绑定可以告诉JAXB代码生成器将Java类生成为,而不必在XSD中将相应的XML类型标记为? 情况如下: > 我在xsd中定义架构: 我使用内联JAXB绑定(“inline”==“直接在模式中”)来指示应该生成JAXB类的包(): 我使用内联JAXB绑定为我的每个复杂类型(在本例中、和)指示实现类的名称: 我从模式生成JAXB类。这导致: 我自己编写类: 使用这两个类层次结构这样