2011年4月26日 星期二

[SQL] executeQuery

executeQuery

  • Executes the SQL query in this PreparedStatement object
  • and returns the ResultSet object generated by the query.



Returns:
a ResultSet object that contains the data produced by the query; never null


2011年4月24日 星期日

[JPA] ObjectDB Manual (02 - Entity Classes)

[JPA Persistable Types]
  • JPA persistable types:
    • User defined classes
    • Entity classes
    • Mapped superclasses
    • Embeddable classes.
      • Instances of an embeddable class can only be stored in the database as embedded objects, i.e. as part of a containing entity object.
      • Instances of embeddable classes are always embedded in other entity objects and do not require separate space allocation and separate store and retrieval operations. Therefore, using embeddable classes can save space in the database and improve efficiency.
  • Simple Java data types
    • Primitive types
    • Wrappers
    • String
    • Date and Math types.
      • java.sql.Date - represents date only (e.g. 2010-12-31).
      • java.sql.Time - represents time only (e.g. 23:59:59).
      • java.sql.Timestamp - represents date and time (e.g. 2010-12-31 23:59:59).
      • @Temporal(TemporalType.DATE)
  • Multi value types
    • Collections
    • Maps
    • Arrays.
  • Miscellaneous types
    • Enum types
    • Serializable types (user or system defined).
  • [Note] Only instances of entity classes can be stored in the database directly. Other persistable types can only be embedded in entity classes as fields.
  • A portable JPA entity class:
    • Should be a top-level class (i.e. not a nested / inner class).
    • Should have a public or protected no-arg constructor.
    • Cannot be final and cannot have final methods or final instance variables.
  • Mapped superclasses are really only useful in applications that use an ORM-based JPA provider (such as Hibernate, TopLink, EclipseLink, OpenJPA, JPOX, DataNucleus, etc.).

[JPA Entity Fields]

Fields of persistable user defined classes can be classified into the following five groups:
  • Transient fields
    • Do not participate in persistence and their values are never stored in the database
    • Static and final entity fields are always considered to be transient
  • Persistent fields
    • Every persistent field can be marked with one of the following annotations:
      • OneToOne, ManyToOne - for references of entity types.
      • OneToMany, ManyToMany - for collections and maps of entity types.
      • Basic - for any other persistable type.
    • Specifying optional=false causes an exception to be thrown on any attempt to store an entity with a null value in that field.
  • Inverse fields
    • Inverse (or mapped by) fields contain data that is not stored as part of the entity in the database, but is still available after retrieval by a special automatic query.
    • The mappedBy element specifies that the field is an inverse field rather than a persistent field. The content of the field is not stored as part of outer entity. Instead, the inverse field is automatically populated when the outer entity is retrieved from the database.
    • The mappedBy element defines a bidirectional relationship. In a bidirectional relationship, the side that stores the data is the owner. Only changes to the owner side affect the database, since the other side is not stored and calculated by a query.
    • Inverse fields may improve efficiency when managing very large collections that are changed often.
  • Primary key (ID) fields
  • Version field
    • Should be treated as read only by the application and no mutator methods should be written against them. Only one version field per entity class is allowed.
  • The first three groups (transient, persistent and inverse fields) can be used in both entity classes and embeddable classes.
  • The last two groups (primary key and version fields) can only be used in entity classes.


[JPA Primary Key]

* Entity Identification
  • Only entity objects have primary keys.

* Automatic Primary Key
  • By default the primary key is a sequential 64 bit number (long) that is set automatically by ObjectDB for every new entity object that is stored in the database.
  • The primary key of the first entity object in the database is 1.
  • Primary key values are not recycled when entity objects are deleted from the database.
  • The @GeneratedValue annotation specifies that the primary key is automatically allocated by ObjectDB.

* Application Set Primary Key
  • If an entity has a primary key field that is not marked with @GeneratedValue, automatic primary key value is not generated and the application is responsible to set a primary key by initializing the primary key field.

* Composite Primary Key
  • A composite primary key consist of multiple primary key fields.
  • When an entity has multiple primary key fields, JPA requires defining a special ID class that is attached to the entity class using the @IdClass annotation.

* Embedded Primary Key
  • An alternate way to represent a composite primary key is to use an embeddable class.
  • The entity contains a single primary key field that is annotated with @EmbeddedId and contains an instance of that embeddable class.

* Using Primary Keys for Object Clustering

  • it is useful to choose a primary key that helps clustering entity objects in the database in an efficient way. This is especially useful when using queries that return large result sets.



[Auto Generated Values]
  • Marking a field with the @GeneratedValue annotation specifies that a value will be automatically generated for that field.
  • This is primarily intended for primary key fields but ObjectDB also supports this annotation for non-key numeric persistent fields as well.

* The Auto Strategy
  • @GeneratedValue(strategy=GenerationType.AUTO)
  • But AUTO is the default strategy

* The Identity Strategy
  • The IDENTITY strategy also generates an automatic value during commit for every new entity object.
  • The difference is that a separate identity generator is managed per type hierarchy, so generated values are unique only per type hierarchy.

* The Sequence Strategy
  • Defining a named sequence
    • The @SequenceGenerator annotation is used to define a sequence and accepts a name, an initial value (the default is 1) and an allocation size (the default is 50).
  • The number of IDs in each allocation is specified by the allocationSize attribute.
  • Using the named sequence in one or more fields in one or more classes
  • Unlike AUTO and IDENTITY, the SEQUENCE strategy generates an automatic value as soon as a new entity object is persisted (i.e. before commit).
  • This may be useful when the primary key value is needed earlier.

