openjpa框架入门_项目框架搭建(二)

时间:2021-08-20 11:55:08

Openjpa2.2+Mysql+Maven+Servlet+JSP

首先说明几点,让大家更清楚整体结构:

官方source code 下载:http://openjpa.apache.org/downloads.html 我下载2.2.2的版本

openjpa框架入门_项目框架搭建(二)

下载后解压缩 openbooks的source code如图:

openjpa框架入门_项目框架搭建(二)

大家可以根据说明自己研究,也可以和我一起往下看,接下来是自己搭建maven管理的web project.

使用eclipse插件创建openbook web project.

1:create a maven project

openjpa框架入门_项目框架搭建(二)

2:select create a simple project(skip archetype select)

openjpa框架入门_项目框架搭建(二)

packing -----------------------war

.openjpa框架入门_项目框架搭建(二)

这是web project,所以创建的project目录结构如下(如果不是或者有出入,那么请检查Maven的 user settings文件指向)

openjpa框架入门_项目框架搭建(二)

下面修改下,使我们的项目,能发布到server上运行.  项目上点击右键,选择属性convert to faceted from...(若符合的,有的可以跳过此步)

openjpa框架入门_项目框架搭建(二)

配置完成后,再来check下,Deployment Assembly (画红线的可以删除,也可不删),各个目录要路径指向正确

openjpa框架入门_项目框架搭建(二)

下面将官方的source code粘贴到我们项目指定的目录(删除client,tools)

openjpa框架入门_项目框架搭建(二)

根据红线,分别把文件copy到指定目录,下面再修改persistence.xml,web.xml和pom.xml 三个文件.

openjpa框架入门_项目框架搭建(二)

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--
 Licensed to the Apache Software Foundation (ASF) under one
 or more contributor license agreements.  See the NOTICE file
 distributed with this work for additional information
 regarding copyright ownership.  The ASF licenses this file
 to you under the Apache License, Version 2.0 (the
 "License"); you may not use this file except in compliance
 with the License.  You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
 software distributed under the License is distributed on an
 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 KIND, either express or implied.  See the License for the
 specific language governing permissions and limitations
 under the License.
-->
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
        http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
    version="2.0">
    <persistence-unit name="OpenBooks" transaction-type="RESOURCE_LOCAL">
        <provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
        
        <class>openbook.domain.Book</class>
        <class>openbook.domain.Inventory</class>
        <class>openbook.domain.PurchaseOrder</class>
        <class>openbook.domain.LineItem</class>
        <class>openbook.domain.Customer</class>
        <class>openbook.domain.Author</class>
        
        <validation-mode>NONE</validation-mode>
        <properties>
        <!-- Use these for MySQL-->
            <property name="javax.persistence.jdbc.driver"   value="com.mysql.jdbc.Driver"/>
            <property name="javax.persistence.jdbc.url"      value="jdbc:mysql://localhost:3306/OpenBooks?characterEncoding=utf8"/>
            <property name="openjpa.jdbc.DBDictionary" value="mysql"/>
            <property name="javax.persistence.jdbc.user"     value="root"/>
            <property name="javax.persistence.jdbc.password" value="root"/>
            
            <!-- OpenJPA不增强
            <property name="openjpa.ClassLoadEnhancement" value="false" />  
            <property name="openjpa.DynamicEnhancementAgent" value="false" />  
            <property name="openjpa.RuntimeUnenhancedClasses" value="supported" />  
             -->
            <property name="openjpa.FetchBatchSize" value="0"/>
            <property name="openjpa.RemoteCommitProvider" value="sjvm" />
            <property name="openjpa.InitializeEagerly" value="true" />
            <property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)" />
            <property name="openjpa.jdbc.QuerySQLCache" value="true(EnableStatistics=true)" />
            
            <property name="openjpa.Log" value="DefaultLevel=INFO, Runtime=INFO, Tool=INFO, SQL=TRACE" />
            <!-- <property name="openjpa.jdbc.ResultSetType" value="forward-only"/>
            <property name="openjpa.jdbc.FetchDirection" value="forward"/>
            <property name="openjpa.jdbc.LRSSize" value="query"/>
            <property name="openjpa.DataCache" value="false"/>
            <property name="openjpa.QueryCache" value="false"/> -->
            <!-- 配置从java ORM annotation 生成数据库结构,配置此步时,需要把对应的java ORM类复制上面的<class/>标签中。 -->
            <!-- <property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema(SchemaAction='drop,add')"/>
            <property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true,PrimaryKeys=true,Indexes=true,schemaAction=refresh)"/> -->
        
        
            
        <!-- Use these for derby
            <property name="javax.persistence.jdbc.driver"   value="org.apache.derby.jdbc.EmbeddedDriver"/>
            <property name="javax.persistence.jdbc.url"      value="jdbc:derby:memory:OpenBooks;create=true"/>
            <property name="javax.persistence.jdbc.user"     value=""/>
            <property name="javax.persistence.jdbc.password" value=""/>

