码迷,mamicode.com
首页 > 其他好文 > 详细

jpa实例

时间:2018-05-23 20:45:17      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:private   schema   value   inf   bsp   manage   ash   false   void   

ORM框架
新的JPA ORM规范:
1)JPA为POJO提供持久化标准规范。
2)JPA的使用:Hibernate与TopLink以及OpenJpa都提供了JPA的实现。
3)JPA主要技术:
  A.ORM映射元数据:JPA通过注解或XML描述映射关系,并将运行中的实体对象持久化到数据库中。
  B.JPA持久化API:使用面向对象的思想,操作实体对象,进行增删改查的操作。至于怎么操作,由框架思考这件事。
  C.查询语言:使用面向对象的思想避免了同程序的SQL语句产生交集。
LocalContainerEntityManagerFactoryBean 提供了对JPA EntityManagerFactory 的全面控制,
非常适合那种需要细粒度定制的环境。
LocalContainerEntityManagerFactoryBean将基于persistence.xml文件创建PersistenceUnitInfo类,
并提供dataSourceLookup策略和loadTimeWeaver。因此它可以在JNDI之外的用户定义的数据源之上工作,并控制织入流程。

public static void main(String[] args) throws Exception {    
        @SuppressWarnings("resource")
        ApplicationContext context = new ClassPathXmlApplicationContext("context.xml");
        Apply apply = (Apply) context.getBean("apply");
        System.out.println("---------------");
        List<String> list = apply.loadKeys();
}
package com.batman.hzdx.shard.model;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;

import com.batman.hzdx.def.DataTypeUtils;
import com.batman.hzdx.def.HasMapping;
import com.batman.hzdx.def.PrimaryKey;

@Entity(name="user")
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public class User implements HasMapping, PrimaryKey<String>, Serializable{
    private static final long serialVersionUID = 1L;
    
    @Id
    @Column(name="username", nullable=false, length=20)
    private String username;

    @Column(name="password", nullable=true, length=20)
    private String password;
    
    
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public static final String P_Username = "username";

    public static final String P_Password = "password";

    public String pk() {
        return username;
    }

    public Map<String, Serializable> convertToMap() {
        HashMap<String, Serializable> map = new HashMap<String, Serializable>();
        map.put("username", username);
        map.put("password", password);
        return map;
    }

    public void updateFromMap(Map<String, Serializable> map) {
        if (map.containsKey("username")) this.setUsername(DataTypeUtils.getStringValue(map.get("username")));
        if (map.containsKey("password")) this.setPassword(DataTypeUtils.getStringValue(map.get("password")));
        
    }
    
    public void fillDefaultValues() {
        if (username == null) username = "";
        if (password == null) password = "";
    }
}
package com.batman.hzdx.shard.model;

import static com.mysema.query.types.PathMetadataFactory.*;

import com.mysema.query.types.path.*;

import com.mysema.query.types.PathMetadata;
import javax.annotation.Generated;
import com.mysema.query.types.Path;


/**
 * QUser is a Querydsl query type for User
 */
@Generated("com.mysema.query.codegen.EntitySerializer")
public class QUser extends EntityPathBase<User> {

    private static final long serialVersionUID = -620768573;

    public static final QUser user = new QUser("user");

    public final StringPath password = createString("password");

    public final StringPath username = createString("username");

    public QUser(String variable) {
        super(User.class, forVariable(variable));
    }

    @SuppressWarnings("all")
    public QUser(Path<? extends User> path) {
        super((Class)path.getType(), path.getMetadata());
    }

    public QUser(PathMetadata<?> metadata) {
        super(User.class, metadata);
    }
}
package com.batman.hzdx.batch;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.batman.hzdx.shard.model.QPersion;
import com.batman.hzdx.shard.model.QTmAppMain;
import com.batman.hzdx.shard.model.QUser;
import com.mysema.query.Tuple;
import com.mysema.query.jpa.impl.JPAQuery;

public class Apply {
    @PersistenceContext
    private EntityManager em;
    