* The Table Strategy
  • Is very similar to the SEQUENCE strategy
  • ORM-based JPA providers (such as Hibernate, TopLink, EclipseLink, OpenJPA, JPOX, etc.) simulate a sequence using a table to support this strategy.
  • Whereas the SEQUENCE strategy maintains the next sequence number to be used the TABLE strategy maintains the last value that was used.

[Index Definition]
  • Using proper indexes the iteration can be avoided and complex queries over millions of objects can be executed quickly.
  • Index management introduces overhead in terms of maintenance time and storage space.

* Single Field Index
  • @Unique represents a unique index that prevents duplicate values in the indexed field.
  • A PersistenceException is thrown on commit (or flush) if different entities have the same value in a unique field (similar to how primary keys behave).
  • @Index represents either an ordinary index with no unique constraint or a unique index if unique="true" is specified (the default is false).
  • Indexes can only be defined on ordinary persistent fields (not on primary key / version fields).

* Composite Index
  • A composite index is an index on more than one persistent field.
  • It is defined by specifying multiple fields in the members attribute of the the @Index or @Unique annotations.
  • Multiple @Index annotations can be wrapped with an @Indices annotation
  • the @Uniques annotation can wrap multiple @Unique annotations.

* Multi Part Path Index
  • Indexes must always refer to values that are stored as part of the entity.
  • Indexes on multi part paths are only allowed when using embeddable classes as fields of embedded object are stored as part of the containing entity.
  • Multi part paths in a composite index must have the same length.

* Indexes in Queries
  • A BTree is an ordered map data structure that ObjectDB maintains in the file system rather than in memory.
  • Indexes require maintenance time and consume storage space.
  • Indexes are especially efficient in lookup and range queries.
  • the order of the fields in the composite index definition is important, because it determines which field is used as the BTree's primary sort key and which field is used as a secondary sort key. If x is specified first, the BTree is ordered by x values, so a range scan on x values is supported.
  • Indexes on collections are useful in JOIN queries.


[Database Schema Evolution]
  • New entity objects have to be stored in the new class schema, and old entity objects, which were stored previously in the old class schema, have to be converted to the new schema.
  • [Note] In client-server mode the ObjectDB server must be restarted after a schema change.

* Automatic Schema Evolution
  • When an entity object of an old schema is loaded into memory it is automatically converted into an instance of the up to date entity class.
  • The database object is only updated to the new schema when that entity object is stored to the database again.
  • A matching field is a field with the same name and either the same type or a convertible type.
  • A matching field might also be located in a different place in the class hierarchy.


[JPA Persistence Unit]

  • A JPA Persistence Unit is a logical grouping of user defined persistable classes (entity classes, embeddable classes and mapped superclasses) with related settings.
  • Defining a persistence unit is optional when using ObjectDB, but required by JPA.


* persistence.xml

  • One persistence.xml file can include definitions for one or more persistence units.
  • The portable way to instantiate an EntityManagerFactory in JPA requires a persistence unit.
  • <provider>
    • Indicates which JPA implementation should be used. 
    • ObjectDB is represented by the com.objectdb.jpa.Provider string.
    • If not specified, the first JPA implementation that is found is used.
  • <mapping-file>
    • Specify XML mapping files that are added to the default META-INF/orm.xml mapping file.
    • Every annotation that is described in this manual can be replaced by equivalent XML in the mapping files (as explained below).
  • <jar-file>
    • Specify JAR files that should be searched for managed persistable classes.
  • <class>
    • Specify names of managed persistable classes .
  • <property>
    • Specify general properties. 
    • JPA 2 defines standard properties for specifying database url, username and password, as demonstrated above.


* Managed Persistable Classes

  • JPA requires registration of all the user defined persistable classes (entity classes, embeddable classes and mapped superclasses), which are referred to by JPA as managed classes, as part of a persistence unit definition.




* Reference
- ObjectDB 2.2 Developer's Guide

2011年4月23日 星期六

[JPA] ObjectDB Manual (01 - Quick Tour)

* Defining a JPA Entity Class
  • A JPA annotated entity class as have the ability to represent objects in the database and similar to serializable classes.
  • By default, any field that is not declared as static or transient is a persistent field.


* Obtaining a JPA Database Connection
  • In JPA a database connection is represented by the EntityManager interface.
  • Operations that modify database content also require an EntityTransaction instance.
  • To obtain an instance of EntityManagerFactory that represents the relevant database.
  • Can use that factory instance to get an EntityManager instance.
    • Define a standard persistence unit in an XML file
    • Can simply provide the file path of the ObjectDB database.
  • Closing an EntityManager does not close the database itself.
  • Once the EntityManager object is closed it cannot be reused. But, the owning EntityManagerFactory instance may preserve the EntityManager's resources


* CRUD Database Operations with JPA
  • Operations that modify the content of the database (such as storing new objects) require an active transaction.
  • The EntityManager object serves as the factory for Query instances.
  • The getSingleResult method executes the query and returns the result. It should only be used when exactly one result value is expected (a single Long object in the query above).
  • The TypedQuery interface is a type safe subinterface of Query and is usually the preferred way to work with queries.
  • The EntityManager that manages an entity is responsible for automatically detecting changes to the entity object and applying them to the database when the transaction is committed.



* Reference
- ObjectDB 2.2 Developer's Guide

2011年4月22日 星期五

[CSS] anchors

[Note] 如果為下段中的 anchor 指定了全域 CSS,這些樣式會覆蓋為 <h2> 指定的樣式。

Note CSS for h2


* id 像 name 屬性,可為頁面指定 anchor,但有些 browser 不支援。

* 不建議使用 name 屬性,所以可以考慮同時使用 id and name,但只有在相同標籤時才能這樣,也只有特定標籤允許這樣做:
ex: <a>, <applet>, <form>, <frame>, <iframe>, <img>, <map>。


