永发信息网

如何利用SQL中数据使用FreeMarker生成JAVA实体bean代码

答案:2  悬赏:80  手机版
解决时间 2021-04-06 03:28
如何利用SQL中数据使用FreeMarker生成JAVA实体bean代码
最佳答案
利用freemarker生成JAVA BEAN

Freemarker模板代码如下:

package ${packageName};


pulic class ${className} {
<#list attrs as a>
private ${a.type} ${a.field};


<#list attrs as a>
public void set${a.field?cap_first}(${a.type} ${a.field}){
this.${a.field} = ${a.field};
}

public ${a.type} get${a.field?cap_first}(){
return this.${a.field};
}


}

Java代码如下

package com.my.learn.freemarker;
public class Attr{
public String field;
public String type;

public Attr(String field, String type){
this.field = field;
this.type = type;
}

public String getField(){
return this.field;
}

public String getType(){
return this.type;
}

public void setField(String field){
this.field = field;
}

public void setType(String type){
this.type = type;
}
}

package com.my.learn.freemarker;
import java.io.File; import java.io.IOException; import java.io.StringWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException;
public class FmAppUseage {

public static void main(String[] args){
List list = new ArrayList();
list.add(new Attr("username", "String"));
list.add(new Attr("password", "String"));
list.add(new Attr("age", "int"));
list.add(new Attr("hobby", "String"));

Map root = new HashMap();
root.put("packageName", "com.my.learn.freemarker");
root.put("className", "User");
root.put("attrs", list);
root.put("author", "adams");

Configuration cfg = new Configuration();
String path = FmAppUseage.class.getResource("/").getPath()+"template";
try {
cfg.setDirectoryForTemplateLoading(new File(path));
Template template = cfg.getTemplate("/demo.ftl");
StringWriter out = new StringWriter();
template.process(root, out);

System.out.println(out.toString());
} catch (IOException e) {
System.out.println("Cause==>" + e.getCause());
} catch (TemplateException e) {
System.out.println("Cause==>" + e.getCause());
}
}
}

输出结果如下:

package com.my.learn.freemarker;

pulic class User {
private String username;
private String password;
private int age;
private String hobby;

public void setUsername(String username){
this.username = username;
}

public String getUsername(){
return this.username;
}

public void setPassword(String password){
this.password = password;
}

public String getPassword(){
return this.password;
}

public void setAge(int age){
this.age = age;
}

public int getAge(){
return this.age;
}

public void setHobby(String hobby){
this.hobby = hobby;
}

public String getHobby(){
return this.hobby;
}

}

当在笔者刚做测试时,将Attr的类定义在了FmAppUseage类的内部,导致不能正常运行,只能将其移除单独成一个类时,便能正常运行了。 转载仅供参考,版权属于原作者。祝你愉快,满意请采纳哦
全部回答
  • 1楼网友:第四晚心情
  • 2021-04-05 17:19
any-java是个java代码模板生成工具,你可以看看。apusic的ide也有类似功能,最笨的方法还可以用hibernate的plugin搞定。如果你只想要实体对象,自己读数据库的数据字典写一个好了,没几行代码。
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