JavaWeb页面静态化之使用模板+元数据生成数据库表对应的Javabean类

版权声明:《==study hard and make progress every day==》 https://blog.csdn.net/qq_38225558/article/details/83511105

Javabean类,pojo类:无参构造、get/set方法、必要的时候实现Serializable接口【序列化】


我的数据库中t_user表:

功能类:

/**
 * 1.创建配置实例
 * 2.获得模板
 * 3.创建数据模型[数据模型可以是List、Map对象 注意:Map类型的key必须是String类型]
 * 4.将模板和数据模型合并
 * @author 郑清
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring.xml")
public class FreeMarkerTest {

	@Autowired
	private DataSource ds;

	@Test
	public void testGetMetaData() throws Exception {
		//⑤创建数据模型
		Connection conn = ds.getConnection();
		String sql = "select * from t_user";
		PreparedStatement pst = conn.prepareStatement(sql);
		ResultSet rs = pst.executeQuery();//获取结果集
		ResultSetMetaData rsmd = rs.getMetaData();//获取元数据
		int count = rsmd.getColumnCount();//获取表的列数
		HashMap<String, Object> ds = new HashMap<>();//代表数据库的map
		HashMap<String, Object> table = new HashMap<>();//代表表的map
		for (int i = 1; i <= count; i++) {
			// value是一个类型
			// map.put(rsmd.getColumnLabel(i), rsmd.getColumnClassName(i));
			String name = rsmd.getColumnLabel(i);//获取字段名
			String newname = name.substring(0, 1).toUpperCase() + name.substring(1);//将字段的首字母大写,然后拼接   ex:username-->Username

			HashMap<String, Object> tableInfo = new HashMap<>();//tableInfo代表的是一个字段的所有信息
			tableInfo.put("type", rsmd.getColumnClassName(i));//将字段类型存储到map
			tableInfo.put("getname", "get" + newname);
			tableInfo.put("setname", "set" + newname);
			tableInfo.put("name", name);

			table.put(name, tableInfo);// 将tableInfo存储到map中
		}
		// 将表的map添加到数据库的map中
		ds.put("user", table);

		//①创建配置对象
		Configuration cfg = new Configuration(Configuration.VERSION_2_3_28);//注意:这里需要传递一个版本
		File f = new File("E:/eclipse-workspace/JavaWeb_workspace/JavaWeb/src/main/webapp/test");
		//②读取模板文件夹
		cfg.setDirectoryForTemplateLoading(f);//设置要加载的模板文件的路径
		//③设置模板的编码格式
		cfg.setDefaultEncoding("UTF-8");

		//④获取模板对象
		Template template = cfg.getTemplate("java.ftl");//java.ftl是模板名称

		//⑥将模板和数据模型合并 --> 输出模板,生成文件
		PrintWriter pw = new PrintWriter(new File(f, "User.java"));
		template.process(ds, pw);//合并  ds:数据模型  pw:输出流对象
		pw.close();//关闭流
	}
	
}

猜你喜欢

转载自blog.csdn.net/qq_38225558/article/details/83511105