hibernate hql查詢個別欄位對映到實體類_Hibernate 執行期動態模型、動態實體建表、動態欄位...
阿新 • • 發佈:2021-01-30
技術標籤:hibernate hql查詢個別欄位對映到實體類
在頁面上建立表模型新增修改欄位。涉及到動態生成表結構,動態生成模型實體類動態查詢表字段等等,經過調研發現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(); }}