简体   繁体   English

从SQL代码自动生成Java休眠代码

[英]Automatic generation of java hibernate code from sql code

Is there a tool able to generate java hibernate code starting from the sql query? 是否存在能够从sql查询开始生成Java休眠代码的工具? (like reverse of what hibernate does, generating selects from java code) It will help me move all my queries to hibernate! (就像冬眠所做的事情相反,它会从Java代码生成选择内容)它将帮助我将所有查询移到冬眠!

I mean if i have a select with parameters like this: 我的意思是,如果我有这样的参数选择:

 select ta.id label, ta.nume value
    from ar 
    left outer join ta ta on idp = ta.ID
    where ta.status = 1
    and (dp = 0 OR ps = idps_)
    and status = 1
order by ta.nume;

to obtain in the end something like this: 最终获得如下内容:

 DetachedCriteria criteria = DetachedCriteria.forEntityName("ar");
    criteria.createAlias("ta", "ta", Criteria.LEFT_JOIN);
    criteria.add(Restrictions.eq("ta.status", 1));
    Criterion eq = Restrictions.eq("ps.id", idps_);
    Criterion isZero = Restrictions.eq("dp.id", 0);
    Criterion or = Restrictions.or(eq, isZero);
    criteria.add(or);
    criteria.add(Restrictions.eq("status", 1));
    ProjectionList projectionList = Projections.projectionList();
    projectionList.add(Projections.property("ta.id"), "value");
    projectionList.add(Projections.property("ta.nume"), "label");
    criteria.setProjection(Projections.distinct(projectionList));
    criteria.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
    criteria.addOrder(Order.asc("ta.nume"));

OR something similar using maps as output... 或者类似的使用地图作为输出...

providing to the tool the path where i store the mappings of the entities/beans with the tables (or the path to the beans, if the beans are annotated) 向该工具提供我存储实体/ bean与表的映射的路径(或如果注释了bean,则为bean的路径)

You have the HQL that is an SQL-like dialect to work with Hibernate. 您拥有HQL,它是一种类似于SQL的方言,可以与Hibernate一起使用。 You use field names from entities instead of those from tables. 您使用实体中的字段名,而不是表中的字段名。 It supports joins etc. 它支持联接等。

In fact, Criteria API has very limited support of joins (at least it was so last time I've tried to used) and I've a few times finished rewriting everything from Criteria API to HQL, so I now simply tread Criteria API as no option. 实际上,Criteria API对联接的支持非常有限(至少我上次尝试使用它是这样),并且我已经完成了几次重写从Criteria API到HQL的所有工作,因此我现在只是简单地将Criteria API设置为没有选择。

In HQL you can also use SQL functions, both in SELECT and in WHERE part, those embedded and those you've written yourself. 在HQL中,您还可以在SELECT和WHERE部分中使用SQL函数,嵌入式函数和您自己编写的函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM