当前位置:网站首页>A usage exploration of entitymanagerfactory and entitymanager
A usage exploration of entitymanagerfactory and entitymanager
2022-07-23 11:07:00 【Road of Kings 001】
Some time ago, I designed a JAVA Service program , use JPA As the database access interface layer .
JPA The main tool of , Namely EntityManagerFactory and EntityManager 了 . among ,EntityManagerFactory Is build EntityManager Our factory ,EntityManager You can manipulate the database .
Main operations of database , Actually, it's adding, deleting, modifying and checking . at present , Use EntityManager The method of adding, deleting, modifying and checking is as follows :
Inquire about
CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder(); //em by EntityManager
CriteriaQuery<Test> crit = criteriaBuilder.createQuery(Test.class);
Root<Test> root = crit.from(Test.class);
crit.select(root);
//Predicate Corresponding search criteria
Predicate predicate = criteriaBuilder.and(
criteriaBuilder.equal(root.get("inuse"), true)
);
// Query results
test = em
.createQuery(crit.where(predicate))
.getResultList();Add or change
//em by EntityManager
em.getTransaction().begin();
//test Is an entity class ,merge Will implement existing changes , There is no addition , Subject to the judgment of the primary key
em.merge(test);
em.getTransaction().commit();Delete
//em by EntityManager
em.getTransaction().begin();
//test Is an entity class ,remove Will realize deletion
em.remove(test);
em.getTransaction().commit();It is worth noting that , For complex statements , Such as join,JPA No good support . I tried , The better way is to write by yourself SQL sentence , Perform the following process :
NativeQueryImpl queryImpl = em.createNativeQuery(sql).unwrap(NativeQueryImpl.class);
queryImpl.setResultTransformer(Transformers.aliasToBean(Test.class));
Test db = (Test)queryImpl.getSingleResult();In the beginning , When executing these statements , The process of discovery is always creation EntityManager On and off EntityManager.
Find out EntityManager The bottom layer uses a connection pool to maintain connections , It is found that there are not many database accesses , Just try to store the data of the same address in one Map in , When the same URL when , Perform an execution visit .
Discover this method : The visit is indeed quite efficient , But data is often inaccessible .
find EntityManager and EntityManagerFactory The official documents for learning .
EntityManagerFactory About EntityManagerFactory The introduction of is :
“Interface used to interact with the entity manager factory for the persistence unit.
When the application has finished using the entity manager factory, and/or at application shutdown, the application should close the entity manager factory. Once an EntityManagerFactory has been closed, all its entity managers are considered to be in the closed state.”
Namely EntityManagerFactory It is an interface in the persistence unit that interacts with entity management .EntityManagerFactory Mainly used for management EntityManager, And when EntityManagerFactory closed ,EntityManager It will also shut down .
and EntityManager The official document of is :
“Interface used to interact with the persistence context.
An EntityManager instance is associated with a persistence context. A persistence context is a set of entity instances in which for any persistent entity identity there is a unique entity instance. Within the persistence context, the entity instances and their lifecycle are managed. The EntityManager API is used to create and remove persistent entity instances, to find entities by their primary key, and to query over entities.
The set of entities that can be managed by a given EntityManager instance is defined by a persistence unit. A persistence unit defines the set of all classes that are related or grouped by the application, and which must be colocated in their mapping to a single database.”
The basic meaning is :EntityManager example ( Namely EntityManager In fact, the function is embodied through examples ) Interact with and persistent environments . A persistent environment is a collection of entities .EntityManager Of API Used for adding, deleting, modifying and querying ( Based on the concept of persistent environment ). The persistence unit can manage the set of persistent instances . Persistent unit management requires a defined database mapping to complete management .
With this official document , The author understands why EntityManagerFactory The need when persistence.xml. Because the definition of persistence layer 、 Basic configuration , And the database relationship is all in persistence.xml in .
also , In fact, the description of this official document also :EntityManager Is the specific operation of adding, deleting, modifying and querying , but EntityManagerFactory Just defined the environment of persistent storage unit .
therefore , The method that can be used is :EntityManagerFactory Store in Map in , Then generate EntityManager Add, delete, modify and check .
It is worth noting that : Want to operate correctly , Must ensure EntityManager The operation of is single task , therefore ,synchronized Keywords become a better choice .
Tested , Use this method as an interface to the persistence environment , It's still very efficient .1000 visit ,300 Seconds to complete ( Each visit is at 0.5 Second effect , Meet network access requirements ).
reference :
边栏推荐
- pycharm占用c盘
- Master slave synchronization step read / write separation + self encountered error sharing
- Huawei executives talk about the 35 year old crisis. How can programmers overcome the worry of age?
- pyqt5使用QPainter绘制坐标轴并显示散点图
- 达人专栏 | 还不会用 Apache Dolphinscheduler?大佬用时一个月写出的最全入门教程
- 一次 MySQL 误操作导致的事故,「高可用」都不好使了
- [Anaconda environmental management and package management]
- With only 5000 lines of code, AI renders 100 million landscape paintings on v853
- PyTorch(五)——PyTorch进阶训练技巧
- 防止神经网络过拟合的五种方法
猜你喜欢
随机推荐
赫克Hurco工控机维修WinMax数控机床控制器维修
6、重心坐标插值和图形渲染管线
Redis source code and design analysis -- 6. Compressed list
【社媒营销】出海新思路:Whatsapp Business替代Facebook
C1 -- vivado configuration vs code text editor environment 2022-07-21
C1--Vivado配置VS Code文本编辑器环境2022-07-21
pyqt5使用QPainter绘制坐标轴并显示散点图
Redis source code and design analysis -- 7. Quick list
图片模糊处理批量生产模糊数据集
华为高层谈 35 岁危机,程序员如何破年龄之忧?
Redis source code and design analysis -- 5. Integer set
js中拼接字符串,注意传参,若为字符串,则需要加转义字符
Deploy metersphere
大规模后台导出Excel无法并发
Why does MySQL index use b+ tree?
SPR:SUPERVISED PERSONALIZED RANKING BASED ON PRIOR KNOWLEDGE FOR RECOMMENDATION
H1 -- HDMI interface test application 2022-07-15
Thing JS notes
Database process stuck solution
A case study on the collaborative management of medical enterprise suppliers, hospitals, patients and other parties by building a low code platform