* Order: LoVe/HAte
  • a:link
  • a:visited
  • a:hover
  • a:active


[Note] 冒號後不可空格!


2011年4月21日 星期四

[SQL] Join

join 總共分為六種:
  • Inner Join
  • Natural Join
  • Left Outer Join
  • Right Outer Join
  • Full Outer Join
  • Cross Join

Inner join:
  • 兩個資料表只顯示匹對的資料
  • 其實等同於多個Where條件式的連結

Outer join
  • 不管是否有匹對,都會將資料顯示出來,又分為 LEFT, RIGHT, FULL join。
  • 外部連接的語法是依資料庫的不同而有所不同的。
    • ex: 在 Oracle 上, 我們會在 WHERE 子句中要選出所有資料的那個表格之後加上一個 "(+)" 來代表說這個表格中的所有資料我們都要。
    • 當第二個表格沒有相對的資料時, SQL 會傳回 NULL 值。
    • ex: ...where A1.store_name = A2.store_name (+): 表示 A1 的資訊會全撈。

Update on 2013/01/07
  • join = inner join
  • left join = left outer join




* Reference
- [MySQL]left, right, inner, outer join 使用方法
- SQL 外部連接
- SQL Join語法筆記

[SQL] distinct

若接著 SELECT DISTINCT 後面有指定兩個以上的欄位

則要符合所有欄位值皆同樣重複的情況下該筆資料才會被捨棄。

(若只有其中一個欄位值相同但其它欄位值並不同,則仍會取出該筆資料。)


* Reference
- SELECT DISTINCT (SQL SELECT DISTINCT Statement)

[SQL] PK and FK

盡量使用 PK 當 FK

否則 join/物件連結 時會很慢

[JPA] Metamodel

有些屬性 JPA 不認得  而 metadata 就是讓 JPA 知道是和什麼屬性做比較

ex: date, object


2011年4月20日 星期三

CSS and HTML

  • <em> : 斜體並且強調
  • font-style: italic;
    • 僅表示斜體外觀。
  • <strong> : 粗體並且更強烈的強調
  • font-weight: bold;
    • 僅表示粗體外觀。

[JPA] Criteria Query

entityManager -> criteriaBuilder -> criteriaQuery -> root

2011年4月19日 星期二

[Annotation] JPA Annotation and JPQL API

Annotation Id
  • Specifies the primary key of an entity.
Annotation Column
  • Is used to specify the mapped column for a persistent property or field.
  • If no Column annotation is specified, the default values apply.
  • 如果名稱相同,則不需要使用此指定。

Annotation GeneratedValue
  • Provides for the specification of generation strategies for the values of primary keys.
    • String generator
      • (Optional) The name of the primary key generator to use as specified in the SequenceGenerator or TableGenerator annotation.
    • GenerationType strategy (Refer the next)
      • (Optional) The primary key generation strategy that the persistence provider must use to generate the annotated entity primary key.
      • Default value:
        • javax.persistence.GenerationType.AUTO

Enum GenerationType
  • GenerationType AUTO
    • Default for Annotation GeneratedValue
  • GenerationType IDENTITY
  • GenerationType SEQUENCE
    • Indicates that the persistence provider must assign primary keys for the entity using a database sequence.
  • GenerationType TABLE

Annotation ManyToOne
  • Defines a single-valued association to another entity class that has many-to-one multiplicity.
  • It is not normally necessary to specify the target entity explicitly since it can usually be inferred from the type of the object being referenced.
  • The ManyToOne annotation may be used within an embeddable class to specify a relationship from the embeddable class to an entity class.
    • CascadeType[] cascade
      • (Optional) The operations that must be cascaded to the target of the association.
      • By default no operations are cascaded.
    • FetchType fetch
    • (Optional) (refer the following items)
    • Default value:
  • javax.persistence.FetchType.EAGER

Enum CascadeType
  • Defines the set of cascadable operations that are propagated to the associated entity.
  • The value cascade=ALL is equivalent to cascade={PERSIST, MERGE, REMOVE, REFRESH, DETACH}.

Enum FetchType
  • Defines strategies for fetching data from the database.
  • The EAGER strategy
    • A requirement on the persistence provider runtime that data must be eagerly fetched. 
  • The LAZY strategy
    • A hint to the persistence provider runtime that data should be fetched lazily when it is first accessed.
  • The implementation is permitted to eagerly fetch data for which the LAZY strategy hint has been specified.

Annotation JoinColumn

Interface CriteriaBuilder
  • Used to construct criteria queries, compound selections, expressions, predicates, orderings.
  • Note that Predicate is used instead of Expression in this API in order to work around the fact that Java generics are not compatible with varags. (?)

Interface CriteriaQuery<T>
  • The CriteriaQuery interface defines functionality that is specific to top-level queries.

Interface Root<X>
  • A root type in the from clause. Query roots always reference entities.


* Reference
- JPA Reference (JavaDoc)

[JPQL][Annotation] Brief JPQL API

* @GeneratedValue(strategy = GenerationType.SEQUENCE, generator="teacherSEQ")
  • strategy = GenerationType.SEQUENCE: 主键策略
  • generator = "teacherSEQ": 寻找数据库中sequence的名字的中间量.
  • 若使用 @GeneratedValue(strategy = GenerationType.SEQUENCE)
    • 则 hibernate 在 oracle 中自动生成一个sequence, 这个 sequence 可能是与其他表共用的, 但是这不影响主键的唯一性.

