Openjpa2.2+Mysql+Maven+Servlet+JSP

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

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

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

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

使用eclipse插件创建openbook web project.

1:create a maven project

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

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

.

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

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

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

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

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

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类 举例一个,下面类似(附完整的类)

/*
 *  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

后续再次更新Database.

openjpa框架入门_项目框架搭建(二)的更多相关文章

  1. openjpa框架入门_项目 database 启动project 初始化(三)

    mysql数据库安装好,这里不多说,现在来执行sql脚本 http://download.csdn.net/detail/shenhonglei1234/6019677 将下载好的脚本后缀名“open ...

  2. SpringMVC框架入门配置 IDEA下搭建Maven项目(zz)

    SpringMVC框架入门配置 IDEA下搭建Maven项目 这个不错哦 http://www.cnblogs.com/qixiaoyizhan/p/5819392.html

  3. 从壹开始前后端分离【 .NET Core2.0 +Vue2.0 】框架之七 || API项目整体搭建 6.2 轻量级ORM

    更新 1.在使用的时候,特别是更新数据的时候,如果不知道哪里有问题,可以查看数据库 和 实体类 的字段,是否大小写一致,比如 name 和 Name 2.在使用Sqlsugar 的 CodeFirst ...

  4. Z从壹开始前后端分离【 .NET Core2.2/3.0 +Vue2.0 】框架之七 || API项目整体搭建 6.2 轻量级ORM

    本文梯子 本文3.0版本文章 前言 零.今天完成的蓝色部分 0.创建实体模型与数据库 1.实体模型 2.创建数据库 一.在 IRepository 层设计接口 二.在 Repository 层实现相应 ...

  5. BBS项目分布搭建二(个人站点相关)

    BBS项目分布搭建二 1. 首页详情补充 # 在home.html文件中 body标签内补充: <div class="container-fluid"> <di ...

  6. SpringMVC框架入门配置 IDEA下搭建Maven项目

    初衷:本人初学SpringMVC的时候遇到各种稀奇古怪的问题,网上各种技术论坛上的帖子又参差不齐,难以一步到位达到配置好的效果,这里我将我配置的总结写到这里供大家初学SpringMVC的同僚们共同学习 ...

  7. [转]SpringMVC框架入门配置 IDEA下搭建Maven项目

    初衷:本人初学SpringMVC的时候遇到各种稀奇古怪的问题,网上各种技术论坛上的帖子又参差不齐,难以一步到位达到配置好的效果,这里我将我配置的总结写到这里供大家初学SpringMVC的同僚们共同学习 ...

  8. 从壹开始前后端分离【 .NET Core2.0 +Vue2.0 】框架之六 || API项目整体搭建 6.1 仓储模式

    前言 1.@LearningCoding 小伙伴关于用Sqlsugar在mysql数据库上的研究成果: sqlsugarcore支持mysql等数据库,在DbContext里面只需要设置dbtype为 ...

  9. Z从壹开始前后端分离【 .NET Core2.2/3.0 +Vue2.0 】框架之六 || API项目整体搭建 6.1 仓储+服务+抽象接口模式

    本文梯子 本文3.0版本文章 前言 零.完成图中的粉色部分 2019-08-30:关于仓储的相关话题 一.创建实体Model数据层 二.设计仓储接口与其实现类 三.设计服务接口与其实现类 四.创建 C ...

随机推荐

  1. XML的Schema约束

    XSD文档至少要包含:schema根元素和XML模式命名空间的定义.元素定义.需要注意的是XSD中必须定义一个且只能定义一个schema根元素,根元素中包括模式的约束,XML模式命名空间的定义,其他命 ...

  2. activity 的返回按钮

    http://www.2cto.com/kf/201210/160251.html 连续点击两次程序就退出程序,这是一个很有趣的程序功能,下来介绍一下我的实现方式(欢迎大家拍砖指点):   1.在Ac ...

  3. android的edittext输入长度

    http://blog.csdn.net/uyu2yiyi/article/details/6329738 http://flysnow.iteye.com/blog/828415/ http://s ...

  4. LogLog

    https://github.com/rsyslog https://github.com/beave/sagan http://www.securitywarriorconsulting.com/l ...

  5. QT:使用“状态模式”绘制界面

    QT与很多GUI库不同(如MFC),它不能随时随地地在界面上画图,只能在界面类的painterEvent中画图,如此一来,想在绘制QT界面时使用状态模式(GOF的23种设计模式之一)就有点困难了,作为 ...

  6. Table XXX is marked as crashed and should be repaired问题

    数据表出错了,查询数据获取不到了. 尝试一 重启mysql service mysqld restart 没用,重启并没有把表修复掉 尝试二 check table vicidial_list;rep ...

  7. Singleton 单例模式 泛型 窗体控制

    MDI子窗体 控制单例 /// <summary> /// 单例提供者 /// </summary> /// <typeparam name="T"& ...

  8. Yii2权威指南中文版及众包翻译平台

    Yii2在今年4月份公布了beta版本号,预计下半年会推出正式版本号(可用于生产环境). Yii2使用了新的PHP语法特性(PHP5.4+)并集成了大量新的编程最佳实践, 如命名空间.响应式界面组件库 ...

  9. C#—Dev XtraTabControl动态增加Tab和关闭选项卡方法

    C#—Dev XtraTabControl动态增加Tab和关闭选项卡方法,有需要的朋友可以参考下. 记录一下以免以后忘了 添加using DevExpress.XtraTab; 双击listview增 ...

  10. XML是什么,它能够做什么?——写给XML入门者

    XML就可以扩展标记语言(eXtensible Markup Language).标记是指计算机所能理解的信息符号,通过此种标记,计算机之间能够处理包括各种信息的文章等.怎样定义这些标记,既能够选择国 ...