JPA学习笔记
JPA學(xué)習(xí)筆記
JPA是一種規(guī)范,而Hibernate,EclipseLink,OpenJPA都是它的一種實(shí)現(xiàn)。Spring Data JPA 是簡化JPA的寫法的實(shí)現(xiàn),封裝常用的寫法。
一、基本知識(shí)
1. JPA規(guī)范要求在類路徑的META-INF目錄下放置persistence.xml,文件的名稱是固定的
<!-- src/main/resources/META-INF/persistence.xml --><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_1_0.xsd" version="1.0"> <persistence-unit name="testdb" transaction-type="RESOURCE_LOCAL"> <provider>org.hibernate.ejb.HibernatePersistence</provider><class>com.domain.entity.User</class><class>com.domain.entity.Role</class><properties><!-- <property name="hibernate.connection.driver_class" value="org.gjt.mm.mysql.Driver" /> <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8" /> <property name="hibernate.connection.username" value="root" /> <property name="hibernate.connection.password" value="123456" /> --><property name="hibernate.cache.region.factory_class" value="net.sf.ehcache.hibernate.EhCacheRegionFactory" /><property name="net.sf.ehcache.configurationResourceName" value="/ehcache.xml" /><property name="hibernate.cache.use_second_level_cache" value="true" /><property name="hibernate.cache.use_structured_entries" value="true" /><property name="hibernate.cache.use_query_cache" value="true" /><property name="hibernate.hbm2ddl.auto" value="update" /><property name="hibernate.generate_statistics" value="false" /><property name="hibernate.jdbc.fetch_size" value="64" /><property name="hibernate.jdbc.batch_size" value="32" /><!--<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" /> --><property name="hibernate.dialect" value="org.hibernate.dialect.MySQLInnoDBDialect" /><property name="hibernate.format_sql" value="false" /><property name="hibernate.show_sql" value="true" /> <!-- <property name="hibernate.max_fetch_depth" value="1" /> --><property name="javax.persistence.validation.group.pre-persist" value="javax.validation.groups.Default" /><property name="javax.persistence.validation.group.pre-update" value="javax.validation.groups.Default" /> </properties> </persistence-unit> </persistence>2. JPA ORM映射元素?cái)?shù)據(jù)有XML和注解兩種方式
1)在實(shí)體bean中用注解@Entity來指定實(shí)體以讓jpa知道生成數(shù)據(jù)庫中的表 2)在實(shí)體bean中用注解@Column(length,nullable,name)指定數(shù)據(jù)庫中的表的字段的長度,是否為空即字段的名字 3)在實(shí)體類的前面用注解@Table(name="xx")指定生成表的名字 4)在實(shí)體類中用注解@Temporal(TemporalType.Date)指定生日的時(shí)間類型 5) @Enumerated(EmumType.STRING//保存到數(shù)據(jù)庫中是索引還是字符串)注解指定枚舉類型 6) @Lob聲明屬性對(duì)應(yīng)的數(shù)據(jù)庫字段為大文本類型,可以存放大的數(shù)據(jù)(文本和字節(jié)) 7) @Transient不成為持久化字段及不跟數(shù)據(jù)庫中的字段形成映射 8) @Basic(fetch=FetchType.LAZY)//是否把數(shù)據(jù)裝載到內(nèi)存中延遲初始化,第一次訪問的時(shí)候在加載數(shù)據(jù),一般用在大數(shù)據(jù)存放 9) @Embeddable指定聯(lián)合組鍵 一個(gè)實(shí)體類要在多個(gè)不同的實(shí)體類中進(jìn)行使用,而本身又不需要獨(dú)立生成一個(gè)數(shù)據(jù)庫表,就需要使用@Embedded、@Embeddable@MappedSuperclass public class IDEntity implements java.io.Serializable{@Id@GeneratedValueprivate Integer id;@Temporal(TemporalType.TIMESTAMP)@Column(name="create_date", updatable=false)public Date createDate; }@Entity @Table(name="city") public class City extends IDEntity{}@Entity @Table(name="brand",uniqueConstraints = { @UniqueConstraint(columnNames = {"mobile_brand", "mobile_model"})}) public class Brand extends IDEntity {@Column(name = "mobile_brand")public String brand;@Column(name = "mobile_model")public String model;@ManyToOne@NotFound(action=NotFoundAction.IGNORE)private City city;@Column(name="frequency",columnDefinition="INT(11) DEFAULT 0 NULL COMMENT '請(qǐng)求頻率'")private int frequency;@Transientprivate ChannelParameter channelParameter;@OneToOne(mappedBy = "channel",fetch = FetchType.LAZY)private ChannelParameter channelParameter;@Lob @Basic(fetch = FetchType.LAZY) @Column(columnDefinition = "TEXT",name = "content")private String content; }3. JPA的增刪改查:
1)讀取數(shù)據(jù)不要開啟事務(wù),只要有更改數(shù)據(jù)的動(dòng)作才需要開啟事務(wù) 2)增加數(shù)據(jù):em.persist(new Person("Jack"));//插入 3)刪除數(shù)據(jù):em.remove(person); //刪除(注意有外鍵約束時(shí),需要先解除外鍵約束才能刪除) 4)更新數(shù)據(jù):方法一: Person person = em.find(Person.class,1); person.setName("Jack");(1).跟事務(wù)關(guān)聯(lián)在一起了(2)對(duì)象處于托管狀態(tài) 方法二: Person person = em.find(Person.class,1); em.clear();//把實(shí)體管理器中的所有實(shí)體變成游離狀態(tài) person.setName("Jack");//現(xiàn)在還是不可以,實(shí)體還是處于游離狀態(tài) em.merge(person);//把游離狀態(tài)中的實(shí)體bean同步到數(shù)據(jù)庫5) 查看數(shù)據(jù):
方法一: Person person = em.find(Person.class,1);//查看數(shù)據(jù),1為對(duì)象在數(shù)據(jù)庫中的id值 方法二: Person person = em.getReference(Person.class,1);//沒有值不出現(xiàn)異常,只person.getName()的時(shí)候報(bào)異常 em.refresh(person);//進(jìn)行數(shù)據(jù)庫刷新,拿出最新的數(shù)據(jù) //加排它鎖 person = em.find(Person.class,person.getId(),LockModeType.PESSIMISTIC_WRITE);4.JPA中四種數(shù)據(jù)庫狀態(tài):
(1)新建:剛new出對(duì)象來的時(shí)候 (2)托管:從數(shù)據(jù)庫中查出來的時(shí)候 (3)游離(即脫管) (4)刪除5.JPA的查詢語句:
Query query = em.createQuery("select o from Person o");//必須有select o,id=等于后面不要直接寫值以免sql注入 (1)匿名查詢用:id (2)未參數(shù)查詢?1即:where o.id=?1//指明?的值從索引1開始 uery.getSingleResult5.1.Java簡單的示例代碼
EntityManagerFactory factory = Persistence.createEntityManagerFactory("testdb"); EntityManager em = factory.createEntityManager(); em.getTransaction().begin(); em.persist(new User("Jack")); em.getTransaction().commit(); em.close(); factory.close();5.2 JPA提供以下3種查詢結(jié)果解釋方法:
Transformers.ALIAS_TO_ENTITY_MAP //把輸出結(jié)果轉(zhuǎn)換成map Transformers.TO_LIST //把結(jié)果按順序排進(jìn)List Transformers.aliasToBean(target) //把結(jié)果通過setter方法注入到指定的對(duì)像屬性中 在JPA中Transformers的所有轉(zhuǎn)換都是需要實(shí)現(xiàn)ResultTransformer接口。① ALIAS_TO_ENTITY_MAP :太簡單了就是把key和value直接轉(zhuǎn)換到Map當(dāng)中 :
public Object transformTuple(Object[] tuple, String[] aliases) { Map result = new HashMap(tuple.length); for ( int i=0; i<tuple.length; i++ ) { String alias = aliases[i]; if ( alias!=null ) { result.put( alias, tuple[i] ); } } return result; }② TO_LIST:轉(zhuǎn)換過程很簡單,就是把value轉(zhuǎn)換成List對(duì)像:
public Object transformTuple(Object[] tuple, String[] aliases) { return Arrays.asList( tuple ); }③ aliasToBean:轉(zhuǎn)換過程就是通過讀取查詢后的字段,然后通過使用setter方法注入到目標(biāo)對(duì)像中 :
getSession().beginTransaction(); Query query = getSession().createSQLQuery("select * from user"); list =query.setResultTransformer(Transformers.aliasToBean(User.class)).list(); getSession().getTransaction().commit();參考資料
- JPA Reference (JavaDoc)
- Spring Data JPA - Reference Documentation
- JavaEE – JPA(4):EntityManager相關(guān)核心概念
- Spring data JPA
- JPA JPQL 查詢、排序
轉(zhuǎn)載于:https://www.cnblogs.com/huligong1234/p/7077552.html
總結(jié)
- 上一篇: 英语----名词性从句的混合练习(上)
- 下一篇: 转:WebApi(一)