* 查询表达式被赋予泛型。一些典型的表达式是:

  • Root: 相当于一个 FROM子句。
  • Predicate: 其计算为布尔值 true 或 false(事实上,它被声明为 interface Predicate extends Expression)。
  • Path: 表示从 Root表达式导航到的持久化属性。Root是一个没有父类的特殊 Path
  • QueryBuilder: 是 CriteriaQuery和各种查询表达式的工厂。
  • CriteriaQuery: 被传递给一个可执行查询并保留类型信息,这样可以直接访问选择列表的元素,而不需要任何运行时强制类型转换。

* Reference
- Hibernate中连接Oracle10g(使用annotation标识数据库中的sequence)
- JPA2.0的学习一 **
- JPA 2.0 中的动态类型安全查询 **

JPA annotation

The JPA annotation cannot be inherited and override

2011年4月18日 星期一

Metamodel and JPQL (dynamic query)

[Metamodel API]

* 將 metamodel class 定義為 持久化實體類的描述。
就像 Reflection API 需要其他接口(比如 java.lang.reflect.Field 或 java.lang.reflect.Method)來描述 java.lang.Class 的组成一樣,JPA Metamodel API 也需要其他接口(比如 SingularAttribute 和 PluralAttribute)來描述元模型类的类型及其属性。

* 持久化实体在语义上区分为 MappedSuperClass、Entity 和 Embeddable
在 JPA 2.0 之前,这种语义区分是通过持久化类定义中的对应类级别注释来表示的


* JPA Metamodel 在 javax.persistence.metamodel 包中描述了 3 个独立的接口:
  • MappedSuperclassType
  • EntityType
  • EmbeddableType
类似地,可以通过接口(比如 SingularAttribute、CollectionAttribute 和 MapAttribute)在类型定义级别上区分持久化属性。

* 持久化单元作用域的持久化实体在 META-INF/persistence.xml 文件的 <class> 子句中枚举。
通过 javax.persistence.metamodel.Metamodel 接口让开发人员可以在运行时使用作用域。Metamodel 接口是特定持久化单元知道的所有持久化实体的容器。

* 元模型接口是持久化单元中的类型的容器。

* 这个接口允许通过元模型元素的对应持久化实体类访问元模型元素。

* 可以在运行时浏览 EntityType<person> 获得在 Person 实体中声明的持久化属性

* 如果应用程序在 pClass(比如 pClass.getSingularAttribute("age", Integer.class))上调用一个方法,它将返回一个 SingularAttribute<person, integer=""> 实例,该实例与实例化规范元模型类的静态 Person_.age 成员相同

* 最重要的是,对于应用程序可以通过 Metamodel API 在运行时引用的属性,是通过实例化静态规范元模型 Person_ 类向 Java 编译器提供的。

* 除了将持久化实体分解为对应的元模型元素之外,Metamodel API 还允许访问所有已知的元模型类 (Metamodel.getManagedTypes()),或者通过类的持久化信息访问元模型类,例如 embeddable(Address.class),它将返回一个 EmbeddableType<address> 实例(ManagedType<> 的子接口)。

* 持久化元信息分为两大类:
  • 持久化, ex: @Entity
    • 元模型仅为持久化注释(不是映射注释)捕捉元数据。因此,使用当前版本的 Metamodel API 可以知道哪些字段是持久化的,但不能找到它们映射到的数据库列。
  • 映射, ex: @Table
* Person_.age
  • 表示 Person 的持久化属性 age。
  • 是 Person_ 类中的公共静态字段,Person_ 是静态、已实例化的规范元模型类,对应于原来的 Person 实体类。
* 元模型类描述持久化类的元数据。如果一个类安装 JPA 2.0 规范精确地描述持久化实体的元数据,那么该元模型类就是规范的。
  • 规范的元模型类是静态的,因此它的所有成员变量都被声明为静态的(也是 public 的)。
  • Person_.age 是静态成员变量之一。您可以在开发时在源代码中生成一个具体的 Person_.java 来实例化 一个规范类。
  • 实例化之后,它就可以在编译期间以强类型的方式引用 Person 的持久化属性。

* JPA 2.0 提供的解决办法通过静态地公开相同的持久化属性实例化名为 Person_ 的元模型类(对应于 Person)。
  • 元模型类将原来的 domain.Person 实体的每个持久化属性声明为类型为 SingularAttribute< Person,?> 的静态公共字段。
  • 通过利用这个 Person_ 元模型类,可以在编译期间引用 domain.Person 的持久化属性 age — 不是通过 Reflection API,而是直接引用静态的 Person_.age 字段
  • 编译器可以根据 age 属性声明的类型实施类型检查。
  • ex:QueryBuilder.gt(p.get(Person_.age), "xyz") 将导致编译器错误,因为编译器通过 QueryBuilder.gt(..) 的签名和 Person_.age 的类型可以确定 Person 的 age 属性是一个数字字段,不能与 String 进行比较。

* 元模型类被注释为 @StaticMetamodel(domain.Person.class) 以将其标记为一个与原来的持久化 domain.Person 实体对应的元模型类。



[Criteria API]

* This dynamic query definition capability, referred as Criteria API, is based on the:
  • abstract persistent schema of the entities.
  • their embedded objects.
  • their relationships.

* The first step in constructing a query definition is specification of query roots.
  • Query roots
    • Specify the domain objects on which the query is evaluated. 
    • Is an instance of the Root interface. 
    • A query root is added to a CriteriaQuery by addRoot(Class c) method.

* A query domain can be further refined by joining to other domain objects.

* An attribute of a domain object can also be specified by navigating via get(String attr). The attribute should refer to a valid persistent property of the receiving domain object, however no such validation is enforced during the construction of the query definition.

CriteriaBuilder interface
  • The factory for CriteriaQuery. 
  • Is obtained from either an EntityManagerFactory or an EntityManager.

