最近公司的零代码开发平台数据中心需要重构,需要在页面上创建表模型添加修改字段。涉及到动态生成表结构,动态生成模型实体类动态查询表字段等等,经过调研发现hibernate在这方面是很方便的,调用内置API就能完成系列操作,下面贴出核心代码:
/**
* @author cjbi
*/
public class DynamicDdlTest {
@Autowired
private EntityManagerFactory entityManagerFactory;
/**
* 运行期的持久化实体没有必要一定表示为像POJO类或JavaBean对象那样的形式。
* Hibernate也支持动态模型在运行期使用Map)和象DOM4J的树模型那样的实体表示。
* 使用这种方法,你不用写持久化类,只写映射文件就行了。
**/
public static final String XML_MAPPING = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<!DOCTYPE hibernate-mapping PUBLIC\n" +
" \"-//Hibernate/Hibernate Mapping DTD 3.0//EN\"\n" +
" \"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd\">\n" +
"<hibernate-mapping>\n" +
" <class entity-name=\"Student\" table=\"t_student\">\n" +
" <id name=\"id\" type=\"java.lang.Long\" length=\"64\" unsaved-value=\"null\">\n" +
" <generator class=\"identity\" />\n" +
" </id>" +
" <property type=\"java.lang.String\" name=\"username\" column=\"username\"/>\n" +
" <property name=\"password\" type=\"java.lang.String\" column=\"password\"/>\n" +
" <property name=\"sex\" type=\"java.lang.String\" column=\"sex\"/>\n" +
" <property name=\"age\" type=\"java.lang.Integer\" column=\"age\"/>\n" +
" <property name=\"birthday\" type=\"java.util.Date\" column=\"birthday\"/>\n" +
" </class>" +
"</hibernate-mapping>";
@Test
public void testDynamicDdl() {
SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
StandardServiceRegistry serviceRegistry = sessionFactory.getSessionFactoryOptions().getServiceRegistry();
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
sessionFactory.getSessionFactoryOptions();
//读取映射文件
metadataSources.addInputStream(new ByteArrayInputStream(XML_MAPPING.getBytes()));
Metadata metadata = metadataSources.buildMetadata();
//创建数据库Schema,如果不存在就创建表,存在就更新字段,不会影响已有数据
SchemaExport schemaExport = new SchemaExport();
schemaExport.createOnly(EnumSet.of(TargetType.DATABASE), metadata);
Metadata metadata = metadataSources.buildMetadata();
//创建会话工厂
SessionFactory newSessionFactory = metadata.buildSessionFactory();
//保存对象
Session newSession = newSessionFactory.openSession();
for (int i = 0; i < 100; i++) {
Map<String, Object> student = new HashMap<>();
student.put("username", "张三" + i);
student.put("password", "adsfwr" + i);
student.put("sex", i % 2 == 0 ? "male" : "female");
student.put("age", i);
student.put("birthday", new Date());
newSession.save("Student", student);
}
//查询所有对象
Query query = newSession.createQuery("from Student");
List list = query.getResultList();
System.out.println("resultList: " + list);
//关闭会话
newSession.close();
}
}