    public List loadKeys() {
        String name = "xiaosi";        
        Query qu2 = em.createNativeQuery("select password from user where username=‘111‘");
        List list3 = qu2.getResultList();
        System.out.println(list3.toString());
        
        
      /*  QUser qp = new QUser("user");
        JPAQuery query = new JPAQuery(em);
        List<String> list2 = query.from(qp).where(qp.username.eq(name)).list(qp.password);
        System.out.println(list2.toString());*/
        
        QPersion qp5 = new QPersion("persion");
        JPAQuery query = new JPAQuery(em);
        List<String> list5 = query.from(qp5).where(qp5.name.eq(name)).list(qp5.age);
        System.out.println(list5.toString());
        
        return list5;        
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xsi:schemaLocation="http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.1.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">

    <!-- 这里定义JPA相关配置。总体上来说,这里使用以Hibernate为Provider的JPA2.0方案,使用Spring来进行集成,不依赖于容器的JPA实现。 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="#{env[‘jdbcDriver‘]}" />
        <property name="url" value="#{env[‘jdbcUrl‘]}" />
        <property name="username" value="#{env[‘jdbcUsername‘]}" />
        <property name="password" value="#{env[‘jdbcPassword‘]}" />
        <!-- 最大活动连接:连接池在同一时间能够分配的最大活动连接的数量, 如果设置为非正数则表示不限制 -->
        <property name="maxActive" value="#{env[‘jdbcMaxActive‘] ?: 20}" />
        <!-- 最大空闲连接:连接池中容许保持空闲状态的最大连接数量,超过的空闲连接将被释放,如果设置为负数表示不限制 -->
        <property name="maxIdle" value="#{env[‘jdbcMaxIdle‘] ?: 10 }" />
        <!-- 最小空闲连接:连接池中容许保持空闲状态的最小连接数量,低于这个数量将创建新的连接,如果设置为0则不创建 -->
        <property name="minIdle" value="#{env[‘jdbcMinIdle‘] ?: 2 }" />
        <!-- 初始化连接:连接池启动时创建的初始化连接数量 -->
        <property name="initialSize" value="#{env[‘jdbcInitialSize‘] ?: 20}" />    
        <!-- 最大等待时间:当没有可用连接时,连接池等待连接被归还的最大时间(以毫秒计数),超过时间则抛出异常,如果设置为-1表示无限等待 -->    
        <property name="maxWait" value="#{env[‘jdbcMaxWait‘] ?: 10000 }" />
        <!-- 指明是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个 注意: 设置为true后如果要生效,validationQuery参数必须设置为非空字符串 -->
        <property name="testOnBorrow" value="#{env[‘jdbcTestOnBorrow‘]?: true}" />
        <!-- 进行returnObject对返回的connection进行validateObject校验 -->
        <property name="testOnReturn" value="#{env[‘jdbcTestOnReturn‘]?: false}" />
        <property name="validationQuery" value="#{env[‘jdbcTestSql‘]}" />
        <property name="validationQueryTimeout" value="#{env[‘jdbcValidationQueryTimeout‘] ?: 1}" />
        <!-- 空闲时是否进行验证,检查对象是否有效,默认为false -->
        <property name="testWhileIdle" value="#{env[‘jdbcTestWhileIdle‘]?: false}" />
        <!-- 在空闲连接回收器线程运行期间休眠的时间值,以毫秒为单位.如果设置为非正数,则不运行空闲连接回收器线程 -->
        <property name="timeBetweenEvictionRunsMillis" value="#{env[‘jdbcTimeBetweenEvictionRunsMillis‘]?: 600000}" />
        <!-- 连接在池中保持空闲而不被空闲连接回收器线程(如果有)回收的最小时间值,单位毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="#{env[‘jdbcMinEvictableIdleTimeMillis‘] ?: 1800000}" />
        <!-- 代表每次检查链接的数量,建议设置和maxActive一样大,这样每次可以有效检查所有的链接 -->
        <property name="numTestsPerEvictionRun" value="#{env[‘jdbcMaxActive‘] ?: 20}" />
        <property name="removeAbandoned" value="#{env[‘jdbcRemoveAbandoned‘]?: true}" />
        <property name="removeAbandonedTimeout" value="#{env[‘jdbcRemoveAbandonedTimeout‘]?: 300}" />
        <property name="logAbandoned" value="#{env[‘jbdcLogAbandoned‘]?: true}" />
    </bean>
    <!-- 实体管理类 -->
    <bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <description>
            定义EntityManagerFactory,用于Spring控制事务。
            具体的Hibernate配置在persistence.xml中控制,包括JPA Provider和Hibernate的各种参数(不含组件扫描)。
        </description>
        <property name="dataSource" ref="dataSource" />
         <property name="persistenceUnitName" value="default" />
        <property name="packagesToScan">
           <list>
              <value>com.batman.hzdx.shard.model</value>
           </list>
        </property>
        <property name="persistenceProviderClass" value="org.hibernate.ejb.HibernatePersistence"/>
        <property name="jpaDialect">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>
        </property>
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="database" value="#{env[‘jpaDatabaseType‘]?:‘DEFAULT‘}" />
                <property name="showSql" value="#{env[‘jpaShowSql‘]?:false}" />
            </bean>
        </property>
     <!--    <property name="jpaProperties">
          <props>
            <prop key="hibernate.jdbc.batch_size">1</prop>
          </props>
         </property>  -->
    </bean>    
    <!-- 事务设置 -->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="emf"/>
    </bean> 

    <!-- 事务使用AspectJ进行编译时Weave -->
      <tx:annotation-driven mode="aspectj"/>

    <!-- Spring Data -->
    <jpa:repositories base-package="com.batman.hzdx.shared.model"/>
</beans>

 

jpa实例

标签:private   schema   value   inf   bsp   manage   ash   false   void   

原文地址:https://www.cnblogs.com/mutong1228/p/9078771.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!