* queryBuilder
  • 是 CriteriaQuery 的工厂,同时也是查询表达式的工厂。
  • 包含构造传统 JPQL 语法支持的所有查询表达式的 API 方法,并且还包含额外的方法。

* CriteriaQuery
  • 一个查询表达式节点树。
  • 在传统的基于字符串的查询语言中,这些表达式节点用于指定查询子句,比如 FROM、WHERE 和 ORDER BY。


* Reference
- JPA 2.0 中的动态类型安全查询(3)
- JPA 2.0 中的动态类型安全查询(4)
- 详解JPA 2.0动态查询机制:Criteria API(1)
- 详解JPA 2.0动态查询机制:Criteria API(2)
- Part 2. Java Persistence API

[ibatis] Attributes

<ispropertyavailable> 属性是存在

<isnotpropertyavailable> 属性不存在

<isnull> 属性值是null

<isempty> 判断 Collection.size < 1 或 String.length() < 1

<isequal> 等於

<isnotequal> 不等於

<isgreaterthan> 大於

<isgreaterequal> 大於等於

<islessthan> 小於

<islessequal> 小於等於



* Reference
- 如何进行ibatis动态多条件组合查询以及模糊查询(oracle,mysql)

[Configuration] persistence.xml and applicationContext.xml

* How does the server know which database it is supposed to save / update / query the entity objects? How do we configure the underlying object-relational-mapping engine and cache for better performance and trouble shooting? The persistence.xml file gives you complete flexibility to configure the EntityManager.

* persistence.xml file
  • Is a standard configuration file in JPA.
  • Has to be included in the META-INF directory inside the JAR file that contains the entity beans.
  • The <provider> specifies the underlying implementation of the JPA EntityManager.
  • The <jta-data-source> points to the JNDI name of the database this persistence unit maps to.

* Since you might have multiple instances of persistence-unit defined in the same application, you typically need to explicitly tell the @PersistenceContext annotation which unit you want to inject. For instance, @PersistenceContext(name="myapp") injects the EntityManager from the persistence-unit named "myapp".

* JTA:
  • One of the Java Enterprise Edition (Java EE) APIs allowing distributed transactions to be done across multiple XA resources in a Java environment.
  • Provides for:
    • demarcation of transaction boundaries
    • X/Open XA API allowing resources to participate in transactions.

* <tx:annotation-driven>
  • Enabled spring to interpret @Transactional annotation.
  • Creates a BeanPostProcessor to be included in the BeanPostProcessor step in the initialization phase.
    • When that BeanPostProcessor sees @Transactional in your Spring bean code, then it create a DynamicProxy to proxy that bean so that it will run transactionally.

* 一個 LocalContainerEntityManagerFactoryBean 只能管理一個持久化單元, 僅管其内部創建的DefaultPersistenceUnitManager 類可以得取多個持久化單元信息(PersistenceUnitInfo), 但最终只能有一個被返回给 LocalContainerEntityManagerFactoryBean 用於創建 JPA 實現提供者的 EntityManagerFactory

* Entity Manager 藉由 Persistence Context 來控制被管理的 Entity Instances,而每個 Persistence Context 必定由一個 Persistence Unit 來限制該 Context 可以管理的 Entity Classes 種類。

* Entity Manager 可以分為兩類
  • Container-Managed Entity Manager
    • 是由 JEE Container 所管理的 Entity Manager
    • 主要是以 @PersistenceContext 標識在你的程式中,Container 會在執行期間自動注入對應的 instance。
    • 可以再區分兩類:
      • PersistenceContextType.TRANSACTION (Default):
        • 主要是配合 Stateless Session Bean 與 JTA Transaction,在每次 method 被呼叫時都去檢查 JTA transaction 中是不是有 Persistence Context,如果有就續用否則就建一個新的。
        • 當 JTA Transaction commit 時,在 persistence context 中的 entity instances 就會自動 persist 至 DB。
      • PersistenceContextType.EXTENDED:
        • 主要是配合 Stateful Session Bean,只有當執行到有 @Remove 標識的 method 時才會 persist 在 persistence context 中的 entity instances。
  • Application-Managed Entity Manager
    • Application 自行管理,藉由呼叫 EntityManagerFactory.createEntityManager() 來取得,因此,一般的 J2SE程式也可以使用,當然在 JEE Container 也可以使用,特別是在某些特別情況或有特殊考慮時多一種方式可以應用。
    • 如果要在 JEE Container 中使用的話,與 Container-Managed Entity Manager 不同之處是以 @PersistenceUnit 來標識要被注入的 EntityManagerFactory,而且也必需呼叫 EntityManager.close() 來指出要 persist 的時機。
    • 產生 persistence context 的時機也有所不同,當呼叫 EntityManagerFactory.createEntityManager() 就會產生一個 persistence context。

