hibernate hql查询个别字段映射到实体类_Hibernate 运行期动态模型、动态实体建表、动态字段...
程序员文章站
2022-04-13 22:15:50
...
在页面上创建表模型添加修改字段。涉及到动态生成表结构,动态生成模型实体类动态查询表字段等等,经过调研发现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"?>" + " + " "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">" + "" + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + ""; @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 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(); }}
上一篇: centOS 安装postGIS和pgRouting
下一篇: Dom4j解析xml