<property name="openjpa.DataCache"                value="true"/>        
            <property name="openjpa.RemoteCommitProvider"     value="sjvm"/>
            <property name="openjpa.InitializeEagerly"        value="true"/>
            
            <property name="openjpa.DynamicEnhancementAgent"  value="false"/>
            <property name="openjpa.RuntimeUnenhancedClasses" value="unsupported"/>
            
            <property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)"/>
            <property name="openjpa.jdbc.QuerySQLCache"       value="true(EnableStatistics=true)"/>
       -->     
        </properties>
    </persistence-unit>
    
</persistence>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>openjpatest</display-name>
    <welcome-file-list>
        <welcome-file>intro.jsp</welcome-file>
    </welcome-file-list>
    <distributable />
</web-app>

POM.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.shen</groupId>
    <artifactId>openjpatest</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <dependencies>
        <dependency>
            <groupId>org.apache.openjpa</groupId>
            <artifactId>openjpa</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>org.antlr</groupId>
            <artifactId>antlr</artifactId>
            <version>3.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.ant</groupId>
            <artifactId>ant</artifactId>
            <version>1.8.1</version>
        </dependency>
        <dependency>
            <groupId>de.java2html</groupId>
            <artifactId>java2html</artifactId>
            <version>5.0</version>
        </dependency>
        
        <dependency>
            <groupId>org.apache.openjpa</groupId>
            <artifactId>openjpa-all</artifactId>
            <version>2.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>servlet-api</artifactId>
            <version>6.0.35</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>jsp-api</artifactId>
            <version>6.0.37</version>
            <scope>provided</scope>
        </dependency>
        
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.18</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
               <version>4.11</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>${project.artifactId}</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <version>2.3.6</version>
                <extensions>true</extensions>
                <configuration>
                    <instructions>
                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
                        <Meta-Persistence>META-INF/persistence.xml</Meta-Persistence>
                    </instructions>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.openjpa</groupId>
                <artifactId>openjpa-maven-plugin</artifactId>
                <version>2.2.1</version>
                <configuration>
                    <includes>**/representations/*.class</includes>
                    <addDefaultConstructor>true</addDefaultConstructor>
                    <enforcePropertyRestrictions>true</enforcePropertyRestrictions>
                </configuration>
                <executions>
                    <execution>
                        <id>enhancer</id>
                        <phase>process-classes</phase>
                        <goals>
                            <goal>enhance</goal>
                        </goals>
                    </execution>
                </executions>
                <dependencies>
                    <dependency>
                        <groupId>org.apache.openjpa</groupId>
                        <artifactId>openjpa</artifactId>
                        <version>2.2.1</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
        <pluginManagement>
            <plugins>
                <!--This plugin's configuration is used to store Eclipse m2e settings
                    only. It has no influence on the Maven build itself. -->
                <plugin>
                    <groupId>org.eclipse.m2e</groupId>
                    <artifactId>lifecycle-mapping</artifactId>
                    <version>1.0.0</version>
                    <configuration>
                        <lifecycleMappingMetadata>
                            <pluginExecutions>
                                <pluginExecution>
                                    <pluginExecutionFilter>
                                        <groupId>org.apache.openjpa</groupId>
                                        <artifactId>openjpa-maven-plugin</artifactId>
                                        <versionRange>[2.2.1,)</versionRange>
                                        <goals>
                                            <goal>enhance</goal>
                                        </goals>
                                    </pluginExecutionFilter>
                                    <action>
                                        <ignore></ignore>
                                    </action>
                                </pluginExecution>
                            </pluginExecutions>
                        </lifecycleMappingMetadata>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>

最后再,修改下OpenBookServiceImpl.java类 举例一个,下面类似(附完整的类)

openjpa框架入门_项目框架搭建(二)

/*
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
*/
package openbook.server;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContextType;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.ParameterExpression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.persistence.metamodel.EntityType;