* JPA allows us to work with entity classes, which are denoted as such using
  • The annotation @Entity.
  • configured in an XML file (we'll call this persistence meta information).
When we acquire the Entity Manager Factory using the Persistence class, the Entity Manager Factory finds and processes the persistence meta information.


* To work with a database using JPA, we need an Entity Manager. Before we can do that, we need to create an Entity Manager Factory.
=> Entity Manager Factory -> Entity Manager -> using JPA...

* To acquire an Entity Manager Factory, we use the class javax.persistence.Persistence.
  • It reads a file called persistence.xml in the META-INF directory.
  • Then creates the named Entity Manager Factory, which processes persistence meta information stored in XML files or annotations (we only use annotations).

* Once we have an Entity Manager, we can ask it to perform several operations such as persisting or removing an entity from the database or creating a query.



* Reference
- 1.2.1. The persistence.xml file
- Java Transaction API
- Understanding working
- 非J2EE 容器环境下Spring +JPA 多持久化单元/多个JAR归档注解实体 的实体扫描问题及解决办法
- JPA2--Transaction Management
- Comments/Suggestions, please email: schuchert -at- yahoo -dot- com

XML schema

* XML Schema 提供了兩個在實例文檔中使用的特殊屬性,用於指出模式文檔的位置。
  • xsi:schemaLocation:
    • 聲明目標名稱空間的模式文檔,可以針對在 XML 執行個體文件中定義的命名空間,提供尋找 XML 結構描述定義的方法。
    • 此屬性值是以空格分隔的統一資源識別元 (URI) 組清單,其中每一組都是由命名空間加上該命名空間 XML 結構描述定義 (通常是 .xsd 檔) 的位置所組成。
    • 第一個 URI 是名稱空間的名字,第二個 URI 给出模式文檔的位置,模式處理器將從這個位置讀取模式文檔,該模式文檔的目標名稱空間必须與第一个 URI 相匹配。
  • xsi:noNamespaceSchemaLocation: 
    • 用於没有目標名稱空間的模式文檔,它们通常在實例文檔中使用。

* XSD (XML Schema Definition)
  • A Recommendation of the W3C, specifies how to formally describe the elements in an XML document.
  • This description can be used to verify that each item of content in a document adheres to the description of the element in which the content is to be placed.
  • In general, a schema is an abstract representation of an object's characteristics and relationship.
  • An XML schema represents the interrelationship between the attributes and elements of an XML object (for example, a document or a portion of a document). To create a schema for a document, you analyze its structure, defining each structural element as you encounter it.


* Reference
- Xsi:schemaLocation 屬性繫結支援
- xsi:schemaLocation属性
- XSD (XML Schema Definition)

2011年4月17日 星期日

[API] JPA

* PersistenceUnitManager
  • Interface that defines an abstraction for finding and managing JPA PersistenceUnitInfos.
  • Used by LocalContainerEntityManagerFactoryBean in order to obtain a PersistenceUnitInfo for building a concrete EntityManagerFactory.

* DefaultPersistenceUnitManager
  • Used as internal default by LocalContainerEntityManagerFactoryBean.
  • Supports standard JPA scanning for persistence.xml files, with configurable file locations, JDBC DataSource lookup and load-time weaving.
  • The default XML file location is classpath*:META-INF/persistence.xml, scanning for all matching files in the class path (as defined in the JPA specification).
  • DataSource names are by default interpreted as JNDI names, and no load time weaving is available (which requires weaving to be turned off in the persistence provider).

* ResourceBundleMessageSource
  • MessageSource implementation that accesses resource bundles using specified basenames.
  • This class relies on the underlying JDK's ResourceBundle implementation, in combination with the JDK's standard message parsing provided by MessageFormat.

* OpenEntityManagerInViewFilter
  • Servlet 2.3 Filter that binds a JPA EntityManager to the thread for the entire processing of the request. Intended for the "Open EntityManager in View" pattern, i.e. to allow for lazy loading in web views despite the original transactions already being completed.
  • This filter makes JPA EntityManagers available via the current thread, which will be autodetected by transaction managers.
  • It is suitable for service layer transactions via JpaTransactionManager or JtaTransactionManager as well as for non-transactional read-only execution.

* JpaTransactionManager
  • Is appropriate for applications that use a single JPA EntityManagerFactory for transactional data access.
  • JTA (usually through JtaTransactionManager) is necessary for accessing multiple transactional resources within the same transaction. 
  • Note that you need to configure your JPA provider accordingly in order to make it participate in JTA transactions.
  • Supports direct DataSource access within a transaction (i.e. plain JDBC code working with the same DataSource). This allows for mixing services which access JPA and services which use plain JDBC (without being aware of JPA)!
  • Application code needs to stick to the same simple Connection lookup pattern as with DataSourceTransactionManager (i.e. DataSourceUtils.getConnection(javax.sql.DataSource) or going through a TransactionAwareDataSourceProxy). Note that this requires a vendor-specific JpaDialect to be configured.
  • Will autodetect the DataSource used as known connection factory of the EntityManagerFactory, so you usually don't need to explicitly specify the "dataSource" property.

* transaction-type
  • Is defined in persistence unit (persistence.xml file)
  • Default to JTA in a Java EE environment
  • Default to RESOURCE_LOCAL in a Java SE environment
  • Two different transaction types:
    • JTA:
      • most important
      • Multiple participating resources
      • Distributed XA transactions
      • 透過設置容器端管理的Data Source之JNDI名稱,這必須在容器端先定好,JDBC資源與Connection Pool等。
      • For distributed transactions
    • Resource-local



* Reference
- EJB3 Gossip: 第一個 JPA(容器管理)
- Java Persistence API (JPA): Transaction Transaction
- transaction-type="JTA" / "RESOURCE_LOCAL"

[Introduction] SpringMVC

* Spring MVC
  • Is essentially a request dispatcher framework, with a Servlet API variant and Portlet API variant.
  • As providing foundational facilities and conveniences on top of the Servlet/Portlet container, ex:
    • Flexible request mappings: separation between controller processing and view rendering phase
    • Data binding: basic JSP tag libraries that complement the JSTL, etc.
    • The building blocks of sophisticated HTTP request processing.

* The class is annotated with the @Controller stereotype. This indicates that its methods should be scanned for request mappings.

* @RequestMapping
  • The actual request mappings are expressed through this at the method level.
  • Each of those mappings binds to a specific HTTP path within the containing DispatcherServlet.
  • Allows for specifying HTTP request methods (e.g. method = RequestMapping.GET) or specific request parameters (e.g. params = "action=save"), all narrowing the type-level mapping for specific methods. Alternatively,

* Reference
- Chapter 13. Web MVC framework
- Annotated Web MVC Controllers in Spring 2.5

[Configuration] classpath with Spring

* J2EE default classpath:
- /WEB-INF/classes

* Spring 默认会使用当前线程的 ClassLoader 的 getResource 方法获取资源的 URL,如果无法获得当前线程的ClassLoader,Spring 将使用加载类 org.springframework.util.ClassUtils 的 ClassLoader。

* "classpath*:"
  • 是為了從多個 jar 文件中加載相同的文件。
  • 使用 classpath* 前缀可以获取所有与给定路径匹配的 classpath 资源,从而避免出现两个不同位置有相同名字的文件,Spring 只加载其中一个的情况。
  • You know you could actually have these context files loaded by different class loaders but in same application. 
    • Ex: EAR loading contexts in war and META-INF jars in separate class loaders. As Long as these are in the same VM, You can do a multi classloader resource.
  • ex: "classpath*:META-INF/*-beans.xml": a ClassLoader.getResources() call is used on the last non-wildcard path segment to get all the matching resources in the class loader hierarchy, and then off each resource the same PathMatcher resoltion strategy described above is used for the wildcard subpath.

* "classpath:"
- 只能加載找到的第一個文件。


* Reference
- Spring加载resource时classpath*:与classpath:的区别
- Chapter 4. Resources
- classpath*: making your Modular Spring Resources
- Spring中使用classpath加载配置文件浅析 **
- Spring中使用classpath加载配置文件浅析(续

2011年4月10日 星期日

[Shortcut] 執行

* services.msc: 開啟 "服務"

* msconfig: 開啟 "系統設定"

[Configuration] log4j.xml

* 有 property and xml 兩種設定方式

* Log level
FATAL      0  
  ERROR      3  
  WARN       4  
  INFO       6  
  DEBUG      7 

* Appender: log 輸出位置
org.apache.log4j.ConsoleAppender: 控制台

org.apache.log4j.FileAppender: 文件
 - . Threshold: log 最低 levle
. ImmediateFlush: default is true, 所有 log 都會馬上被 output
. Target: default is System.out, output on console,
   to choose which console stream to print messages to, System.out or System.err.

org.apache.log4j.DailyRollingFileAppender: 每天產生一個 log file
- . Append: default is true, 將 log 增加到指定 file, false is 覆蓋 log
. File: 指定文件
......

org.apache.log4j.RollingFileAppender: 文件大小到達指定大小的时候產生一個新的文件

org.apache.log4j.WriterAppender: 將 log 信息以串流格式發送到任意指定的地方

* Layout: log 輸出格式
org.apache.log4j.HTMLLayout: 以HTML表格形式布局

org.apache.log4j.PatternLayout: 可任意自定格式

org.apache.log4j.SimpleLayout: 包含 log 信息的级别和信息字符串

org.apache.log4j.TTCCLayout: 包含產生 log 的時間、thread、class 等等信息

* 列印參數的格式類似於 C
%m   程式中的 message

  %p   log level

  %r   啟動應用到輸出 log 所花費的毫秒數

  %c   class name

  %t   產生該 log 的 thread

  %n   換行

  %d   日期或時間,ex: %d{yyy MMM dd HH:mm:ss , SSS}

  %l   log 的發生位置,包括 class name, thread, line number,ex: Testlog4.main(TestLog4.java: 10 )。

* Logger: 對應 package 和 appender
additivity: 是否往上查找未設定的屬性
appender-ref: appender reference,可以有多個
level: log level priority,default is "debug"
  //  若沒有設定則是繼承 root logger 的設定
  // everything of spring log level is default "info"

* root: root Logger
以 root 的 LEVEL 為主,ex: 假設 root level 為 INFO,那麼即使設為 DEBUG 也只會輸出到 INFO level。

* API
  • PatternLayout
    • The goal of this class is to format a LoggingEvent and return the results as a String. The results depend on the conversion pattern.
    • The left justification flag which is just the minus (-) character comes the optional minimum field width modifier. This is a decimal constant that represents the minimum number of characters to output.
    • The padding character is space. If the data item is larger than the minimum field width, the field is expanded to accommodate the data. The value is never truncated.
    • This behavior can be changed using the maximum field width modifier which is designated by a period followed by a decimal constant. If the data item is longer than the maximum field, then the extra characters are removed from the beginning of the data item and not from the end.
  • ConsoleAppender
    • Appends log events to System.out or System.err using a layout specified by the user. The default target is System.out.
  • LevelRangeFilter
    • A very simple filter based on level matching, which can be used to reject messages with priorities outside a certain range.
    • The filter admits three options LevelMin, LevelMax and AcceptOnMatch.
    • If LevelMinw/LevelMax is not defined, then there is no minimum/maximum acceptable level (ie a level is never rejected for being too "low"/unimportant// "high"/important).
  • DailyRollingFileAppender
    • The rolling schedule is specified by the DatePattern option. This pattern should follow the SimpleDateFormat conventions. In particular, you must escape literal text within a pair of single quotes. A formatted version of the date pattern is used as the suffix for the rolled file name.
  • Logger
  • Level
    • Defines the minimum set of levels recognized by the system, that is OFFFATALERRORWARNINFODEBUG and ALL.
    • TRACE: The TRACE Level designates finer-grained informational events than the DEBUG

* Reference
- log4j 基本配置
- Apache Log4j 1.2.16 API
- log4j使用指南 ***
- Apache Log4j 学习笔记 **
- org.apache.log4j.Logger 详解 **
- wiki

2011年4月7日 星期四

[J2EE] WEB-INF

外界無法經由網址直接存取 WEB-INF 下的檔案

故若是在 WEB-INF 下的檔案必得經由 controller 存取

[Configuration] pom.xml

* Project Object Model (POM)
  • The fundamental unit of work in Maven.
  • An XML file that contains information about the project and configuration details used by Maven to build the project.
  • Contains default values for most projects, ex: the build directory, which is target; the source directory, which is src/main/java; the test source directory, which is src/main/test; and so on.

* 在 Maven 中,有三個內建的建構生命週期:
  • Default: 處理專案部署。
  • Clean: 處理專案資源清除。
  • Site: 處理專案文件。

* 使用 mvn 指令呼叫執行某個階段,都是呼叫某個 plugin 來執行,像是編譯時會使用 mvn compile,這會呼叫 Maven 的 maven-compiler-plugin,這個 plugin 在 Super POM 中會有預設值。

* plugin
  • maven-resources-plugin: 處理專案資源的複製。
  • maven-compiler-plugin: 負責專案的編譯。
  • maven-surefire-plugin: 負責專案的單元測試。
  • maven-jar-plugin: 負責專案的包裝。
  • maven-clean-plugin
    • Will delete the target directory by default. You may configure it to delete additional directories and files.
    • The directory in the fileset is a relative path inside a project,


* 可有以下關係
  • 繼承
  •   
          
           目前使用的 POM 版本
           組織或項目的唯一標誌,會成為預設的套件名稱  
           項目的通用名稱,這將成為你存放製品的資料夾名稱,通常就是專案名稱  
           產品版本  
           打包出來的檔案類別, ex: war, jar...  
      
    
  • 依賴
  •   
          
          組織或項目的唯一標誌  
          項目的通用名稱  
          版本  
          檔案類型 (war, jar...)  
          用於限制相應的依賴範圍,ex: compile, runtime...  
          用於連續依賴時  
          
        ...  
        
    
  • 合成

* Build
  
   
      打包後的檔案名稱
        
      打包檔案目錄  
        
        
            
        
      

        
            
              資源所在位置  
            
          
    


* Reference
- Introduction to the POM
- 我的Maven2之旅:五.pom.xml基本元素介绍
- maven 配置篇 之pom.xml(一) **
- JUnit Gossip: 使用 Maven
- JUnit Gossip: POM 設定檔
- JUnit Gossip: 建構生命週期
- Maven Clean plugin - Delete Additional Files Not Exposed to Maven

Bind Sevice

* 若有相同的 service 時, 則只能 bind 到第一個安裝的 service。

2011年4月6日 星期三

[Configuration] web.xml

* 以下會影響正確性
  • 大小寫
  • 元素順序,ex: servlet元素必須出現在所有servlet-mapping元素之前。

* 元素配置


    
    










    



    
    
    
        




    
    




    
























* Reference
- Tomcat中用web.xml控制Web应用详解(1)
- web.xml元素:常见设定值一览 **

Spring and Struts2

Spring 像是 framework 的工具


Struts2則是實現 mvc framework

2011年4月5日 星期二

Code Style

@(#) STATIC ATTRIBUTES

@(#) ATTRIBUTES

@(#) INNER CLASSES

@(#) CONSTRUCTORS

@(#) PUBLIC METHODS

@(#) PROTECTED METHODS

@(#) PRIVATE METHODS

2011年4月4日 星期一

[DevGuide] Designing for Responsiveness

* Application Not Responding (ANR)
The system displays an ANR if an application cannot respond to user input.

* What Triggers ANR?
Application responsiveness is monitored by the Activity Manager and Window Manager system services.
  • No response to an input event (e.g. key press, screen touch) within 5 seconds
  • A BroadcastReceiver hasn't finished executing within 10 seconds

* Android applications normally run entirely on a single (i.e. main) thread.
This means that anything your application is doing in the main thread that takes a long time to complete can trigger the ANR dialog because your application is not giving itself a chance to handle the input event or Intent broadcast.


[How to Avoid ANR]

* The recommended approach is to create a child thread and do most of your work there.
  • This keeps the main thread (which drives the user interface event loop) running and prevents the system from concluding that your code has frozen. 
  • Since such threading usually is accomplished at the class level.

* Potentially long running operations (ex: network or database operations, or computationally expensive calculations such as resizing bitmaps) should be done in a child thread (or in the case of databases operations, via an asynchronous request). However, this does not mean that your main thread should block while waiting for the child thread to complete.

* Should also avoid starting an Activity from an Intent Receiver (it will spawn a new screen that will steal focus from whatever application the user is currently has running). If your application has something to show the user in response to an Intent broadcast, it should do so using the Notification Manager.



* Reference
- Designing for Responsiveness

eclipse ini setting

* eclipse JVM
-vm
C:/(jdk path)/bin/javaw.exe

* The priority of eclipse using JVM
  1. eclipse.ini
  2. jre in eclipse
  3. jre that set in system


* Reference
- Rex
- Eclipse.ini
- FAQ How do I run Eclipse?
- Please make sure the -vm option in eclipse.ini is pointing to a JDK and verify that Installed JRE’s are also using JDK installs

2011年4月3日 星期日

[API] Alarm

* Alarm 會被取消的狀態

1. 重新開機

2. 重新安裝 app


---- Update on 2013/06/20 ----

更新不影響其狀態。


---- Update on 2013/08/25 ----

如果時間已經超過設定的 trigger time 那麼會馬上執行。

2011年4月2日 星期六

Security 的三個層次

1. 管道安全性: ex: https

2. 語言通不通: ex: 內文加密 PK

3. 認不認識對方: ex: pwd