Understanding JPA,3

Page 3 of 6

Persistence units

Now that the entity class is complete, you can move on to persistence.xml, shown in Listing 3. This is an XML file placed in the META-INF folder; it's used to specify the persistence provider name, entity class names, and properties like the database connection URL, driver, user, password, and so on.

Listing 3. A sample persistence.xml file
<?xml version="1.0"?>
<persistence>
<persistence-unit name="testjpa" transaction-type="RESOURCE_LOCAL">
<provider>
org.apache.openjpa.persistence.PersistenceProviderImpl
</provider>
<class>entity.Customer</class>
<properties>
<property name="openjpa.ConnectionURL" value="jdbc:derby://localhost:1527/D:\OpenJPA\Derby\testdb;create=true"/>
<property name="openjpa.ConnectionDriverName"
value="org.apache.derby.jdbc.ClientDriver"/>
<property name="openjpa.ConnectionUserName" value="admin"/>
<property name="openjpa.ConnectionPassword" value="admin"/>
<property name="openjpa.Log" value="SQL=TRACE"/>
</properties>
</persistence-unit>
</persistence>

Some important things to note about Listing 3 and the persistence.xml file:

  • persistence.xml can have multiple persistence units. Each unit can be used by different JPA vendor or can be used to persist to different databases.
  • The vendor-specific persistence provider name is specified in the <provider> tag. The persistence provider for OpenJPA is org.apache.openjpa.persistence.PersistenceProviderImpl.
  • The entity class names are specified in the <class> tag.
  • The database connection properties can be specified within the <properties> tag. Note that the property name will differ for each vendor.
  • OpenJPA has its own default logging facility, the default level of which is INFO.

The real show

Now that the prep work is out of the way, you're ready to write a class that will insert a record into the CUSTOMER table. This is shown in Listing 4.

Listing 4. sample code for object persistence
public static void main(String[] args) {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("testjpa");
EntityManager em = entityManagerFactory.createEntityManager();
EntityTransaction userTransaction = em.getTransaction();

userTransaction.begin();
Customer customer = new Customer();
customer.setFirstName("Charles");
customer.setLastName("Dickens");
customer.setCustType("RETAIL");
customer.setStreet("10 Downing Street");
customer.setAppt("1");
customer.setCity("NewYork");
customer.setZipCode("12345");
em.persist(customer);
userTransaction.commit();
em.close();
entityManagerFactory.close();
}

Drill down to see what the code in Listing 4 actually does. The action starts with the Persistence class. The javadoc says, "Persistence is a bootstrap class that is used to obtain an EntityManagerFactory," like so:

EntityManagerFactory emf=Persistence.createEntityManagerFactory("testjpa");

The work of the Persistence class is pretty simple:

  • In the classpath resources, the Persistence class searches for javax.persistence.spi.PersistenceProvider files in META-INF/services/directory. It reads the PersistenceProvider implementation class names from each file.
  • It then calls createEntityManagerFactory() on each PersistenceProvider with the persistenceUnitName until it gets a an EntityManagerFactory back that isn't null. The provider name for OpenJPA is org.apache.openjpa.persistence.PersistenceProviderImpl.

How does PersistenceProvider get the right EntityManagerFactory? This is up to the vendor to implement.

EntityManagerFactory is a factory for creating an EntityManager. EntityManagerFactory should be cached and should ideally be called once for each persistence unit name in the whole application.

EntityManager manages entities; it is responsible for their addition, updating, and deletion. You can find an entity without a transaction; however, add, update, and delete operations need to be within a transaction.

If you ignore transaction management in a fetch operation, the entity does not become managed and hence the system will do a trip to the database every time you try to fetch a record from the data store; in such a scenario, you'd end up fetching a separate object every time.

The rest of the code is pretty self-explanatory. It creates a customer object, sets the values to the appropriate properties, and inserts the object to the data store, as you can see in Listing 5.

Listing 5. A code snippet for object persistence
EntityTransaction userTransaction = em.getTransaction();
userTransaction.begin();
em.persist(customer);
userTransaction.commit();

You may have already noticed by now that the code does not set the custId and updatedTime to the customer object explicitly. Because the primary key generation strategy is AUTO, the JPA provider will take care of populating the primary key. Similarly, version fields (updatedTime, in this case) are also automatically populated by the JPA provider.

Now you need to find the record that's been inserted. Finding a record with a primary key is as simple as Customer cust = em.find(Customer.class, objId);, as you can see in Listing 6.

Listing 6. Fetching data as an object
....
OpenJPAEntityManager oem = OpenJPAPersistence.cast(em);
Object objId = oem.getObjectId(customer);
Customer cust = em.find(Customer.class, objId);
....


Because the primary key is unknown up front, the application must cast EntityManager to OpenJPAEntityManager to get the primary key object by passing the customer object that was persisted earlier. This logic might differ for other vendors.

内容概要:本文深入探讨了Django REST Framework(DRF)在毕业设计中的高级应用与性能优化,围绕智能校园系统案例,系统讲解了DRF的核心进阶技术,包括高级序列化器设计、视图集定制、细粒度权限控制、查询优化、缓存策略、异步任务处理以及WebSocket实时通信集成。文章通过详细的代码示例,展示了如何利用DynamicFieldsModelSerializer实现动态字段返回、使用select_related和prefetch_related优化数据库查询、通过Celery实现异步任务、并集成Channels实现WebSocket实时数据推送。同时介绍了基于IP的限流、自定义分页、聚合统计等实用功能,全面提升API性能与安全性。; 适合人群:具备Django和DRF基础,正在进行毕业设计或开发复杂Web API的高校学生及初级开发者,尤其适合希望提升项目技术深度与系统性能的学习者。; 使用场景及目标:①构建高性能、可扩展的RESTful API,应用于智能校园、数据分析、实时监控等毕业设计项目;②掌握DRF高级技巧,如动态序列化、查询优化、缓存、异步任务与实时通信,提升项目竞争力;③优化系统响应速度与用户体验,应对高并发场景。; 阅读建议:此资源以实战为导向,建议读者结合代码逐项实践,重点理解性能优化与架构设计思路,同时动手搭建环境测试缓存、异步任务和WebSocket功能,深入掌握DRF在真实项目中的高级应用。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值