import openbook.domain.Author;
import openbook.domain.Book;
import openbook.domain.Customer;
import openbook.domain.Inventory;
import openbook.domain.LineItem;
import openbook.domain.PurchaseOrder;
import openbook.domain.Range;
import openbook.domain.ShoppingCart;
import openbook.util.PropertyHelper;
import openbook.util.Randomizer;

import org.apache.openjpa.persistence.criteria.OpenJPACriteriaBuilder;

/**
 * A demonstrative example of a transaction service with persistent entity using Java Persistence API.
 * <br>
 * This example service operates on a persistent domain model to browse {@linkplain Book books},
 * occasionally {@linkplain #placeOrder(ShoppingCart) placing} {@linkplain PurchaseOrder purchase orders},
 * while {@linkplain Inventory inventory} gets updated either by {@linkplain #deliver() delivery} or
 * by {@linkplain #supply() supply}.
 * <br>
 * The operational model as well as the persistent domain model is influenced by the fact that
 * a JPA based application can benefit from  
 * <LI>Mostly Immutable Persistent Data Model
 * <LI>Optimistic Transaction Model
 * <br>for better scalability and throughput.
 * <br>  
 *  
 */
@SuppressWarnings("serial")
class OpenBookServiceImpl extends PersistenceService implements OpenBookService {
    
    public static final int   CUSTOMER_COUNT     = 10;
    public static final int   BOOK_COUNT         = 100;
    public static final int   AUTHOR_COUNT       = 40;
    public static final int   AUTHOR_PER_BOOK    = 3;
    
    /**
     * Range of number of queries executed for a {@linkplain #shop() shopping} trip.
     */
    public static final Range<Double> PRICE_RANGE  = new Range<Double>(4.99, 120.99);
    public static final Range<Integer> STOCK_RANGE = new Range<Integer>(5, 50);
    public static final int REORDER_LEVEL          = 10;
    
    OpenBookServiceImpl(String unit, EntityManagerFactory emf, boolean managed,
            PersistenceContextType scope) {
        super(unit, emf, managed, scope);
    }
    
