如何定制myeclipse逆向生成ORM映射实体

    ORM比较方便的一点就是能够自动生成实体类和DAO类,可以说当entity和dao生成好了,基本上已经完成了一半的工作,大大提高了开发效率。

    平时我常用的就是myeclipse,生成的过程简单快捷,代码也简洁不繁琐;当然,还有些框架如rapid-framework可以生成比较复杂的实体,而且配置起来也很麻烦。

    但是当我们需要定制生成的实体类时,比如我的数据库的表中没有ID,逆向之后就会将所有字段合成ID,从而生成另一个实体XXXID,如果是自己定义的框架不支持额外的这个实体,应该咋办呢?

    从界面上看,能够让我们定制的地方有这么几个:但是目测第一个template是实体类的一个模板,第二个rev-setting是你用于反向工程的配置(每次进来都会自动填充上次的配置),而第三custom rev-eng strategy则是定制逆向工程过程中的设置。



    为了解决这个问题,我需要定制逆向策略。过程比较简单,参考如下两个链接:

    http://www.myeclipseide.com/documentation/quickstarts/hibernate/#5-6

    http://www.javaplex.com/blog/myeclipse-customizing-hibernate-reverse-engineering/

    以下是我定制的策略,主要就是要去修改主键,将第一个字段当做主键,“骗”过逆向代码,让它认为该实体有主键,从而不会为我们自动合成复合主键。

public class ReverseStrategy extends DelegatingReverseEngineeringStrategy {

	Connection connection;

	public ReverseStrategy(ReverseEngineeringStrategy delegate) {
		super(delegate);
		ConnectionConfiguration cc = new ConnectionConfiguration();
		try {
			Class.forName(cc.getDriverClass());
			connection = DriverManager.getConnection(cc.getConnectionUrl(), cc
					.getUsername(), cc.getPassword());
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public List getPrimaryKeyColumnNames(TableIdentifier identifier) {
		List list = new ArrayList();
		DatabaseMetaData d;
		try {
			d = connection.getMetaData();
			ResultSet rs = d.getColumns(null, "%", identifier.getName(), "%");
			if(rs.next())
			{
			    String strFieldName = rs.getString(4);
			    list.add(strFieldName);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public void close() {
		super.close();
		try {
			connection.close();
//			RemoveId.removeIds();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
			}

}
    完成之后需要删掉源码之中生成的@Id,也需要写个程序处理一下

public class RemoveId {

	private final static String sourcePath = "C:\\xxxx\\xxxx\\xxx\\xx";

	public static void removeIds() throws IOException {
		File dirs = new File(sourcePath);
		if (dirs.isDirectory()) {
			File[] fs = dirs.listFiles();
			for (File file : fs) {
				System.out.println(file.getName());
				String str = FileUtils.readFileToString(file);
				FileUtils
						.writeStringToFile(file, str.replaceAll("@Id", ""));
			}
		}
	}

	public static void main(String[] args) throws IOException {
		removeIds();
	}
}

hibernate tool:http://docs.jboss.org/tools/4.0.0.Final/en/hibernatetools/html_single/index.html#download_base_project


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值