下面是一个作为会话 bean 实现的 JAX-RS 服务的示例,它使用 JPA 进行持久性,使用 JAXB 进行消息传递可能看起来像这样。(注意 anEntityManager
被注入到会话 bean 中,为什么要避免这种行为?):
package org.example;
import java.util.List;
import javax.ejb.*;
import javax.persistence.*;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
@Stateless
@LocalBean
@Path("/customers")
public class CustomerService {
@PersistenceContext(unitName="CustomerService",
type=PersistenceContextType.TRANSACTION)
EntityManager entityManager;
@POST
@Consumes(MediaType.APPLICATION_XML)
public void create(Customer customer) {
entityManager.persist(customer);
}
@GET
@Produces(MediaType.APPLICATION_XML)
@Path("{id}")
public Customer read(@PathParam("id") long id) {
return entityManager.find(Customer.class, id);
}
@PUT
@Consumes(MediaType.APPLICATION_XML)
public void update(Customer customer) {
entityManager.merge(customer);
}
@DELETE
@Path("{id}")
public void delete(@PathParam("id") long id) {
Customer customer = read(id);
if(null != customer) {
entityManager.remove(customer);
}
}
@GET
@Produces(MediaType.APPLICATION_XML)
@Path("findCustomersByCity/{city}")
public List<Customer> findCustomersByCity(@PathParam("city") String city) {
Query query = entityManager.createNamedQuery("findCustomersByCity");
query.setParameter("city", city);
return query.getResultList();
}
}
如果要在服务器端和客户端使用相同的域对象。然后我将通过 XML 而不是注释提供 JPA 映射,以避免客户端上的类路径依赖。
了解更多信息
更新
META-INF/persistence.xml
persistence.xml 文件是您指定指向包含 JPA 映射的 XML 文件的链接的位置:
<persistence-unit name="CustomerService" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>CustomerService</jta-data-source>
<mapping-file>META-INF/orm.xml</mapping-file>
</persistence-unit>
META-INF/orm.xml
您将在此文件中添加 JPA 元数据的 XML 表示。
<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings
version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_2_0.xsd">
<entity class="org.example.Customer">
<named-query name="findCustomersByCity">
<query>SELECT c FROM Customer c WHERE c.address.city = :city</query>
</named-query>
<attributes>
<id name="id"/>
<basic name="firstName">
<column name="FIRST_NAME"/>
</basic>
<basic name="lastName">
<column name="LAST_NAME"/>
</basic>
<one-to-many name="phoneNumbers" mapped-by="customer">
<cascade>
<cascade-all/>
</cascade>
</one-to-many>
<one-to-one name="address" mapped-by="customer">
<cascade>
<cascade-all/>
</cascade>
</one-to-one>
</attributes>
</entity>
<entity class="org.example.Address">
<attributes>
<id name="id"/>
<one-to-one name="customer">
<primary-key-join-column/>
</one-to-one>
</attributes>
</entity>
<entity class="org.example.PhoneNumber">
<table name="PHONE_NUMBER"/>
<attributes>
<id name="id"/>
<many-to-one name="customer">
<join-column name="ID_CUSTOMER"/>
</many-to-one>
</attributes>
</entity>
</entity-mappings>
了解更多信息