    /**
     * Initialize service by populating inventory of Books and Customers.
     * If the inventory exists, then returns immediately without creating any new inventory.
     *
     * @return true if new inventory is created. false otherwise.
     */
    public boolean initialize(Map<String,Object> config) {
        if (isInitialized()) {
            return false;
        }
        EntityManager em = begin();
        if (config == null) {
            config = Collections.EMPTY_MAP;
        }
        int nCustomer  = PropertyHelper.getInteger(config, "openbook.Customer.Count",  CUSTOMER_COUNT);
        int nBook   = PropertyHelper.getInteger(config, "openbook.Book.Count",  BOOK_COUNT);
        int nAuthor = PropertyHelper.getInteger(config, "openbook.Author.Count",  AUTHOR_COUNT);
        int nAuthorPerBook = PropertyHelper.getInteger(config, "openbook.Book.Author.Count", AUTHOR_PER_BOOK);

Double priceMax = PropertyHelper.getDouble(config, "openbook.Book.Price.Max",  PRICE_RANGE.getMaximum());
        Double priceMin = PropertyHelper.getDouble(config, "openbook.Book.Price.Min",  PRICE_RANGE.getMinimum());

Integer stockMax = PropertyHelper.getInteger(config, "openbook.Inventory.Max", STOCK_RANGE.getMaximum());
        Integer stockMin = PropertyHelper.getInteger(config, "openbook.Inventory.Min", STOCK_RANGE.getMinimum());
        
        System.err.println("Creating " + nCustomer + " new Customer");
        for (int i = 1; i < nCustomer; i++) {
            Customer customer = new Customer();
            customer.setName("Customer-"+i);
            em.persist(customer);
        }

List<Author> allAuthors = new ArrayList<Author>();
        System.err.println("Creating " + nAuthor + " new Authors");
        for (int i = 1; i <= nAuthor; i++) {
            Author author = new Author();
            author.setName("Author-"+i);
            allAuthors.add(author);
            em.persist(author);
        }
        System.err.println("Creating " + nBook + " new Books");
        System.err.println("Linking at most " + nAuthorPerBook + " Authors per Book");
        for (int i = 1; i <= nBook; i++) {
            Book book = new Book(Randomizer.randomString(4,2),
                                 "Book-" + i,
                                 Randomizer.random(priceMin, priceMax),
                                 Randomizer.random(stockMin, stockMax));
            List<Author> authors = Randomizer.selectRandom(allAuthors,
                    Math.max(1, Randomizer.random(nAuthorPerBook)));
            for (Author author : authors) {
                author.addBook(book);
                book.addAuthor(author);
            }
            em.persist(book);
        }
        
        
        commit();
        return true;
    }
    
    /**
     * Affirms whether the database is loaded with some records.
     */
    public boolean isInitialized() {
        return count(Book.class) > 0;
    }
    
    /**
     * <A name="login">
     * Provide a name to login a Customer.
     * If such a customer exists, return it. Otherwise creates a new one.
     *
     * @param name name of an existing or a new Customer
     *
     * @return a Customer
     */
    public Customer login(String name) {
        EntityManager em = begin();
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Customer> q = cb.createQuery(Customer.class);
        Customer customer = null;
        Root<Customer> root = q.from(Customer.class);
        ParameterExpression<String> pName = cb.parameter(String.class);
        //TODO ��̬
        q.where(cb.equal(root.get("name"), pName));
        List<Customer> customers = em.createQuery(q).setParameter(pName, name).getResultList();
        if (customers.isEmpty()) {
            Customer newCustomer = new Customer();
            newCustomer.setName(name);
            em.persist(newCustomer);
            customer = newCustomer;
        } else {
            customer = customers.get(0);
        }
        commit();
        return customer;
    }
    
    /**
     * Find books that match title and price range.
     * @param title
     * @param minPrice
     * @param maxPrice
     * @param author
     * @return
     */
    
    public List<Book> select(String title, Double minPrice, Double maxPrice, String author,
            QueryDecorator...decorators) {
        CriteriaQuery<Book> q = buildQuery(title, minPrice, maxPrice, author);
        EntityManager em = begin();
        TypedQuery<Book> query =em.createQuery(q);
        List<Book> result=null;
        if(query!=null){
            result = query.getResultList();
        }
        commit();
        return result;
    }
    
    /**
     * <A name="getQuery">
     * Gets the string representation of a Criteria Query.
     * The string form of a Criteria Query is not specified in JPA specification.
     * But OpenJPA produces a readable form that is quite <em>similar</em> to
     * equivalent JPQL.
     */
    public String getQuery(String title, Double minPrice, Double maxPrice, String author) {
        CriteriaQuery<Book> q = buildQuery(title, minPrice, maxPrice, author);
        return q.toString();
    }
   
