Skip to main content

Home/ SoftwareEngineering/ Group items tagged wikibooks

Rss Feed Group items tagged

kuni katsuya

Java Persistence/ManyToMany - Wikibooks, open books for an open world - 0 views

  • Bi-directional Many to Many
  • object model can choose if it will be mapped in both directions
  • in which direction it will be mapped
  • ...9 more annotations...
  • one direction must be defined as the owner and the other must use the mappedBy attribute to define its mapping
  • you will end up getting duplicate rows
  • If the mappedBy is not used, then the persistence provider will assume there are two independent relationships
  • As with all bi-directional relationships it is your object model's and application's responsibility to maintain the relationship in both direction
  • Mapping a Join Table with Additional Columns
  • solution is to create a class that models the join table
  • requires a composite primary key
  • To make your life simpler, I would recommend adding a generated Id attribute to the association class
  • Another usage is if you have a Map relationship between two objects, with a third unrelated object or data representing the Map key
    • kuni katsuya
       
      eg. map key = AuthorizationContext, map value = {Subject,Role}
kuni katsuya

Java Persistence/Inheritance - Wikibooks, open books for an open world - 0 views

  • Inheritance
  • hardest part of persisting inheritance is choosing how to represent the inheritance in the database
  • There are three inheritance strategies defined from the InheritanceType enum,
  • ...101 more annotations...
  • SINGLE_TABLE
  • TABLE_PER_CLASS
  • JOINED
  • Single table inheritance is the default
  • @MappedSuperclass
  • @Inheritance
  • mapped superclass is
  • not a persistent class
  • but allow common mappings to be define for its subclasses
  • Single Table Inheritance
    • kuni katsuya
       
      implemented as a sparse table. ie. all attributes from all entities end up as columns in the 'super' table
  • single table is used to store all of the instances of the entire inheritance hierarchy
  • table will have a column for
  • every attribute
  • every class
  • in the hierarchy
  • discriminator column
  • is used to determine which class the particular row belongs to
  • abstract
  • Project
  • extends Project
  • extends Project
  • @DiscriminatorValue("S")
  • @DiscriminatorValue("L")
  • @DiscriminatorColumn(name="PROJ_TYPE")
  • @Inheritance
  • @Table(name="PROJECT")
  • single table inheritance
  • Joined, Multiple Table Inheritance
  • mirrors the object model in the data model
  • table is defined for each class in the inheritance hierarchy to store only the local attributes of that class
  • Each table in the hierarchy must also store the object's id (primary key), which is
  • only defined in the root class
  • share the same id attribute
  • joined inheritance
  • @Inheritance(strategy=
  • InheritanceType.JOINED
  • @DiscriminatorColumn(name="PROJ_TYPE")
  • @Table(name="PROJECT")
  • abstract
  • Project
  • @DiscriminatorValue("L")
  • @Table(name=
  • "LARGEPROJECT"
  • LargeProject
  • Project
  • @DiscriminatorValue("S")
  • @Table(name=
  • "SMALLPROJECT"
  • SmallProject
  • Project
  • Table Per Class Inheritance
  • Advanced
  • table is defined for
  • each concrete class
  • in the inheritance hierarchy to store
  • all the attributes
  • of that class and
  • all of its superclasses
  • table per class inheritance
  • @Inheritance(strategy=
  • InheritanceType.TABLE_PER_CLASS
  • abstract
  • Project
  • @Table(name="LARGEPROJECT")
  • LargeProject
  • Project
  • @Table(name="SMALLPROJECT")
  • SmallProject
  • Project
  • Mapped Superclasses
  • similar to table per class inheritance, but does not allow querying, persisting, or relationships to the superclass
  • mapped superclass
  • @MappedSuperclass
  • abstract
  • Project
  • @Column(name="NAME")
  • @Table(name="LARGEPROJECT")
  • LargeProject
  • Project
  • @AttributeOverride
  • "PROJECT_NAME"
  • "name"
  • @Table("SMALLPROJECT")
  • SmallProject
  • Project
  • cannot have a relationship to a mapped superclass
  • Joined, Multiple Table Inheritance
  • oined, Multiple Table Inheritance
  • abstract
  • abstract c
  • extends Project
  • Mapped Superclasses
  • Mapped Superclasses
  • apped Superclasses
  • allows inheritance to be used in the object model, when it does not exist in the data model
  • @MappedSuperclass
  • MappedSuperclass
  • abstract
  • abstract
  • extends Project
  • extends Project
kuni katsuya

Java Persistence/Advanced Topics - Wikibooks, open books for an open world - 0 views

  • Events
  • hook into a system that allows the execution of some code when the event occurs
  • JPA defines several events for the persistent
  • ...37 more annotations...
  • life-cycle
  • of Entity objects
  • JPA defines the following events:
  • PostLoad
  • PrePersist
  • PostPersist
  • PreUpdate
  • PostUpdate
  • PreRemove
  • PostRemove
  • after an Entity is loaded into the
  • persistence context
  • before the persist operation is invoked on an Entity
  • after a refresh operation.
  • before the remove operation is invoked on an Entity
  • cascade of a remove operation
  • during a flush or commit for orphanRemoval in JPA 2.0
  • after an instance is deleted from the database
  • occurs during a flush or commit operation
  • after the database DELETE has occurred
  • before the transaction is committed
  • after an instance is updated in the database
  • occurs during a flush or commit operation
  • after the database UPDATE has occurred
  • before the transaction is committed
  • before an instance is updated in the database
  • occurs during a flush or commit operation
  • after the database UPDATE has occurred
  • before the transaction is committed
  • after a new instance is persisted to the database
  • occurs during a flush or commit operation
  • after the database INSERT has occurred
  • before the transaction is committed
  • Id of the object should be assigned
  • merge for new instances
  • cascade of a persist operation
  • Id of the object may not have been assigned, and code be assigned by the event
kuni katsuya

Java Persistence/Mapping - Wikibooks, open books for an open world - 0 views

  • Access Type
  • field
  • get method
  • ...21 more annotations...
  • FIELD
  • PROPERTY
  • Either all annotations must be on the fields, or all annotations on the get methods, but not both (unless the @AccessType annotation is used)
  • if placed on a get method, then the class is using PROPERTY access
  • For FIELD access the class field value will be accessed directly to store and load the value from the database
  • field can be private or any other access type
  • FIELD is normally safer, as it avoids any unwanted side-affect code that may occur in the application get/set methods
  • For PROPERTY access the class get and set methods will be used to store and load the value from the database
  • PROPERTY has the advantage of allowing the application to perform conversion of the database value when storing it in the object
  • be careful to not put any side-affects in the get/set methods that could interfere with persistence
  • Common Problems
  • Odd behavior
  • One common issue that can cause odd behavior is
  • using property access and putting side effects in your get or set methods
  • For this reason it is generally recommended to
  • use field access in mapping, i.e. putting your annotations on your variables not your get methods
  • causing duplicate inserts, missed updates, or a corrupt object model
  • if you are going to use property access, ensure your property methods are free of side effects
  • Access Type
  • Access Type
  • Access Type
  •  
    "Access Type"
kuni katsuya

Java Persistence/Relationships - Wikibooks, open books for an open world - 0 views

  • Cascading
  • following operations can be cascaded, as defined in the CascadeType enum:
  • PERSIST
  • ...11 more annotations...
  • If persist() is called on the
  • parent
  • and the
  • child
  • is also new, it will also be persisted
  • MERGE
  • REFRESH
  • REMOVE
  • . If remove() is called on the parent then the child will also be removed
  • . If merge() is called on the parent, then the child will also be merged
  • If refresh() is called on the parent then the child will also be refreshed
kuni katsuya

Java Persistence/Persisting - Wikibooks, open books for an open world - 0 views

  • Persist
  • used to insert a new object into the database
  • it just registers it as new in the persistence context (transaction)
  • ...6 more annotations...
  • Merge
  • When the transaction is committed, or if the persistence context is flushed, then the object will be updated in the database.
  • used to merge the changes made to a detached object into the persistence context
  • it merges the changes into the persistence context (transaction)
  • When the transaction is committed, or if the persistence context is flushed, then the object will be inserted into the database
  • merge is only required when you have a detached copy of a persistence object
kuni katsuya

Java Persistence/Relationships - Wikibooks, open books for an open world - 0 views

  • Map Key Columns (JPA 2.0)
  • Nested Collections, Maps and Matrices
  • List of Lists
  • ...58 more annotations...
  • Map of Maps,
  • Map of Lists
  • JPA does not support nested collection relationships
  • One solution is to create an object that wraps the nested collection.
  • Map<String, List<Project>>
  • Example nested collection model (original)
  • Example nested collection model (modified)
  • Map<String, ProjectType>
  • @MapKey(name="type")
  • mappedBy="employee"
  • employee
  • type;
  • List<Project>
  • ProjectType
    • kuni katsuya
       
      ProjectType wraps the original map value type List>
  • Maps J
  • JPA allows a Map to be used for any collection mapping including, OneToMany, ManyToMany and ElementCollection
  • @MapKey annotation
  • used to define a map relationship
  • @MapKey(name="type")
  • Map<String, PhoneNumber>
  • type;
  • mappedBy="owner"
  • owner
  • Map Key Columns (JPA 2.0)
  • Map Key Columns (JPA 2.0)
  • JPA 2.0 allows for a Map where the key is not part of the target object to be persisted. The Map key can be any of the following:
  • A Basic value, stored in the target's table or join table.
  • An Embedded object, stored in the target's table or join table.
  • A foreign key to another Entity, stored in the target's table or join table.
  • if the value is a Basic but the key is an Entity a
  • ElementCollection
  • mapping is used.
  • if the key is a Basic but the value is an Entity a
  • OneToMany
  • mapping is still used
  • a three way join table, can be mapped using a
  • ManyToMany with a MapKeyJoinColumn for the third foreign key
  • @MapKeyJoinColumn
  • used to define a map relationship where the
  • key is an Entity value
  • can also be used with this for composite foreign keys
  • @MapKeyClass
  • can be used when the key is an Embeddable
  • if generics are not used
  • @MapKeyColumn
  • Map<String, Phone>
  • mappedBy="owner"
  • owner
  • @MapKeyJoinColumn
  • PHONE_TYPE_ID
  • PHONE_TYPE_ID
  • Map<PhoneType, Phone>
  • mappedBy="owner"
  • owner
  • @MapKeyClass(PhoneType.class)
  • @Embeddable
  • PhoneType
  • Map<PhoneType, Phone>
  •  
    "Map Key Columns (JPA 2.0)"
kuni katsuya

Java Persistence/Transactions - Wikibooks, open books for an open world - 0 views

  • JTA transactions are
  • implicitly defined through SessionBean usage/methods. In a SessionBean normally each SessionBean method invocation defines a JTA transaction.
  • JTA Transactions
  • ...10 more annotations...
  • In JEE managed mode, such as an EntityManager injected into a SessionBean, the EntityManager reference, represents a new persistence context for each transaction. This means objects read in one transaction become detached after the end of the transaction, and should no longer be used, or need to be merged into the next transaction. In managed mode, you never create or close an EntityManager.
  • Transactions
  • operations that are committed or rolled back as a single unit
  • JPA provides two mechanisms for transactions
  • JTA (Java Transaction API
  • EntityTransaction
  • all changes made to all persistent objects in the persistence context are part of the transaction.
  • Nested Transactions
  • do not support nested transactions
  • JPA and JTA
kuni katsuya

Java Persistence/Querying - Wikibooks, open books for an open world - 0 views

  • Result Set Mapping
  • When a native SQL query returns objects, the SQL must ensure it returns the correct data to build the resultClass using the correct column names as specified in the mappings. If the SQL is more complex and returns different column names, or returns data for multiple objects then a @SqlResultSetMapping must be used.
  • @NamedNativeQuery
  • ...7 more annotations...
  • resultClass=Employee.class
  • class Employee
  • createNamedQuery("findAllEmployeesInCity")
  • List<Employee>
  • @NamedNativeQuery
  • resultSetMapping="employee-address"
  • @SqlResultSetMapping(name="employee-address", entities={ @EntityResult(entityClass=Employee.class), @EntityResult(entityClass=Address.class)} )
  •  
    Result Set Mapping
kuni katsuya

Java Persistence/Auditing and Security - Wikibooks, open books for an open world - 0 views

  • Use a common database user id, and manage auditing and security in the application
  • managed in the application by having an application user, and a single shared database user
  • adding a AUDIT_USER and AUDIT_TIMESTAMP column to all of the audited tables and auditUser and auditTimestamp field to all of the audited objects
  • ...5 more annotations...
  • When the application inserts or updates an object, it will set these fields and they will be stored in the database. JPA events could also be used to record the audit information, or to write to a separate audit table.
  • Example AuditedObject class
  • @MappedSuperclass public Class AuditedObject {
  • @Column("AUDIT_USER"); protected String auditUser; @Column("AUDIT_TIMESTAMP"); protected Calendar auditTimestamp;
  • @PrePersist @PreUpdate public void updateAuditInfo() { setAuditUser((String)AuditedObject.currentUser.get()); setAuditTimestamp(Calendar.getInstance()); }
  •  
    Use a common database user id, and manage auditing and security in the application
kuni katsuya

Java Persistence/Runtime - Wikibooks, open books for an open world - 0 views

  • In JEE the EntityManager or EntityManagerFactory can
  • injected into a SessionBean
  • A managed EntityManager should never be closed, and integrates with JTA transactions
  • ...3 more annotations...
  • Example of injecting an EntityManager and EntityManagerFactory in a SessionBean
  • @Stateless
  • @PersistenceContext(unitName="acme") private EntityManager entityManager;
1 - 14 of 14
Showing 20 items per page