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 {@PersistenceContextprivate 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.xsdhttp:
//www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp:
//www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.1.xsdhttp:
//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>
?
轉載于:https://www.cnblogs.com/mutong1228/p/9078771.html
與50位技術專家面對面20年技術見證,附贈技術全景圖
總結
以上是生活随笔為你收集整理的jpa实例的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。