    /**
     * <A name="buildQuery">
     * Creates a Query based on the values of the user input form.
     * The user may or may not have filled a value for each form field
     * and accordingly the query will be different.<br>
     * This is typical of a form-based query. To account for all possible
     * combinations of field values to build a String-based JPQL can be
     * a daunting exercise. This method demonstrates how such dynamic,
     * conditional be alternatively developed using {@link CriteriaQuery}
     * introduced in JPA version 2.0.
     * <br>
     *
     * @return a typed query
     */

private CriteriaQuery<Book> buildQuery(String title, Double minPrice, Double maxPrice, String author) {
        // builder generates the Criteria Query as well as all the expressions
        CriteriaBuilder cb = getUnit().getCriteriaBuilder();
        // The query declares what type of result it will produce
        CriteriaQuery<Book> q = cb.createQuery(Book.class);
        // Which type will be searched
        Root<Book> book = q.from(Book.class);
        // of course, the projection term must match the result type declared earlier
        q.select(book);
        
        // Builds the predicates conditionally for the filled-in input fields
        List<Predicate> predicates = new ArrayList<Predicate>();
        if (!isEmpty(title)) {
            Expression<String> title_e=book.get("title");
            Predicate matchTitle =cb.like(title_e, title);
            predicates.add(matchTitle);
        }
        if (!isEmpty(author)) {
            Expression<String> authors_e=book.join("authors").get("name");
            Predicate matchAuthor =cb.like(authors_e, "%"+author+"%");
            predicates.add(matchAuthor);
        }
        // for price fields, also the comparison operation changes based on whether
        // minimum or maximum price or both have been filled.
        if (minPrice != null && maxPrice != null) {
            Expression<Double> price_e=book.get("price");
            Predicate matchPrice =cb.between(price_e, minPrice, maxPrice);
            predicates.add(matchPrice);
        } else if (minPrice != null && maxPrice == null) {
            Expression<Double> price_e=book.get("price");
            Predicate matchPrice =cb.ge(price_e, minPrice);
            predicates.add(matchPrice);
        } else if (minPrice == null && maxPrice != null) {
            Expression<Double> price_e=book.get("price");
            Predicate matchPrice = cb.le(price_e, maxPrice);
            predicates.add(matchPrice);
        }
        // Sets the evaluation criteria     
        if (!predicates.isEmpty())
            q.where(predicates.toArray(new Predicate[predicates.size()]));
        //SELECT b FROM Book b INNER JOIN b.authors ?  WHERE (b.title LIKE 'Book-63' AND b.price BETWEEN 0.0 AND 100.0)
        return q;
    }
    
    boolean isEmpty(String s) {
        return s == null || s.trim().isEmpty();
    }

/**
     * <A name="deliver"/>
     * Delivers the given order, if it is pending.
     * Delivery of an order amounts to decrementing inventory for each line item
     * and eventually nullify the line items to demonstrate orphan delete feature.
     * <br>
     * The transactions may fail because of either insufficient inventory or
     * concurrent modification of the same inventory by {@link #supply(Book, int) the supplier}.
     */
    public PurchaseOrder deliver(PurchaseOrder o) {
        if (o.isDelivered())
            return o;
        EntityManager em = begin();
        o = em.merge(o);
        for (LineItem item : o.getItems()) {
            item.getBook().getInventory().decrement(item.getQuantity());
        }
        o.setDelivered();
        commit();
        return o;
    }
    
    public List<PurchaseOrder> getOrders(PurchaseOrder.Status status, Customer customer) {
        EntityManager em = begin();
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<PurchaseOrder> q = cb.createQuery(PurchaseOrder.class);
        Root<PurchaseOrder> order = q.from(PurchaseOrder.class);
        q.select(order);
        List<Predicate> predicates = new ArrayList<Predicate>();
        if (status != null) {
            //TODO PurchaseOrder_.status
            predicates.add(cb.equal(order.get("status"), status));
        }
        if (customer != null) {
            //TODO  PurchaseOrder_.customer
            predicates.add(cb.equal(order.get("customer"), customer));
        }
        if (!predicates.isEmpty())
            q.where(predicates.toArray(new Predicate[predicates.size()]));
      //TODO PurchaseOrder_.placedOn
        q.orderBy(cb.desc(order.get("placedOn")));
        
        TypedQuery<PurchaseOrder> query = em.createQuery(q);
        List<PurchaseOrder> result = query.getResultList();
        commit();
        return result;
    }
    
