### Formatting Inline Code Examples Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.ug/src/main/asciidoc/core/EclipseLink_UserGuide_Contributor_Guidelines.adoc Use the `+Example+` syntax to display code examples inline, rendering them in an example font. This is useful for short code snippets or keywords. ```asciidoc +Example+ ``` -------------------------------- ### Example PartitioningPolicy Implementation Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.jpa/src/main/asciidoc/queryhints.adoc Provides an example implementation of a custom PartitioningPolicy for distributing database access. ```java public class OrderPartitioningPolicy extends PartitioningPolicy { public List getConnectionsForQuery(AbstractSession session, DatabaseQuery query, AbstractRecord arguments) { List accessors = new ArrayList(1); accessors.add(getAccessor(ACMEPool.leastBusy(), session, query, false)); return accessors; } } ``` -------------------------------- ### Mapping Example Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.moxy/src/main/asciidoc/loe.adoc A general example of XML mapping. ```java @XmlAccessorType(XmlAccessType.PROPERTY) public class Example { private String value; @XmlElement(name = "data") public String getValue() { return value; } public void setValue(String value) { this.value = value; } } ``` -------------------------------- ### Example Sequences Configuration in Java Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.ug/src/main/asciidoc/core/Configuring_a_Relational_Descriptor_(ELUG).adoc This example demonstrates how to configure different types of sequences (table and native) on the session's login. These sequences can then be referenced by name from descriptors. ```java DatabaseLogin login = new DatabaseLogin(); login.setDriverClassName("oracle.jdbc.driver.OracleDriver"); login.setConnectionString("jdbc:oracle:thin:@localhost:1521:XE"); login.setUser("user"); login.setPassword("password"); // Table sequencing login.addSequence("SEQ_MY_TABLE", new TableSequence(login, "SEQUENCE", "SEQ_NAME", "SEQ_COUNT")); // Native sequencing login.addSequence("SEQ_MY_NATIVE", new NativeSequence(login, "MY_ORACLE_SEQ")); return login; ``` -------------------------------- ### Example QueryRedirector Implementation Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.jpa/src/main/asciidoc/queryhints.adoc An example implementation of the QueryRedirector interface, demonstrating how to intercept and process query execution. ```java ... public class MyQueryRedirector implements QueryRedirector { @Override public Object invokeQuery(DatabaseQuery query, DataRecord dataRecord, Session session) { List result = (List)session.executeQuery(query); return result.toArray(new Object[result.size()]); } } ... ``` -------------------------------- ### Output for binding-tenant2.xml Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.moxy/src/main/asciidoc/loe.adoc Example output XML based on binding-tenant2.xml. ```xml tenant2 ``` -------------------------------- ### JSON Binding Example (Map) Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.moxy/src/main/asciidoc/loe.adoc A JSON binding example specifically demonstrating the use of a Map. ```java import org.eclipse.persistence.jaxb.JAXBContextFactory; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import java.io.StringReader; import java.io.StringWriter; import java.util.Map; import java.util.HashMap; // Assuming a class that holds a Map: // public class MapContainer { public Map properties; } public class JsonMapExample { public static void main(String[] args) throws Exception { // Create a JAXBContext for JSON binding JAXBContext jc = JAXBContextFactory.createContext("{"json-binding-package"}", Thread.currentThread().getContextClassLoader()); // Create an object with a Map MapContainer container = new MapContainer(); Map props = new HashMap<>(); props.put("key1", "value1"); props.put("key2", "value2"); container.properties = props; // Marshal to JSON Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.setProperty("org.eclipse.persistence.jaxb.marshaller.json-ற்றம்", "true"); StringWriter writer = new StringWriter(); marshaller.marshal(container, writer); System.out.println("Marshalled JSON with Map:\n" + writer.toString()); // Unmarshal from JSON Unmarshaller unmarshaller = jc.createUnmarshaller(); StringReader reader = new StringReader(writer.toString()); MapContainer unmarshalledContainer = (MapContainer) unmarshaller.unmarshal(reader); // Verify the unmarshalled object System.out.println("Unmarshalled Map key1: " + unmarshalledContainer.properties.get("key1")); } } // Dummy MapContainer class for compilation class MapContainer { public Map properties; } ``` -------------------------------- ### JDBC Driver Fetch Size Example Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.ug/src/main/asciidoc/core/Optimizing_the_EclipseLink_Application_(ELUG).adoc Demonstrates how to set the JDBC fetch size for a ReadAllQuery to optimize data retrieval. This example also shows how to use a ScrollableCursor for processing large result sets efficiently. ```java // Create query and set Employee as its reference class ReadAllQuery query = new ReadAllQuery(Employee.class); ExpressionBuilder builder = query.getExpressionBuilder(); query.setSelectionCriteria(builder.get("id").greaterThan(100)); // Set the JDBC fetch size query.setFetchSize(50); // Configure the query to return results as a ScrollableCursor query.useScrollableCursor(); // Execute the query ScrollableCursor cursor = (ScrollableCursor) session.executeQuery(query); // Iterate over the results while (cursor.hasNext()) { System.out.println(cursor.next().toString()); } cursor.close(); ``` -------------------------------- ### Example: Generate Java Classes with Output Directory Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.moxy/src/main/asciidoc/advanced_concepts008.adoc This example demonstrates how to use the JAXB Compiler to generate Java classes from a specific XSD file and place the output in a designated directory. ```bash jaxb-compiler.sh -d jaxb-compiler-output config/Customer.xsd ``` -------------------------------- ### Output for binding-tenant1.xml Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.moxy/src/main/asciidoc/loe.adoc Example output XML based on binding-tenant1.xml. ```xml ``` -------------------------------- ### Example Customer Object Mapping Values to a Simple Sequence Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.solutions/src/main/asciidoc/jpatoxml003.adoc A complete example of the Customer class with 'firstName' and 'lastName' mapped to specific XML element names. ```java package example; import jakarta.xml.bind.annotation.*; @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class Customer { @XmlElement(name="first-name") private String firstName; @XmlElement(name="last-name") private String lastName; ... } ``` -------------------------------- ### Formatting Multi-line Code Examples Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.ug/src/main/asciidoc/core/EclipseLink_UserGuide_Contributor_Guidelines.adoc To display multiple lines of code examples correctly, indent the first character of each line with a single space. This ensures proper rendering in the documentation. ```asciidoc +example line 1+ +example line 2+ +example line 3+ ``` -------------------------------- ### Example 2-91 Using @Partitioning Annotation Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.jpa/src/main/asciidoc/annotations_ref.adoc Provides an example of using the @Partitioning annotation with a custom OrderPartitioningPolicy class. ```APIDOC ## @Entity Order ### Description Applies a custom partitioning policy to the Order entity. ### Annotations - `@Partitioning(name="order", partitioningClass=OrderPartitioningPolicy.class)`: Configures a custom partitioning policy named 'order' using the `OrderPartitioningPolicy` class. ### Custom Policy Example ```java public class OrderPartitioningPolicy extends PartitioningPolicy { public List getConnectionsForQuery(AbstractSession session, DatabaseQuery query, AbstractRecord arguments) { List accessors = new ArrayList(1); accessors.add(getAccessor(ACMEPool.leastBusy(), session, query, false)); return accessors; } } ``` ``` -------------------------------- ### Marshalling and Unmarshalling Example (Dynamic JAXB - Alternative) Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.moxy/src/main/asciidoc/loe.adoc Another example of marshalling and unmarshalling using dynamic JAXB, potentially with different configurations or data. ```java import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import java.io.StringReader; import java.io.StringWriter; import example.Employee; import example.Address; import example.Project; public class DynamicJaxbMarshalling2 { public static void main(String[] args) throws Exception { // Create a JAXBContext for the Employee class JAXBContext jc = JAXBContext.newInstance("example"); // Create an Employee object with different data Employee employee = new Employee(); employee.setName("John Smith"); Address address = new Address(); address.setStreet("456 Oak Ave"); address.setCity("Otherville"); address.setPostalCode("67890"); employee.setAddress(address); Project project1 = new Project(); project1.setName("Project Gamma"); project1.setHours(20); employee.setProjects(new Project[]{project1}); // Marshall the Employee object to XML Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); StringWriter writer = new StringWriter(); marshaller.marshal(employee, writer); System.out.println("Marshalled XML:\n" + writer.toString()); // Unmarshall the XML back to an Employee object Unmarshaller unmarshaller = jc.createUnmarshaller(); StringReader reader = new StringReader(writer.toString()); Employee unmarshalledEmployee = (Employee) unmarshaller.unmarshal(reader); // Verify the unmarshalled object System.out.println("Unmarshalled Employee Name: " + unmarshalledEmployee.getName()); System.out.println("Unmarshalled Employee City: " + unmarshalledEmployee.getAddress().getCity()); System.out.println("Unmarshalled Employee Project 1: " + unmarshalledEmployee.getProjects()[0].getName()); } } ``` -------------------------------- ### Configure Sequencing Start at NextVal in persistence.xml Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.jpa/src/main/asciidoc/persistenceproperties_ref.adoc Enable the sequencing.start-sequence-at-nextval property in persistence.xml to generate ID values starting from the sequence's NEXTVAL. ```xml ``` -------------------------------- ### Partial Object Reading Example Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.ug/src/main/asciidoc/core/Using_Basic_Query_API_(ELUG).adoc Demonstrates partial object reading to retrieve only the last name and primary key for employees, reducing data transfer from the database. This example reads all employees and asks the user to choose one. ```java // Read all the employees from the database, ask the user to choose one and return it. // This uses partial object reading to read just the last name of the employees. Since ``` -------------------------------- ### EclipseLink Build Properties Configuration Source: https://github.com/eclipse-ee4j/eclipselink/wiki/Building-EclipseLink Example content for the build.properties file, specifying paths for dependencies, Eclipse SDK installation, and JDBC driver details for testing. ```properties extensions.depend.dir=$HOME/extension.lib.external junit.lib=$HOME/extension.lib.external/junit-4.13.2.jar:$HOME/extension.lib.external/hamcrest-core-1.3.jar eclipse.install.dir=$HOME/extension.lib.external/eclipse jdbc.driver.jar=$HOME/extension.lib.external/mysql-connector-java.jar db.driver=com.mysql.cj.jdbc.Driver db.url=jdbc:mysql://localhost:3306/ecltests?allowPublicKeyRetrieval=true db.user=root db.pwd=root db.platform=org.eclipse.persistence.platform.database.MySQLPlatform ``` -------------------------------- ### Bootstrapping Example for Dynamic JAXB Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.moxy/src/main/asciidoc/loe.adoc Demonstrates bootstrapping a JAXBContext using external bindings, likely with a custom .xjb file. ```java import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import java.net.URL; public class DynamicJaxbBootstrapping { public static void main(String[] args) { try { // Load the external bindings file URL bindings = DynamicJaxbBootstrapping.class.getClassLoader().getResource("custom1.xjb"); if (bindings == null) { System.err.println("Error: custom1.xjb not found."); return; } // Create a JAXBContext using the external bindings JAXBContext jc = JAXBContext.newInstance("com.example.custom", Thread.currentThread().getContextClassLoader(), bindings); System.out.println("JAXBContext created successfully with external bindings."); // Now use 'jc' for marshalling/unmarshalling } catch (JAXBException e) { System.err.println("Error creating JAXBContext: " + e.getMessage()); e.printStackTrace(); } } } ``` -------------------------------- ### Example Sequences Configuration Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.ug/src/main/asciidoc/core/Configuring_a_Relational_Descriptor_(ELUG).adoc Demonstrates adding different types of sequences to the database login configuration. ```java dbLogin.addSequence(new TableSequence("EMP_SEQ", 25)); dbLogin.addSequence(new DefaultSequence("PHONE_SEQ", 30)); dbLogin.addSequence(new UnaryTableSequence("ADD_SEQ", 55)); dbLogin.addSequence(new NativeSequence("NAT_SEQ", 10)); ``` -------------------------------- ### XML Customer Document Example Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.moxy/src/main/asciidoc/runtime008.adoc An example XML document representing a customer. ```xml Jon Smith 515 2726652 ``` -------------------------------- ### Sample Application Code for Dynamic JAXB (Another Alternative) Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.moxy/src/main/asciidoc/loe.adoc Sample application code demonstrating dynamic JAXB with a product data model. ```java import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import java.io.StringReader; import java.io.StringWriter; import com.example.data.Product; public class DynamicJaxbAppCode3 { public static void main(String[] args) throws Exception { // Create a JAXBContext for the "com.example.data" package JAXBContext jc = JAXBContext.newInstance("com.example.data"); // Create a Product object Product product = new Product(); product.setProductId("P1001"); product.setProductName("Laptop"); product.setPrice(1200.50); // Marshall the Product object to XML Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); StringWriter writer = new StringWriter(); marshaller.marshal(product, writer); System.out.println("Marshalled XML:\n" + writer.toString()); // Unmarshall the XML back to a Product object Unmarshaller unmarshaller = jc.createUnmarshaller(); StringReader reader = new StringReader(writer.toString()); Product unmarshalledProduct = (Product) unmarshaller.unmarshal(reader); // Verify the unmarshalled object System.out.println("Unmarshalled Product Name: " + unmarshalledProduct.getProductName()); System.out.println("Unmarshalled Product Price: " + unmarshalledProduct.getPrice()); } } ``` -------------------------------- ### JSON Binding Example Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.moxy/src/main/asciidoc/loe.adoc A general example of JSON binding, likely covering common use cases. ```java import org.eclipse.persistence.jaxb.JAXBContextFactory; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import java.io.StringReader; import java.io.StringWriter; // Assuming a simple class like this exists: // public class ExampleData { public String field1; public int field2; } public class GeneralJsonExample { public static void main(String[] args) throws Exception { // Create a JAXBContext for JSON binding JAXBContext jc = JAXBContextFactory.createContext("{"json-binding-package"}", Thread.currentThread().getContextClassLoader()); // Create an object to marshal ExampleData data = new ExampleData(); data.field1 = "Value One"; data.field2 = 42; // Marshal to JSON Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.setProperty("org.eclipse.persistence.jaxb.marshaller.json-ற்றம்", "true"); StringWriter writer = new StringWriter(); marshaller.marshal(data, writer); System.out.println("Marshalled JSON:\n" + writer.toString()); // Unmarshal from JSON Unmarshaller unmarshaller = jc.createUnmarshaller(); StringReader reader = new StringReader(writer.toString()); ExampleData unmarshalledData = (ExampleData) unmarshaller.unmarshal(reader); // Verify the unmarshalled object System.out.println("Unmarshalled Field1: " + unmarshalledData.field1); System.out.println("Unmarshalled Field2: " + unmarshalledData.field2); } } // Dummy ExampleData class for compilation class ExampleData { public String field1; public int field2; } ``` -------------------------------- ### Example: Using Union and Value Partitioning Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.jpa/src/main/asciidoc/annotations_ref.adoc Demonstrates the use of @UnionPartitioning and @ValuePartitioning annotations on an entity to distribute data across different database nodes based on entity attributes. ```java @Entity @IdClass(EmployeePK.class) @UnionPartitioning( name="UnionPartitioningAllNodes", replicateWrites=true) @ValuePartitioning( name="ValuePartitioningByLOCATION", partitionColumn=@Column(name="LOCATION"), unionUnpartitionableQueries=true, defaultConnectionPool="default", partitions={ @ValuePartition(connectionPool="node2", value="Ottawa"), @ValuePartition(connectionPool="node3", value="Toronto") }) @Partitioned("ValuePartitioningByLOCATION") public class Employee { @Id @Column(name = "EMP_ID") private Integer id; @Id private String location; ... @ManyToMany(cascade = { PERSIST, MERGE }) @Partitioned("UnionPartitioningAllNodes") private Collection projects; ... } ``` -------------------------------- ### JSON with Attribute Prefix Example Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.moxy/src/main/asciidoc/json003.adoc Example JSON structure demonstrating the use of an attribute prefix for mapping. ```json { "phone" : { "area-code" : "613", "@number" : "1234567" } } ``` -------------------------------- ### Marshalling and Unmarshalling Example (Dynamic JAXB) Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.moxy/src/main/asciidoc/loe.adoc Demonstrates marshalling and unmarshalling using dynamic JAXB. ```java import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import java.io.StringReader; import java.io.StringWriter; import java.util.GregorianCalendar; import example.Employee; import example.Address; import example.Project; public class DynamicJaxbMarshalling { public static void main(String[] args) throws Exception { // Create a JAXBContext for the Employee class JAXBContext jc = JAXBContext.newInstance("example"); // Create an Employee object Employee employee = new Employee(); employee.setName("Jane Doe"); Address address = new Address(); address.setStreet("123 Main St"); address.setCity("Anytown"); address.setPostalCode("12345"); employee.setAddress(address); Project project1 = new Project(); project1.setName("Project Alpha"); project1.setHours(40); Project project2 = new Project(); project2.setName("Project Beta"); project2.setHours(32); employee.setProjects(new Project[]{project1, project2}); // Marshall the Employee object to XML Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); StringWriter writer = new StringWriter(); marshaller.marshal(employee, writer); System.out.println("Marshalled XML:\n" + writer.toString()); // Unmarshall the XML back to an Employee object Unmarshaller unmarshaller = jc.createUnmarshaller(); StringReader reader = new StringReader(writer.toString()); Employee unmarshalledEmployee = (Employee) unmarshaller.unmarshal(reader); // Verify the unmarshalled object System.out.println("Unmarshalled Employee Name: " + unmarshalledEmployee.getName()); System.out.println("Unmarshalled Employee City: " + unmarshalledEmployee.getAddress().getCity()); System.out.println("Unmarshalled Employee Project 1: " + unmarshalledEmployee.getProjects()[0].getName()); } } ``` -------------------------------- ### Example: Custom Partitioning Policy Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.jpa/src/main/asciidoc/annotations_ref.adoc Shows how to implement a custom partitioning policy by extending EclipseLink's PartitioningPolicy and overriding the getConnectionsForQuery method to define custom connection logic. ```java @Entity @Partitioning(name="order", partitioningClass=OrderPartitioningPolicy.class) @public class Order { ... } public class OrderPartitioningPolicy extends PartitioningPolicy { public List getConnectionsForQuery(AbstractSession session, DatabaseQuery query, AbstractRecord arguments) { List accessors = new ArrayList(1); accessors.add(getAccessor(ACMEPool.leastBusy(), session, query, false)); return accessors; } } ``` -------------------------------- ### Original Customer Schema Example Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.moxy/src/main/asciidoc/advanced_concepts003.adoc An example of an XML schema for a Customer element, defining 'first-name' and 'last-name' elements. ```xml ``` -------------------------------- ### JSON Example for Data Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.solutions/src/main/asciidoc/restful_jpa004.adoc This is an example of a JSON payload representing data, likely a list of entities with nested manager information. ```json [ { "firstName": "Miles", "lastName": "Davis", "manager": { "firstName": "Charlie", "lastName": "Parker", "gender": "Male", "id": 26 } }, { "firstName": "Charlie", "lastName": "Parker", "manager": { "firstName": "Louis", "lastName": "Armstrong", "gender": "Male", "id": 27 } } ] ``` -------------------------------- ### Java Classes for Inheritance Example Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.moxy/src/main/asciidoc/type_level003.adoc Defines abstract ContactInfo and concrete Address and PhoneNumber classes used in inheritance examples. ```java public abstract class ContactInfo { } public class Address extends ContactInfo { private String street; ... } public class PhoneNumber extends ContactInfo { private String number; ... } ``` ```java @XmlRootElement public class Customer { private ContactInfo contactInfo; ... } ``` -------------------------------- ### Example: Using Range Partitioning Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.jpa/src/main/asciidoc/annotations_ref.adoc Illustrates the @RangePartitioning annotation for distributing entity data across different connection pools based on a specified range of values in a partition column. ```java @Entity @RangePartitioning( name="RangePartitioningByPROJ_ID", partitionColumn=@Column(name="PROJ_ID"), partitionValueType=Integer.class, unionUnpartitionableQueries=true, partitions={ @RangePartition(connectionPool="default", startValue="0", endValue="1000"), @RangePartition(connectionPool="node2", startValue="1000", endValue="2000"), @RangePartition(connectionPool="node3", startValue="2000") }) @Partitioned("RangePartitioningByPROJ_ID") public class Project { @Id @Column(name="PROJ_ID") private Integer id; ... } ``` -------------------------------- ### XML Element Examples Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.jpa/src/main/asciidoc/annotations_ref.adoc Examples demonstrating the use of the XML element for configuring multitenancy, mirroring the @TenantDiscriminatorColumn annotation. ```APIDOC ## XML Element Examples ### Description Examples demonstrating the use of the XML element for configuring multitenancy. ### Usage * Single tenant discriminator column: ```xml ... ``` * Multiple tenant discriminator columns using multiple tables: ```xml
... ``` * Tenant discriminator column mapped as part of the primary key on the database: ```xml
... ``` * Mapped tenant discriminator column: ```xml
... ... ... ``` ``` -------------------------------- ### Display JAXB Compiler Help Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.moxy/src/main/asciidoc/advanced_concepts008.adoc Execute this command to view a comprehensive list of all available options and their descriptions for the JAXB Compiler. ```bash jaxb-compiler.sh -help ``` -------------------------------- ### Descriptor Exception Example Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.ug/src/main/asciidoc/core/EclipseLink_Exception_Error_Reference_(ELUG).adoc An example of a DescriptorException indicating that the reference class is not specified. This exception is raised when insufficient information is provided to the descriptor. ```text EXCEPTION [ECLIPSELINK – 75]: org.eclipse.persistence.exceptions.DescriptorException EXCEPTION DESCRIPTION: The reference class is not specified. ``` -------------------------------- ### SessionCustomizer Implementation Example Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.dbws/src/main/asciidoc/overview003.adoc Example of implementing SessionCustomizer to programmatically access and modify EclipseLink session settings, such as transaction isolation levels. ```java package some.java.package; import org.eclipse.persistence.sessions.SessionCustomizer; import org.eclipse.persistence.sessions.Session; import org.eclipse.persistence.sessions.DatabaseLogin; public class MySessionCustomizer implements SessionCustomizer { public MySessionCustomizer() { } public void customize(Sesssion session) { DatabaseLogin login = (DatabaseLogin)session.getDatasourceLogin(); login.setTransactionIsolation(DatabaseLogin.TRANSACTION_READ_UNCOMMITTED); } } ``` -------------------------------- ### Retrieve All Records as a List Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.ug/src/main/asciidoc/core/Using_Advanced_Query_API_(ELUG).adoc This example demonstrates retrieving all query results into a List. Be aware that for large datasets, this can consume significant memory as all objects are loaded at once. ```java ReadAllQuery query = new ReadAllQuery(Employee.class); Enumeration employeeEnumeration; List employees = (List) session.executeQuery(query); employeeEnumeration = employee.elements(); while (employeeEnumeration.hasMoreElements()) { Employee employee = (Employee) employeeEnumeration.nextElement(); employee.doSomeWork(); } ``` -------------------------------- ### Configure Deployment on Startup Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.jpa/src/main/asciidoc/persistenceproperties_ref.adoc Controls whether the persistence unit is deployed upon EntityManagerFactory creation or delayed until the first EntityManager is created. Setting to 'true' may increase server startup time but avoids first-request hangs. ```xml ``` -------------------------------- ### Using the DefaultSequence Class Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.ug/src/main/asciidoc/core/Configuring_a_Database_Login_(ELUG).adoc Shows how to use the `DefaultSequence` class as a wrapper for the platform default sequence, avoiding the need to clone it. This is useful for creating new sequences with specific names and preallocation sizes based on the platform's default type. ```java login.addSequence(new DefaultSequence("EMP_SEQ", 75)); ``` -------------------------------- ### Configure Sequencing Start at NextVal in Property Map Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.jpa/src/main/asciidoc/persistenceproperties_ref.adoc Set the SEQUENCING_START_AT_NEXTVAL property to 'true' in a property map to ensure sequence-generated IDs start at NEXTVAL. ```java import org.eclipse.persistence.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.SEQUENCING_START_AT_NEXTVAL, "true"); ``` -------------------------------- ### Ignore Error Element Example Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.ug/src/main/asciidoc/core/Using_Workbench_(ELUG).adoc This example demonstrates how to use the ignoreerror element within a mappings.export task to ignore a specific Workbench error code (0545). ```xml ``` -------------------------------- ### Using JSON to Bootstrap a JAXBContext Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.moxy/src/main/asciidoc/loe.adoc Demonstrates bootstrapping a JAXBContext directly from JSON configuration, rather than XML schema. ```java import org.eclipse.persistence.jaxb.JAXBContextFactory; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import java.io.StringReader; import java.io.StringWriter; // Assuming a simple class like this exists: // public class BootstrappedData { public String status; } public class JsonBootstrapJaxb { public static void main(String[] args) throws Exception { // JSON configuration string (can also be read from a file) String jsonConfig = "{\"json-binding-package\": \"com.example.bootstrap\", \"classes\": [\"BootstrappedData\"]}"; // Create a JAXBContext using the JSON configuration JAXBContext jc = JAXBContextFactory.createContext(jsonConfig, Thread.currentThread().getContextClassLoader()); // Create an object to marshal BootstrappedData data = new BootstrappedData(); data.status = "Initialized"; // Marshal to JSON Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.setProperty("org.eclipse.persistence.jaxb.marshaller.json-ற்றம்", "true"); StringWriter writer = new StringWriter(); marshaller.marshal(data, writer); System.out.println("Marshalled JSON (Bootstrapped):\n" + writer.toString()); // Unmarshal from JSON Unmarshaller unmarshaller = jc.createUnmarshaller(); StringReader reader = new StringReader(writer.toString()); BootstrappedData unmarshalledData = (BootstrappedData) unmarshaller.unmarshal(reader); // Verify the unmarshalled object System.out.println("Unmarshalled Status: " + unmarshalledData.status); } } // Dummy BootstrappedData class for compilation class BootstrappedData { public String status; } ``` -------------------------------- ### PARTITIONING Query Hint Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.jpa/src/main/asciidoc/queryhints.adoc Demonstrates how to use the PARTITIONING query hint with the @QueryHint annotation to specify a custom partitioning policy. ```APIDOC ## PARTITIONING Query Hint ### Description This query hint allows you to specify a custom partitioning policy for queries. It is useful for distributing data across multiple databases or tables. ### Usage Can be used with the `@QueryHint` annotation. ### Example ```java import org.eclipse.persistence.config.HintValues; import org.eclipse.persistence.config.QueryHints; @QueryHint(name=QueryHints.PARTITIONING, value="org.acme.persistence.OrderPartitioningPolicy"); ``` ``` -------------------------------- ### XML Response Example for Query Results Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.solutions/src/main/asciidoc/restful_jpa004.adoc Example of an XML response for a query returning a list of entities. 'List' is the grouping name for the collection and 'item' for each member. ```xml Miles Davis Charlie Parker Male 26 Charlie Parker Louis Armstrong Male 27 ``` -------------------------------- ### Force Session Reparse and Login Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.ug/src/main/asciidoc/core/Acquiring_and_Using_Sessions_at_Run_Time_(ELUG).adoc This example demonstrates forcing a reparse of the sessions.xml file and logging in the session. This is typically used in redeployment scenarios. ```java //In this example, XMLSessionConfigLoader loads sessions.xml from the classpath SessionManager manager = SessionManager.getManager(); Session session = manager.getSession( new XMLSessionConfigLoader(), // XMLSessionConfigLoader (sessions.xml file) "mysession", // session name YourApplicationClass.getClassLoader(), // class loader true, // log in session true // refresh session ); ``` -------------------------------- ### SelectedFieldsLockingPolicy SQL Example Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.ug/src/main/asciidoc/core/Introduction_to_Descriptors_(ELUG).adoc Provides an example of SQL generated by EclipseLink when using SelectedFieldsLockingPolicy, where only specific fields (LNAME and CREDIT_RATING) are used for optimistic locking checks during an update. ```SQL UPDATE CUSTOMER SET LNAME='new name' WHERE ID=7 AND LNAME='old name' AND CREDIT_RATING='A+' ``` -------------------------------- ### Query Employee by Name using Query-by-Example Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.ug/src/main/asciidoc/core/Using_Basic_Query_API_(ELUG).adoc Use Query-by-Example with ReadObjectQuery to find a specific employee by their first and last name. The sample object defines the search criteria. ```java Employee employee = new Employee(); employee.setFirstName("Bob"); employee.setLastName("Smith"); ReadObjectQuery query = new ReadObjectQuery(Employee.class); query.setExampleObject(employee); Employee result = (Employee) session.executeQuery(query); ``` -------------------------------- ### Classpath Element Example Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.ug/src/main/asciidoc/core/Using_Workbench_(ELUG).adoc This example shows a typical classpath element configuration within an Ant build file. It is used to define the Java classpath necessary for running a task. ```xml ``` -------------------------------- ### Update Query Example Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.ug/src/main/asciidoc/jpa/Developing_Applications_Using_EclipseLink_JPA_(ELUG).adoc Use an UPDATE statement with JP QL to perform bulk updates on entities. This example demonstrates giving employees a raise based on their current salary. ```sql UPDATE Employee e SET e.salary = 60000 WHERE e.salary = 50000 ``` -------------------------------- ### Sample Application Code for Dynamic JAXB (Alternative) Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.moxy/src/main/asciidoc/loe.adoc Sample application code demonstrating dynamic JAXB usage with a different data model. ```java import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import java.io.StringReader; import java.io.StringWriter; import example.Customer; import example.Order; import example.Item; public class DynamicJaxbAppCode2 { public static void main(String[] args) throws Exception { // Create a JAXBContext for the "example" package JAXBContext jc = JAXBContext.newInstance("example"); // Create a Customer object Customer customer = new Customer(); customer.setFirstName("Bob"); customer.setLastName("The Builder"); Order order = new Order(); order.setOrderId("ORD123"); Item item1 = new Item(); item1.setItemName("Hammer"); item1.setQuantity(2); Item item2 = new Item(); item2.setItemName("Screwdriver"); item2.setQuantity(5); order.setItem(new Item[]{item1, item2}); customer.setOrder(order); // Marshall the Customer object to XML Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); StringWriter writer = new StringWriter(); marshaller.marshal(customer, writer); System.out.println("Marshalled XML:\n" + writer.toString()); // Unmarshall the XML back to a Customer object Unmarshaller unmarshaller = jc.createUnmarshaller(); StringReader reader = new StringReader(writer.toString()); Customer unmarshalledCustomer = (Customer) unmarshaller.unmarshal(reader); // Verify the unmarshalled object System.out.println("Unmarshalled Customer Name: " + unmarshalledCustomer.getFirstName() + " " + unmarshalledCustomer.getLastName()); System.out.println("Unmarshalled Order ID: " + unmarshalledCustomer.getOrder().getOrderId()); } } ``` -------------------------------- ### Mappings Export Task Example Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.ug/src/main/asciidoc/core/Using_Workbench_(ELUG).adoc This example demonstrates a typical mappings.export Ant task configuration. It specifies project and deployment files, a property, error handling, and a classpath reference. ```xml ``` -------------------------------- ### Using External Bindings for JSON Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.moxy/src/main/asciidoc/loe.adoc Demonstrates how to use external binding files (e.g., MOXy's oxm.xml) to configure JSON binding. ```java import org.eclipse.persistence.jaxb.JAXBContextFactory; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import java.io.StringReader; import java.io.StringWriter; import java.util.HashMap; import java.util.Map; // Assuming a class like this exists and is configured via oxm.xml: // public class ConfiguredData { public String value; } public class ExternalJsonBinding { public static void main(String[] args) throws Exception { // Load external bindings (e.g., oxm.xml) Map properties = new HashMap<>(); properties.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, "oxm.xml"); // Specify the binding file properties.put(Marshaller.JAXB_FORMATTED_OUTPUT, true); properties.put("org.eclipse.persistence.jaxb.marshaller.json-ற்றம்", "true"); // Create a JAXBContext using the external bindings JAXBContext jc = JAXBContextFactory.createContext("{"json-binding-package"}", Thread.currentThread().getContextClassLoader(), properties); // Create an object to marshal ConfiguredData data = new ConfiguredData(); data.value = "Configured Value"; // Marshal to JSON Marshaller marshaller = jc.createMarshaller(); StringWriter writer = new StringWriter(); marshaller.marshal(data, writer); System.out.println("Marshalled JSON with external bindings:\n" + writer.toString()); // Unmarshal from JSON Unmarshaller unmarshaller = jc.createUnmarshaller(); StringReader reader = new StringReader(writer.toString()); ConfiguredData unmarshalledData = (ConfiguredData) unmarshaller.unmarshal(reader); // Verify the unmarshalled object System.out.println("Unmarshalled Value: " + unmarshalledData.value); } } // Dummy ConfiguredData class for compilation class ConfiguredData { public String value; } ``` -------------------------------- ### Serialized Object Policy Example Model Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.solutions/src/main/asciidoc/performance001.adoc Defines an inheritance hierarchy for a serialized object policy example, including abstract and concrete entity classes with relationships and named queries. ```java @Entity(name="SOP_PartOrWhole") @Table(name="SOP_PART_OR_WHOLE") @Inheritance(strategy=InheritanceType.SINGLE_TABLE) @Index(columnNames={"LEFTPART_ID", "RIGHTPART_ID"}) public abstract class PartOrWhole implements Serializable { @Id @GeneratedValue(strategy=GenerationType.TABLE) public long id; protected String description = ""; @OneToOne(cascade=CascadeType.ALL, orphanRemoval=true) protected Part leftPart; @OneToOne(cascade=CascadeType.ALL, orphanRemoval=true) protected Part rightPart; } ``` ```java @Entity(name="SOP_Whole") @DiscriminatorValue("W") @SerializedObject(MySerializedObjectPolicy.class) @NamedQueries({ @NamedQuery(name="findWhole", query="Select w from SOP_Whole w where w.id = :id", hints= @QueryHint(name="eclipselink.serialized-object", value="false")), @NamedQuery(name="findWholeSOP", query="Select w from SOP_Whole w where w.id = :id"), }) public class Whole extends PartOrWhole { } ``` ```java @Entity(name="SOP_Part") @DiscriminatorValue("P") public class Part extends PartOrWhole { } ``` -------------------------------- ### Simple ReadAllQuery Example Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.ug/src/main/asciidoc/core/Using_Basic_Query_API_(ELUG).adoc Returns a List of employees whose employee ID is greater than 100. Initializes the query with the reference class and configures the selection criteria using an ExpressionBuilder. ```java ReadAllQuery query = new ReadAllQuery(Employee.class); ExpressionBuilder builder = query.getExpressionBuilder(); query.setSelectionCriteria(builder.get("id").greaterThan(100)); List employees = (List) session.executeQuery(query); ``` -------------------------------- ### Using Partitioning in @QueryHint Annotation Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.jpa/src/main/asciidoc/queryhints.adoc Demonstrates how to configure partitioning for queries using the @QueryHint annotation. Requires a custom PartitioningPolicy implementation. ```java import org.eclipse.persistence.config.HintValues; import org.eclipse.persistence.config.QueryHints; @QueryHint(name=QueryHints.PARTITIONING, value="org.acme.persistence.OrderPartitioningPolicy"); ``` -------------------------------- ### Example of @VariableOneToOne Annotation Usage Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.jpa/src/main/asciidoc/annotations_ref.adoc Demonstrates the usage of the @VariableOneToOne annotation for mapping polymorphic associations. This example is typically used in conjunction with discriminator columns to manage different entity types. ```java @Entity @Table(name = "EMPLOYEE") @VariableOneToOne( TargetInterface = Employee.class, DiscriminatorColumn = "DTYPE", DiscriminatorClasses = { @DiscriminatorClass(value = "FULLTIME", discriminator = FullTimeEmployee.class), @DiscriminatorClass(value = "PARTTIME", discriminator = PartTimeEmployee.class) } ) public abstract class Employee implements Serializable { // ... implementation details } ``` -------------------------------- ### @TenantDiscriminatorColumn Annotation Examples Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.jpa/src/main/asciidoc/annotations_ref.adoc Examples demonstrating the use of the @TenantDiscriminatorColumn annotation for various multitenancy scenarios, including single tenant, multiple tenant discriminator columns, and mapped discriminator columns. ```APIDOC ## @TenantDiscriminatorColumn Annotation Examples ### Description Examples demonstrating the use of the @TenantDiscriminatorColumn annotation for various multitenancy scenarios. ### Usage * Single tenant discriminator column: ```java @Entity @Table(name = "CUSTOMER") @Multitenant @TenantDiscriminatorColumn(name = "TENANT", contextProperty = "multi-tenant.id") public class Customer { // ... } ``` * Multiple tenant discriminator columns using multiple tables: ```java @Entity @Table(name = "EMPLOYEE") @SecondaryTable(name = "RESPONSIBILITIES") @Multitenant(SINGLE_TABLE) @TenantDiscriminatorColumns({ @TenantDiscriminatorColumn(name = "TENANT_ID", contextProperty = "employee-tenant.id", length = 20), @TenantDiscriminatorColumn(name = "TENANT_CODE", contextProperty = "employee-tenant.code", discriminatorType = STRING, table = "RESPONSIBILITIES") }) public class Employee { // ... } ``` * Tenant discriminator column mapped as part of the primary key on the database: ```java @Entity @Table(name = "ADDRESS") @Multitenant @TenantDiscriminatorColumn(name = "TENANT", contextProperty = "tenant.id", primaryKey = true) public class Address { // ... } ``` * Mapped tenant discriminator column: ```java @Entity @Table(name = "Player") @Multitenant @TenantDiscriminatorColumn(name = "AGE", contextProperty = "tenant.age") public class Player { // ... @Basic @Column(name="AGE", insertable="false", updatable="false") public int age; } ``` ``` -------------------------------- ### Query-by-Example with LIKE Operator Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.ug/src/main/asciidoc/core/Using_Basic_Query_API_(ELUG).adoc Use Query-by-Example to filter results based on string patterns using the 'like' operator and numeric ranges with 'greaterThan'. Ensures the 'salary' attribute is always included. ```java Employee employee = new Employee(); employee.setFirstName("B%"); employee.setLastName("S%"); employee.setSalary(0); // Create a query and set Employee as its reference class ReadAllQuery query = new ReadAllQuery(Employee.class); query.setExampleObject(employee); // Query by example policy section adds like and greaterThan QueryByExamplePolicy policy = new QueryByExamplePolicy(); policy.addSpecialOperation(String.class, "like"); policy.addSpecialOperation(Integer.class, "greaterThan"); policy.alwaysIncludeAttribute(Employee.class, "salary"); query.setQueryByExamplePolicy(policy); List results = (List) session.executeQuery(query); ``` -------------------------------- ### Minimal @Multitenant Annotation Example Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.jpa/src/main/asciidoc/annotations_ref.adoc A minimal example demonstrating the @Multitenant annotation on an entity. This configuration implies that the entity's data is stored across multiple tenants in a single table. ```java @Entity @Multitenant public class Player { } ``` -------------------------------- ### Example 2-89 Using Partitioning Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.jpa/src/main/asciidoc/annotations_ref.adoc Demonstrates the use of @UnionPartitioning and @ValuePartitioning annotations on an Entity to configure data partitioning strategies for writes and value-based partitioning respectively. ```APIDOC ## @Entity Employee ### Description Configures data partitioning for the Employee entity using both union and value-based strategies. ### Annotations - `@IdClass(EmployeePK.class)`: Specifies the primary key class. - `@UnionPartitioning(name="UnionPartitioningAllNodes", replicateWrites=true)`: Configures union partitioning, replicating writes across all nodes. - `@ValuePartitioning(name="ValuePartitioningByLOCATION", partitionColumn=@Column(name="LOCATION"), unionUnpartitionableQueries=true, defaultConnectionPool="default", partitions={ @ValuePartition(connectionPool="node2", value="Ottawa"), @ValuePartition(connectionPool="node3", value="Toronto") })`: Configures value-based partitioning on the 'LOCATION' column, with specific partitions for 'Ottawa' and 'Toronto'. - `@Partitioned("ValuePartitioningByLOCATION")`: Applies the defined value partitioning strategy. ### Relationships - `@ManyToMany(cascade = { PERSIST, MERGE }) @Partitioned("UnionPartitioningAllNodes") private Collection projects;`: Configures partitioning for the 'projects' relationship using the union partitioning strategy. ``` -------------------------------- ### Generate project.xml from Command Line Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.ug/src/main/asciidoc/core/Creating_EclipseLink_Files_for_Deployment_(ELUG).adoc Generate the project.xml file from the command line using the DeploymentXMLGenerator. Ensure eclipselink.jar and eclipselinkmw.jar are in your classpath. ```bash java -classpath eclipselink.jar;eclispelinkmw.jar; org.eclipse.persistence.tools.workbench.mappings.DeploymentXMLGenerator ``` -------------------------------- ### EclipseLink Performance Profiler Output Example Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.ug/src/main/asciidoc/core/Optimizing_the_EclipseLink_Application_(ELUG).adoc This is an example of the output generated by the EclipseLink Performance Profiler. It details the profiling information for a ReadAllQuery, including object counts, execution times, and SQL-related metrics. ```text Begin Profile of{ ReadAllQuery(com.demos.employee.domain.Employee) Profile(ReadAllQuery,# of obj=12, time=1399,sql execute=217, prepare=495, row fetch=390, time/obj=116,obj/sec=8) } End Profile ``` -------------------------------- ### ChangedFieldsLockingPolicy SQL Example (Unit of Work 1) Source: https://github.com/eclipse-ee4j/eclipselink/blob/master/docs/docs.ug/src/main/asciidoc/core/Introduction_to_Descriptors_(ELUG).adoc Shows the SQL generated by EclipseLink for an update operation using ChangedFieldsLockingPolicy, where only changed fields are compared. This example represents an update to the last name. ```SQL UPDATE CUSTOMER SET LNAME='new name' WHERE ID=7 AND LNAME='old name' ```