    /**
     * <A name="placeOrder"/>
     * Creates a new {@linkplain PurchaseOrder} from the content of the given {@linkplain ShoppingCart}.
     * The content of the cart is cleared as a result.
     * <br>
     * The transaction is not expected to fail because the inventory is
     * not modified by placing an order.
     *
     * @param cart a non-null Shopping cart.
     */
    public PurchaseOrder placeOrder(ShoppingCart cart) {
        EntityManager em = begin();
        PurchaseOrder order = new PurchaseOrder(cart);
        em.persist(order);
        commit();
        cart.clear();
        return order;
    }
    
    /**
     * Supply books that have low inventory.
     * <br>
     * Queries for books with low inventory and supply each book in separate
     * transaction. Some of the transactions may fail due to concurrent modification on
     * the {@linkplain Inventory} by the {@linkplain #deliver() delivery} process.
     */
    public Book supply(Book b, int quantity) {
        EntityManager em = begin();
        b = em.merge(b);
        b.getInventory().increment(quantity);
        commit();
        return b;
    }
    
    public List<Inventory> getReorderableBooks(int limit) {
        EntityManager em = begin();
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Inventory> q = cb.createQuery(Inventory.class);
        Root<Inventory> inv = q.from(Inventory.class);
        q.select(inv);
        //TODO
        Expression<Integer> sup=inv.get("supplied");
        Expression<Integer> sold=inv.get("sold");
        Expression<Integer> inStock =cb.diff(sup,sold);
        q.orderBy(cb.asc(inStock));
        
        List<Inventory> result = em.createQuery(q)
                                   .setMaxResults(limit)
                                   .getResultList();
        commit();
        return result;
    }
    
    public long count(Class<?> cls) {
        EntityManager em = getEntityManager();
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Long> c = cb.createQuery(Long.class);
        Root<?> from = c.from(cls);
        c.select(cb.count(from));
        return em.createQuery(c).getSingleResult();
    }
    
    public List<Book> selectByExample(Book b, QueryDecorator...decorators) {
        return queryByTemplate(Book.class, b);
    }
    
    private <T> List<T> queryByTemplate(Class<T> type, T template) {
        EntityManager em = begin();
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<T> c = cb.createQuery(type);
        c.where(((OpenJPACriteriaBuilder)cb).qbe(c.from(type), template));
        List<T> result = em.createQuery(c).getResultList();
        commit();
        return result;
    }
    
    public <T> List<T> getExtent(Class<T> entityClass) {
        EntityManager em = begin();
        CriteriaQuery<T> c = em.getCriteriaBuilder().createQuery(entityClass);
        c.from(entityClass);
        List<T> result =  em.createQuery(c).getResultList();
        commit();
        return result;
    }
    
    public <T> List<T> query(String jpql, Class<T> resultClass, QueryDecorator... decorators) {
        EntityManager em = begin();
        TypedQuery<T> query = em.createQuery(jpql, resultClass);
        if (decorators != null) {
            for (QueryDecorator decorator : decorators) {
                decorator.decorate(query);
            }
        }
        List<T> result =   query.getResultList();
        commit();
        return result;
    }
    
    public void clean() {
        EntityManager em = begin();
        Set<EntityType<?>> entities = em.getMetamodel().getEntities();
        for (EntityType<?> type : entities) {
            System.err.println("Deleting all instances of " + type.getName());
            em.createQuery("delete from " + type.getName() + " p").executeUpdate();
        }
        commit();
    }

}

****************************************************************************************************************

更新project configuration

openjpa框架入门_项目框架搭建(二)

openjpa框架入门_项目框架搭建(二)

后续再次更新Database.