Java Persistence Frameworks - 1.1
Extension ID
com.castsoftware.java.hibernate
What’s new?
Please see Java Persistence Frameworks - 1.1 - Release Notes for more information.
Description
This extension provides support for Java Persistence frameworks such as JPA, Jakarta Persistence and 3 majors implementations (Hibernate, EclipseLink, Apache OpenJPA), as well as Ebean ORM, Spring Hibernate, EJB Entity, etc. (see below for the full list of supported frameworks).
Note that the JEE Analyzerprovides full support for JPA and Hibernate, however, this extension provides additional support and should be used for any application using Ebean ORM, JPA, Jakarta Persistence, EclipseLink and Apache OpenJPA libraries.
In what situation should you install this extension?
If your Java application uses a supported Java Persistence framework (see below for the full list of supported frameworks), and you want to view these object types and their links, then you should install this extension. More specifically the extension will identify:
- “callLinks” from Java methods to JPA Entity Operation objects.
- “callLinks” from Java methods to JPA SQL Query objects.
- “callLinks” from Java methods to JPQL Query objects.
- “callLinks” from JPQL Query Objects to JPA Entity Operation objects.
- “callLinks” from JPA Entity Operation objects to Life Cycle annotated Java Methods
Technology support
The following libraries are supported by this extension:
Library name | Version | Supported | Supported Technology |
---|---|---|---|
JPA | 1.0 to 2.2 | ✅ | Java |
Jakarta Persistence | 2.2 to 3.1 | ✅ | Java |
Hibernate | 2.0 to 6.5.x | ✅ | Java |
EclipseLink | 2.6.0 to 4.0.2 | ✅ | Java |
Apache OpenJPA | 1.0 to 3.2 | ✅ | Java |
Spring Hibernate | 3.0 to 6.1.x | ✅ | Java |
Ebean ORM | 10.0 to 13.25 | ✅ | Java |
EJB Entity | 1.1 to 3.0 | ✅ | Java |
Supported persistence libraries
JPA |
|
---|---|
Jakarta Persistence | |
Hibernate
|
|
EclipseLink | |
Apache OpenJPA | |
Spring Hibernate | |
Ebean ORM | |
EJB |
Supported JPA Annotations
The following JPA annotations are supported, whatever their full name : in javax.persistence, jakarta.persistence or in specific library package name, when overidden.
|
Compatibility
This extension is compatible with:
Core release | Operating System | Supported |
---|---|---|
8.4.x | Microsoft Windows/Linux | ✅ |
8.3.x | Microsoft Windows | ✅ |
Download and installation instructions
For Java applications using any of the above mentioned libraries, this extension will be automatically installed. This is in place since October 2023.
For upgrade, if the Extension Strategy is not set to Auto update, you can manually upgrade the extension using the Application - Extensions interface.
What results can you expect?
Objects
Icon | Description | Comment |
---|---|---|
JPA Entity | an object is created when we encounter @Entity annotation | |
JPA Entity Operation | an object is created for each CRUD operation performed on Entity | |
JPA SQL Query | an object is created for each native SQL query found and resolved in a method call | |
JPQL Query | an object is created for each HQL or JPQL query found and resolved in a method call | |
JPA Unknown SQL Query | an object is created for each SQL / HQL / JPQL query found and the exact query cannot be resolved | |
JPA Unknown Entity | an object is created when entity cannot be resolved | |
JPA Unknown Entity Operation | an object is created when CRUD operation is performed and Entity cannot be resolved |
Links
Link Type |
Caller type | Callee type |
Java Persistence Framework APIs Supported |
---|---|---|---|
callLink
|
Java Method | JPA Entity Operation, JPA Unknown Entity Operation |
|
callLink | Java Method | callLink between the caller Java Method and JPA SQL Query / JPQL Query / JPA Unknown SQL Query object | |
callLink | JPA Entity Operation | Java Method | |
useLink | JPA SQL Query / JPQL Query | Table / View | Created by SQL Analyzer when DDL source files are analyzed |
callLink | JPA SQL Query / JPQL Query | Procedure | |
useLink | JPA Entity Operation | Table / View | Created by WBS when DDL source files are analyzed by SQL Analyzer |
callLink | JPA Entity Operation | Procedure | |
useLink | JPA SQL Query / JPQL Query | Missing Table | Created by Missing tables and procedures for JEE extension when the object is not analyzed |
callLink | JPA SQL Query / JPQL Query | Missing Procedure |
Code examples
CRUD Operations
Update Operation
Entity using hbm xml
hbm.xml File
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.javainterviewpoint.Employee" table="EMPLOYEE">
<id name="id" column="ID">
<generator class="assigned" />
</id>
<property name="name" column="NAME" />
<property name="age" column="AGE" />
<property name="dept" column="DEPT" />
</class>
</hibernate-mapping>
Hibernate Update Operation
public void updateEmployeeById(int id,String name)
{
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
Employee employee = (Employee)session.get(Employee.class, id);
employee.setName(name);
session.update(employee);
session.getTransaction().commit();
System.out.println("Employee Updated!!!");
}
Entity using @Entity annotation
JPA Entity
@Entity
@Table(name = "cast_student", schema = "TEST")
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Student implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String firstName;
private String lastName;
private String email;
}
Hibernate Update Operation
public void updateStudent(Integer id, String firstName, String lastName, String email) {
Transaction transaction = null;
Session session = null;
try{
session = HibernateUtil.getSessionFactory().openSession();
transaction = session.beginTransaction();
Student student = session.get(Student.class, id);
if(firstName != null){
student.setFirstName(firstName);
}
if(lastName != null){
student.setLastName(lastName);
}
if(email != null){
student.setEmail(email);
}
session.update(student);
transaction.commit();
}catch (Exception e){
try{
transaction.rollback();
}catch(RuntimeException re){
re.getMessage();
}
throw e;
}finally {
if(session != null){
session.close();
}
}
}
Select Operation
Parent Entity with Inheritance Joined
@Table(name = "account_table")
@Entity(name = "Account")
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class Account {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String owner;
private double balance;
private double interestRate;
}
Child Entity
@Entity(name="DebitAccount")
@Table(name = "debit_account_table")
public class CreditAccount extends Account {
private double creditLimit;
}
JPA Select Operation
public boolean getDebitAccountCRUD(Long theId){
try {
session = dataSourceFactory.getSessionFactory().openSession();
beginTransactionIfAllowed(session);
DebitAccount creditAccount = session.get(DebitAccount.class, theId);
session.getTransaction().commit();
return true;
}
}
Add Operation
Secondary Table
@Table(name = "author")
@Entity
@SecondaryTables({
@SecondaryTable(name = "author_details"),
@SecondaryTable( name = "author_data")
})
public abstract class Author{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private double lastName;
private double category;
}
JPA Add Operation
public static void main(String[] args) {
Transaction transaction = null;
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
// start a transaction
transaction = session.beginTransaction();
// save the author object
Author author = new Author();
author.setBalance(10000.0);
author.setInterestRate(10.0);
author.setOwner("Ramesh");
author.setCreditLimit(10000.0);
session.save(author);
}
}
Delete Operation
Ebean deleteAll Operation
public void deleteByIds() {
UserContext.set("fred", "ten_2");
MtContent a = newContent("title a");
MtContent b = newContent("title b");
List<Long> ids = Arrays.asList(a.getId(), b.getId(), 99998L);
LoggedSql.start();
int rows = server.deleteAll(MtContent.class, ids);
assertThat(rows).isEqualTo(2);
List<String> sql = LoggedSql.stop();
assertSql(sql.get(0)).contains("delete from mt_content where id=? and tenant_id=?");
}
SaveOrUpdate
Hibernate SaveOrUpdate Operation
public boolean saveCompany() {
try {
final Company theCompany = new Company();
session = dataSourceFactory.getSessionFactory().openSession();
beginTransactionIfAllowed(session);
session.saveOrUpdate(theCompany);
session.getTransaction().commit();
logging.setMessage("CompanyDaoImpl -> saving company...");
return true;
} catch (HibernateException ex) {
session.getTransaction().rollback();
logging.setMessage("CompanyDaoImpl Error -> "+ex.getLocalizedMessage());
return false;
} finally {
if(session.isOpen()){session.close();}
}
}
Hibernate Query
Raw SQL Query
JPA SQL Query
@Test
public void whenNamedQuery_thenMultipleEntityResult() {
final Query query = em.createNativeQuery("SELECT e.id, e.name, d.id, d.employeeId, d.dayOfWeek "
+ " FROM employee e, schedule_days d "
+ " WHERE e.id = d.employeeId", "EmployeeScheduleResults");
List<Object[]> results = query.getResultList();
assertEquals(4, results.size());
assertTrue(results.get(0).length == 2);
Employee emp = (Employee) results.get(1)[0];
ScheduledDay day = (ScheduledDay) results.get(1)[1];
assertTrue(day.getEmployeeId() == emp.getId());
}
CriteriaQuery
Criteria Query
public class HibernateCriteriaBuilderJoinQueryClient {
public static void main(String[] args) {
try(Session session = HibernateUtil.getSessionFactory().openSession()) {
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<Object[]> criteriaQuery = builder.createQuery(Object[].class);
Root<Employee> empRoot = criteriaQuery.from(Employee.class);
Root<Department> deptRoot = criteriaQuery.from(Department.class);
criteriaQuery.multiselect(empRoot, deptRoot);
criteriaQuery.where(builder.equal(empRoot.get("department"), deptRoot.get("id")));
// List<Object[]> list = session.createQuery(criteriaQuery).getResultList();
TypedQuery<Employee> query = session.createQuery(criteriaQuery);
List<Object[]> list = query.getResultList();
for (Object[] objects : list) {
Employee emp = (Employee) objects[0];
System.out.println(emp.getId() + "\t" + emp.getName());
System.out.println("----------------------------------");
Department dept = (Department) objects[1];
System.out.println(dept.getId() + "\t" + dept.getName());
}
} catch(HibernateException e) {
e.printStackTrace();
}
}
}
Named Query / Named Native Query
JPA Entity
@Entity
@Table(name = "Address")
@NamedQueries({ @NamedQuery(name = "@HQL_GET_ALL_ADDRESS",
query = "from Address") })
@NamedNativeQueries({ @NamedNativeQuery(name = "@SQL_GET_ALL_ADDRESS",
query = "select emp_id, address_line1, city, zipcode from Address") })
public class Address {
@Id
@Column(name = "emp_id", unique = true, nullable = false)
@GeneratedValue(generator = "gen")
@GenericGenerator(name = "gen", strategy = "foreign", parameters = { @Parameter(name = "property", value = "employee") })
private long id;
@Column(name = "address_line1")
private String addressLine1;
@Column(name = "zipcode")
private String zipcode;
@Column(name = "city")
private String city;
}
Named Query
@SuppressWarnings("unchecked")
public static void main(String[] args) {
// Prep work
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.getCurrentSession();
Transaction tx = session.beginTransaction();
query = session.getNamedQuery("@HQL_GET_ALL_ADDRESS");
List<Address> addressList = query.list();
for (Address addr : addressList) {
System.out.println("List of Address::" + addr.getId() + "::"
+ addr.getZipcode() + "::" + addr.getEmployee().getName());
}
//Native SQL Named Query Example
Query query = session.getNamedQuery("@SQL_GET_ALL_ADDRESS");
List<Object[]> addressObjArray = query.list();
for(Object[] row : addressObjArray){
for(Object obj : row){
System.out.print(obj + "::");
}
System.out.println("\n");
}
query = session.getNamedQuery("SQL_GET_ALL_EMP_ADDRESS");
addressObjArray = query.list();
for(Object[] row : addressObjArray){
Employee e = (Employee) row[0];
System.out.println("Employee Info::"+e);
Address a = (Address) row[1];
System.out.println("Address Info::"+a);
}
// rolling back to save the test data
tx.commit();
// closing hibernate resources
sessionFactory.close();
}
NamedStoredProcedureQuery
JPA Entity
@Entity
@Table(name = "CAR")
@NamedStoredProcedureQueries({@NamedStoredProcedureQuery(name = "findByYearProcedure", procedureName = "FIND_CAR_BY_YEAR", resultClasses = { Car.class }, parameters = { @StoredProcedureParameter(name = "p_year", type = Integer.class, mode = ParameterMode.IN) }) })
@NamedStoredProcedureQuery(name = "getTotalCardsbyModelEntity", procedureName = "GET_TOTAL_CARS_BY_MODEL", resultClasses = { Car.class }, parameters = {@StoredProcedureParameter(mode = ParameterMode.IN, name = "model_in", type = String.class),@StoredProcedureParameter(mode = ParameterMode.OUT, name = "count_out", type = Integer.class)})
public class Car {
private long id;
private String model;
private Integer year;
public Car(final String model, final Integer year) {
this.model = model;
this.year = year;
}
}
Named Stored Procedure
public void findCarsByYearNoNamed() {
final StoredProcedureQuery storedProcedure = entityManager.createStoredProcedureQuery("FIND_CAR_BY_YEAR", Car.class)
.registerStoredProcedureParameter(1, Integer.class, ParameterMode.IN)
.setParameter(1, 2015);
storedProcedure.getResultList()
.forEach(c -> Assert.assertEquals(new Integer(2015), ((Car) c).getYear()));
}
public void findCarsByModelYearNoNamed() {
final StoredProcedureQuery storedProcedure = entityManager.createStoredProcedureQuery("FIND_CARS_AFTER_YEAR", Car.class)
.registerStoredProcedureParameter(1, Integer.class, ParameterMode.IN)
.setParameter(1, 2015);
storedProcedure.getResultList()
.forEach(c -> Assert.assertEquals(new Integer(2015), ((Car) c).getYear()));
}
JPQL Query
using hbm.xml
hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.javainterviewpoint.Employee" table="EMPLOYEE">
<id name="id" column="ID">
<generator class="assigned" />
</id>
<property name="name" column="NAME" />
<property name="age" column="AGE" />
<property name="dept" column="DEPT" />
</class>
<query name="HQL_GET_ALL_EMPLOYEE">from Employee</query>
<query name="HQL_GET_EMPLOYEE_BY_ID">
<![CDATA[select from Employee where emp_id = :id]]>
</query>
<query name="HQL_GET_EMPLOYEE_BY_SALARY">
<![CDATA[delete from Employee where emp_salary > :salary]]>
</query>
<sql-query name="SQL_GET_ALL_EMPLOYEE">
<![CDATA[select emp_id, emp_name, emp_salary from Employee]]>
</sql-query>
<sql-query name="SQL_GET_ALL_EMP_ADDRESS">
<![CDATA[select {e.*}, {a.*} from Employee e join Address a ON e.emp_id=a.emp_id]]>
<return alias="e" class="com.journaldev.hibernate.model.Employee" />
<return-join alias="a" property="e.address"></return-join>
</sql-query>
</hibernate-mapping>
JPQL Query
public static void main(String[] args)
{
// Prep work
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.getCurrentSession();
Transaction tx = session.beginTransaction();
//HQL Named Query Example
Query query = session.getNamedQuery("HQL_GET_EMPLOYEE_BY_SALARY");
List<Employee> empList = query.list();
for (Employee emp : empList) {
System.out.println("List of Employees::" + emp.getId() + ","
+ emp.getSalary());
}
}
using @NamedQueries/@NamedQuery
JPA Entity
@Entity
@Table(name = "Address")
@NamedQueries({ @NamedQuery(name = "@HQL_GET_ALL_ADDRESS",
query = "from Address") })
@NamedNativeQueries({ @NamedNativeQuery(name = "@SQL_GET_ALL_ADDRESS",
query = "select emp_id, address_line1, city, zipcode from Address") })
public class Address {
@Id
@Column(name = "emp_id", unique = true, nullable = false)
@GeneratedValue(generator = "gen")
@GenericGenerator(name = "gen", strategy = "foreign", parameters = { @Parameter(name = "property", value = "employee") })
private long id;
@Column(name = "address_line1")
private String addressLine1;
@Column(name = "zipcode")
private String zipcode;
@Column(name = "city")
private String city;
}
JPQL Query
public static void main(String[] args) {
// Prep work
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.getCurrentSession();
Transaction tx = session.beginTransaction();
Query query = session.getNamedQuery("@HQL_GET_ALL_ADDRESS");
List<Address> addressList = query.list();
for (Address addr : addressList) {
System.out.println("List of Address::" + addr.getId() + "::"
+ addr.getZipcode() + "::" + addr.getEmployee().getName());
}
}
Raw JPQL
JPQL Query
private static void displayEntities(EntityManagerFactory emf) {
//loading all entities
EntityManager em = emf.createEntityManager();
Query query = em.createQuery("Select e from Employee e");
List<Employee> list = (List<Employee>) query.getResultList();
Employee employee = new Employee("Sara Dorsey", "Admin");
for (Employee employee : list) {
//sending to ui for display
displayEntity(employee);
print("refreshing employee", employee);
//now refreshing entity before doing something with it
em.refresh(employee);
print("after refreshing employee", employee);
}
}
Apache OpenJPA
OpenJPA
OpenJPACriteriaQuery
@SuppressWarnings("unused")
public Page<Author> search(List<SearchCriteria> paramsAuthor, List<SearchCriteria> paramsBooks, Pageable pageable) {
OpenJPACriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
OpenJPACriteriaQuery<Author> criteriaQuery = criteriaBuilder.createQuery(Author.class);
CriteriaDelete<Author> criteriaDelete = criteriaBuilder.createCriteriaDelete(Author.class);
CriteriaUpdate<Author> criteriaUpdate = criteriaBuilder.createCriteriaUpdate(Author.class);
Root<Author> author = criteriaQuery.from(Author.class);
Root<Author> author_update = criteriaUpdate.from(Author.class);
Root<Author> author_delete = criteriaDelete.from(Author.class);
Join<Author, Books> books = author.join("books", JoinType.INNER);
Predicate predicate = this.predicateRootBuilder(criteriaBuilder, paramsAuthor, author);
if(!paramsBooks.isEmpty())
predicate = this.predicateJoinBuilder(criteriaBuilder, paramsBooks, books);
Sort sort = pageable.isPaged() ? pageable.getSort() : Sort.unsorted();
if (sort.isSorted())
criteriaQuery.orderBy(toOrders(sort, author, criteriaBuilder));
criteriaQuery.distinct(true);
criteriaQuery.where(predicate);
criteriaDelete.where(author.get("first_name"));
criteriaUpdate.set(author.get("first_name"));
TypedQuery<Author> typedQuery = entityManager.createQuery(criteriaQuery);
entityManager.createQuery(criteriaDelete).executeUpdate();
entityManager.createQuery(criteriaUpdate).executeUpdate();
if(pageable == null)
return new PageImpl<Author>(typedQuery.getResultList());
else {
Long total = (long) typedQuery.getResultList().size();
// Sets the offset position in the result set to start pagination
typedQuery.setFirstResult((int) pageable.getOffset());
// Sets the maximum number of entities that should be included in the page
typedQuery.setMaxResults(pageable.getPageSize());
List<Author> content = total > pageable.getOffset() ? typedQuery.getResultList() : Collections.<Author> emptyList();
return new PageImpl<Author>(content, pageable, total);
}
Ebean Query
Select queries
Select Query
public static void queryCustomers() {
Customer customer = Ebean.find(Customer.class)
.select("name")
.fetch("address", "city")
.where()
.eq("city", "San Jose")
.findOne();
}
Update queries
Update Query
public static void CheckUpdate() {
// Assuming you have an EbeanServer instance
// EbeanServer ebeanServer = Ebean.getDefaultServer();
// Create a query
Query<Customer> query = Ebean.createQuery(Customer.class);
// Define the conditions for the delete operation
query.where().eq("status", "INACTIVE");
// You can add more conditions as needed
// Create a transaction
Transaction transaction = Ebean.beginTransaction();
try {
// Execute the delete query with the specified transaction
int rowsDeleted = query.update(transaction);
// Commit the transaction
transaction.commit();
System.out.println("Rows deleted: " + rowsDeleted);
} catch (Exception e) {
// Rollback the transaction in case of an exception
transaction.rollback();
e.printStackTrace();
} finally {
// End the transaction
transaction.end();
}
}
Delete queries
Delete Query
public static void CheckDelete() {
// Assuming you have an EbeanServer instance
// EbeanServer ebeanServer = Ebean.getDefaultServer();
// Create a query
Query<Customer> query = Ebean.createQuery(Customer.class);
// Define the conditions for the delete operation
query.where().eq("status", "INACTIVE");
// You can add more conditions as needed
// Create a transaction
Transaction transaction = Ebean.beginTransaction();
try {
// Execute the delete query with the specified transaction
int rowsDeleted = query.delete(transaction);
// Commit the transaction
transaction.commit();
System.out.println("Rows deleted: " + rowsDeleted);
} catch (Exception e) {
// Rollback the transaction in case of an exception
transaction.rollback();
e.printStackTrace();
} finally {
// End the transaction
transaction.end();
}
}
Named Query
Named Query
public static void CheckCreateNamedQuery() {
Query<Customer> query = DB.createNamedQuery(Customer.class, "findByName");
query.setParameter("name", name);
List<Customer> customers = query.findList();
}
Stored Procedure
Stored Procedure
public static void CheckExecute() {
// Create a new Database instance
Database database = DatabaseFactory.create();
// Prepare the SQL statement for the stored procedure call
CallableSql callableSql = new CallableSql("{call update_customer(?, ?)}")
.setParameter(1, 123) // Set the productId parameter to 123
.setParameter(2, 99.99); // Set the new Price parameter to 99.99
// Execute the Callable SQL statement and get the update count
int updateCount = database.execute(callableSql);
// Process the result
System.out.println("Rows Updated: " + updateCount);
}
EJB Query
ejb-ql
ejb-jar.xml
<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar>
<display-name>TradeEJBs</display-name>
<enterprise-beans>
<entity>
<display-name>OrderEJB</display-name>
<ejb-name>OrderEJB</ejb-name>
<local-home>org.apache.geronimo.samples.daytrader.ejb.LocalOrderHome</local-home>
<local>org.apache.geronimo.samples.daytrader.ejb.LocalOrder</local>
<ejb-class>org.apache.geronimo.samples.daytrader.ejb.OrderBean</ejb-class>
<persistence-type>Container</persistence-type>
<prim-key-class>java.lang.Integer</prim-key-class>
<reentrant>false</reentrant>
<cmp-version>2.x</cmp-version>
<abstract-schema-name>Orders</abstract-schema-name>
<cmp-field>
<field-name>orderFee</field-name>
</cmp-field>
<cmp-field>
<field-name>completionDate</field-name>
</cmp-field>
<cmp-field>
<field-name>orderType</field-name>
</cmp-field>
<cmp-field>
<field-name>orderStatus</field-name>
</cmp-field>
<cmp-field>
<field-name>price</field-name>
</cmp-field>
<cmp-field>
<field-name>quantity</field-name>
</cmp-field>
<cmp-field>
<field-name>openDate</field-name>
</cmp-field>
<cmp-field>
<field-name>orderID</field-name>
</cmp-field>
<primkey-field>orderID</primkey-field>
<security-identity>
<description/>
<use-caller-identity/>
</security-identity>
<query>
<description/>
<query-method>
<method-name>findAll</method-name>
<method-params/>
</query-method>
<result-type-mapping>Local</result-type-mapping>
<ejb-ql>SELECT OBJECT(o) FROM Orders o</ejb-ql>
</query>
<query>
<description/>
<query-method>
<method-name>findClosedOrders</method-name>
<method-params>
<method-param>java.lang.String</method-param>
</method-params>
</query-method>
<result-type-mapping>Local</result-type-mapping>
<ejb-ql>SELECT OBJECT(o) FROM Orders o WHERE
o.orderStatus = 'closed' AND
o.account.profile.userID = ?1</ejb-ql>
</query>
<query>
<description/>
<query-method>
<method-name>findByUserID</method-name>
<method-params>
<method-param>java.lang.String</method-param>
</method-params>
</query-method>
<result-type-mapping>Local</result-type-mapping>
<ejb-ql>SELECT OBJECT(o) FROM Orders o WHERE
o.account.profile.userID = ?1 ORDER BY o.orderID DESC</ejb-ql>
</query>
<query>
<query-method>
<method-name>findByPrimaryKeyForUpdate</method-name>
<method-params>
<method-param>java.lang.Integer</method-param>
</method-params>
</query-method>
<result-type-mapping>Local</result-type-mapping>
<ejb-ql>SELECT OBJECT(o) FROM Orders o WHERE o.orderID = ?1</ejb-ql>
</query>
<query>
<query-method>
<method-name>findClosedOrdersForUpdate</method-name>
<method-params>
<method-param>java.lang.String</method-param>
</method-params>
</query-method>
<result-type-mapping>Local</result-type-mapping>
<ejb-ql>SELECT OBJECT(o) FROM Orders o WHERE
o.orderStatus = 'closed' AND
o.account.profile.userID = ?1</ejb-ql>
</query>
</entity>
</enterprise-beans>
</ejb-jar>
EJB
public interface LocalOrderHome extends EJBLocalHome {
public LocalOrder create (int orderID, LocalAccount account, LocalQuote quote, LocalHolding holding, String orderType, double quantity)
throws CreateException;
public LocalOrder create (Integer orderID, LocalAccount account, LocalQuote quote, LocalHolding holding, String orderType, double quantity)
throws CreateException;
public LocalOrder findByPrimaryKeyForUpdate (Integer orderID)
throws FinderException;
public LocalOrder findByPrimaryKey (Integer orderID)
throws FinderException;
public Collection findAll()
throws FinderException;
public Collection findByUserID (String userID)
throws FinderException;
public Collection findClosedOrders(String userID)
throws FinderException;
public Collection findClosedOrdersForUpdate(String userID)
throws FinderException;
}
orion-ejb-jar
ejb-jar.xml
<?xml version = '1.0' encoding = 'windows-1252'?>
<ejb-jar>
<enterprise-beans>
<session>
<description>Session Bean ( Stateless )</description>
<display-name>StudentCourseEJB</display-name>
<ejb-name>StudentCourseEJB</ejb-name>
<home>com.jdevbook.chap6.ejbapp.StudentCourseEJBHome</home>
<remote>com.jdevbook.chap6.ejbapp.StudentCourseEJB</remote>
<ejb-class>com.jdevbook.chap6.ejbapp.StudentCourseEJBBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Container</transaction-type>
<ejb-local-ref>
<ejb-ref-name>ejb/local/Course</ejb-ref-name>
<ejb-ref-type>Entity</ejb-ref-type>
<local-home>com.jdevbook.chap6.ejbapp.CourseLocalHome</local-home>
<local>com.jdevbook.chap6.ejbapp.CourseLocal</local>
<ejb-link>Course</ejb-link>
</ejb-local-ref>
<ejb-local-ref>
<ejb-ref-name>ejb/local/Student</ejb-ref-name>
<ejb-ref-type>Entity</ejb-ref-type>
<local-home>com.jdevbook.chap6.ejbapp.StudentLocalHome</local-home>
<local>com.jdevbook.chap6.ejbapp.StudentLocal</local>
<ejb-link>Student</ejb-link>
</ejb-local-ref>
</session>
<entity>
<description>Entity Bean ( CMP )</description>
<display-name>Course</display-name>
<ejb-name>Course</ejb-name>
<local-home>com.jdevbook.chap6.ejbapp.CourseLocalHome</local-home>
<local>com.jdevbook.chap6.ejbapp.CourseLocal</local>
<ejb-class>com.jdevbook.chap6.ejbapp.CourseBean</ejb-class>
<persistence-type>Container</persistence-type>
<prim-key-class>java.lang.Long</prim-key-class>
<reentrant>False</reentrant>
<cmp-version>2.x</cmp-version>
<abstract-schema-name>Course</abstract-schema-name>
<cmp-field>
<field-name>courseId</field-name>
</cmp-field>
<cmp-field>
<field-name>courseName</field-name>
</cmp-field>
<primkey-field>courseId</primkey-field>
<query>
<query-method>
<method-name>findAll</method-name>
<method-params/>
</query-method>
<ejb-ql>select object(o) from Course o</ejb-ql>
</query>
</entity>
<entity>
<description>Entity Bean ( CMP )</description>
<display-name>Student</display-name>
<ejb-name>Student</ejb-name>
<local-home>com.jdevbook.chap6.ejbapp.StudentLocalHome</local-home>
<local>com.jdevbook.chap6.ejbapp.StudentLocal</local>
<ejb-class>com.jdevbook.chap6.ejbapp.StudentBean</ejb-class>
<persistence-type>Container</persistence-type>
<prim-key-class>java.lang.Long</prim-key-class>
<reentrant>False</reentrant>
<cmp-version>2.x</cmp-version>
<abstract-schema-name>Student</abstract-schema-name>
<cmp-field>
<field-name>studentId</field-name>
</cmp-field>
<cmp-field>
<field-name>studentName</field-name>
</cmp-field>
<primkey-field>studentId</primkey-field>
<query>
<query-method>
<method-name>findAll</method-name>
<method-params/>
</query-method>
<ejb-ql>select object(o) from Student o</ejb-ql>
</query>
</entity>
</enterprise-beans>
<relationships>
<ejb-relation>
<ejb-relation-name>Student - Course</ejb-relation-name>
<ejb-relationship-role>
<ejb-relationship-role-name>Student may have one Course</ejb-relationship-role-name>
<multiplicity>Many</multiplicity>
<relationship-role-source>
<ejb-name>Student</ejb-name>
</relationship-role-source>
<cmr-field>
<cmr-field-name>course_courseId</cmr-field-name>
</cmr-field>
</ejb-relationship-role>
<ejb-relationship-role>
<ejb-relationship-role-name>Course may have many Student</ejb-relationship-role-name>
<multiplicity>One</multiplicity>
<relationship-role-source>
<ejb-name>Course</ejb-name>
</relationship-role-source>
<cmr-field>
<cmr-field-name>student_courseId</cmr-field-name>
<cmr-field-type>java.util.Collection</cmr-field-type>
</cmr-field>
</ejb-relationship-role>
</ejb-relation>
</relationships>
<assembly-descriptor>
<container-transaction>
<method>
<ejb-name>Course</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>Supports</trans-attribute>
</container-transaction>
<container-transaction>
<method>
<ejb-name>Student</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>Supports</trans-attribute>
</container-transaction>
<container-transaction>
<method>
<ejb-name>StudentCourseEJB</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>Required</trans-attribute>
</container-transaction>
</assembly-descriptor>
</ejb-jar>
orion-ejb-jar.xml
<?xml version = '1.0' encoding = 'windows-1252'?>
<orion-ejb-jar>
<enterprise-beans>
<session-deployment name="StudentCourseEJB"/>
<entity-deployment name="Course" data-source="jdbc/OracleDBConnDS" table="SCOTT.COURSES">
<primkey-mapping>
<cmp-field-mapping name="courseId" persistence-name="COURSE_ID" persistence-type="NUMBER(5)"/>
</primkey-mapping>
<cmp-field-mapping name="courseId" persistence-name="COURSE_ID" persistence-type="NUMBER(5)"/>
<cmp-field-mapping name="courseName" persistence-name="COURSE_NAME" persistence-type="VARCHAR2(30)"/>
<cmp-field-mapping name="student_courseId">
<collection-mapping table="STUDENT">
<primkey-mapping>
<cmp-field-mapping>
<entity-ref home="Course">
<cmp-field-mapping persistence-name="COURSE_ID" persistence-type="NUMBER(5)"/>
</entity-ref>
</cmp-field-mapping>
</primkey-mapping>
<value-mapping type="com.jdevbook.chap6.ejbapp.StudentLocal">
<cmp-field-mapping>
<entity-ref home="Student">
<cmp-field-mapping persistence-name="STUDENT_ID" persistence-type="NUMBER(5)"/>
</entity-ref>
</cmp-field-mapping>
</value-mapping>
</collection-mapping>
</cmp-field-mapping>
</entity-deployment>
<entity-deployment name="Student" data-source="jdbc/OracleDBConnDS" table="SCOTT.STUDENT">
<primkey-mapping>
<cmp-field-mapping name="studentId" persistence-name="STUDENT_ID" persistence-type="NUMBER(5)"/>
</primkey-mapping>
<cmp-field-mapping name="studentId" persistence-name="STUDENT_ID" persistence-type="NUMBER(5)"/>
<cmp-field-mapping name="studentName" persistence-name="STUDENT_NAME" persistence-type="VARCHAR2(30)"/>
<cmp-field-mapping name="course_courseId" persistence-name="COURSE_ID">
<entity-ref home="Course">
<cmp-field-mapping persistence-name="COURSE_ID" persistence-type="NUMBER(5)"/>
</entity-ref>
</cmp-field-mapping>
</entity-deployment>
</enterprise-beans>
</orion-ejb-jar>
EJB
public interface CourseLocalHome extends EJBLocalHome
{
CourseLocal create() throws CreateException;
CourseLocal findByPrimaryKey(Long primaryKey) throws FinderException;
Collection findAll() throws FinderException;
CourseLocal create(Long courseId) throws CreateException;
}
jboss-ejb-jar
ejb-jar.xml
<?xml version = '1.0' encoding = 'windows-1252'?>
<ejb-jar>
<enterprise-beans>
<session>
<description>Session Bean ( Stateless )</description>
<display-name>StudentCourseEJB</display-name>
<ejb-name>StudentCourseEJB</ejb-name>
<home>com.jdevbook.chap6.ejbapp.StudentCourseEJBHome</home>
<remote>com.jdevbook.chap6.ejbapp.StudentCourseEJB</remote>
<ejb-class>com.jdevbook.chap6.ejbapp.StudentCourseEJBBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Container</transaction-type>
<ejb-local-ref>
<ejb-ref-name>ejb/local/Course</ejb-ref-name>
<ejb-ref-type>Entity</ejb-ref-type>
<local-home>com.jdevbook.chap6.ejbapp.CourseLocalHome</local-home>
<local>com.jdevbook.chap6.ejbapp.CourseLocal</local>
<ejb-link>Course</ejb-link>
</ejb-local-ref>
<ejb-local-ref>
<ejb-ref-name>ejb/local/Student</ejb-ref-name>
<ejb-ref-type>Entity</ejb-ref-type>
<local-home>com.jdevbook.chap6.ejbapp.StudentLocalHome</local-home>
<local>com.jdevbook.chap6.ejbapp.StudentLocal</local>
<ejb-link>Student</ejb-link>
</ejb-local-ref>
</session>
<entity>
<description>Entity Bean ( CMP )</description>
<display-name>Course</display-name>
<ejb-name>Course</ejb-name>
<local-home>com.jdevbook.chap6.ejbapp.CourseLocalHome</local-home>
<local>com.jdevbook.chap6.ejbapp.CourseLocal</local>
<ejb-class>com.jdevbook.chap6.ejbapp.CourseBean</ejb-class>
<persistence-type>Container</persistence-type>
<prim-key-class>java.lang.Long</prim-key-class>
<reentrant>False</reentrant>
<cmp-version>2.x</cmp-version>
<abstract-schema-name>Course</abstract-schema-name>
<cmp-field>
<field-name>courseId</field-name>
</cmp-field>
<cmp-field>
<field-name>courseName</field-name>
</cmp-field>
<primkey-field>courseId</primkey-field>
<query>
<query-method>
<method-name>findAll</method-name>
<method-params/>
</query-method>
<ejb-ql>select object(o) from Course o</ejb-ql>
</query>
</entity>
<entity>
<description>Entity Bean ( CMP )</description>
<display-name>Student</display-name>
<ejb-name>Student</ejb-name>
<local-home>com.jdevbook.chap6.ejbapp.StudentLocalHome</local-home>
<local>com.jdevbook.chap6.ejbapp.StudentLocal</local>
<ejb-class>com.jdevbook.chap6.ejbapp.StudentBean</ejb-class>
<persistence-type>Container</persistence-type>
<prim-key-class>java.lang.Long</prim-key-class>
<reentrant>False</reentrant>
<cmp-version>2.x</cmp-version>
<abstract-schema-name>Student</abstract-schema-name>
<cmp-field>
<field-name>studentId</field-name>
</cmp-field>
<cmp-field>
<field-name>studentName</field-name>
</cmp-field>
<primkey-field>studentId</primkey-field>
<query>
<query-method>
<method-name>findAll</method-name>
<method-params/>
</query-method>
<ejb-ql>select object(o) from Student o</ejb-ql>
</query>
</entity>
</enterprise-beans>
<relationships>
<ejb-relation>
<ejb-relation-name>Student - Course</ejb-relation-name>
<ejb-relationship-role>
<ejb-relationship-role-name>Student may have one Course</ejb-relationship-role-name>
<multiplicity>Many</multiplicity>
<relationship-role-source>
<ejb-name>Student</ejb-name>
</relationship-role-source>
<cmr-field>
<cmr-field-name>course_courseId</cmr-field-name>
</cmr-field>
</ejb-relationship-role>
<ejb-relationship-role>
<ejb-relationship-role-name>Course may have many Student</ejb-relationship-role-name>
<multiplicity>One</multiplicity>
<relationship-role-source>
<ejb-name>Course</ejb-name>
</relationship-role-source>
<cmr-field>
<cmr-field-name>student_courseId</cmr-field-name>
<cmr-field-type>java.util.Collection</cmr-field-type>
</cmr-field>
</ejb-relationship-role>
</ejb-relation>
</relationships>
<assembly-descriptor>
<container-transaction>
<method>
<ejb-name>Course</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>Supports</trans-attribute>
</container-transaction>
<container-transaction>
<method>
<ejb-name>Student</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>Supports</trans-attribute>
</container-transaction>
<container-transaction>
<method>
<ejb-name>StudentCourseEJB</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>Required</trans-attribute>
</container-transaction>
</assembly-descriptor>
</ejb-jar>
jboss-cmp-jdbc.xml
<?xml version="1.0" encoding="UTF-8"?>
<jbosscmp-jdbc>
<defaults>
<datasource>jdbc/OracleDBConnDS</datasource>
<datasource-mapping>${jboss.mapping}</datasource-mapping>
</defaults>
<enterprise-beans>
<entity>
<ejb-name>Course</ejb-name>
<table-name>Courses</table-name>
<cmp-field>
<field-name>courseId</field-name>
<column-name>open1</column-name>
<jdbc-type>NUMERIC</jdbc-type>
<sql-type>NUMERIC(14,2)</sql-type>
</cmp-field>
<cmp-field>
<field-name>courseName</field-name>
<jdbc-type>VARCHAR</jdbc-type>
<sql-type>VARCHAR(250)</sql-type>
</cmp-field>
</entity>
<entity>
<ejb-name>Student</ejb-name>
<table-name>Student</table-name>
<cmp-field>
<field-name>studentId</field-name>
<column-name>open1</column-name>
<jdbc-type>NUMERIC</jdbc-type>
<sql-type>NUMERIC(14,2)</sql-type>
</cmp-field>
<cmp-field>
<field-name>studentName</field-name>
<jdbc-type>VARCHAR</jdbc-type>
<sql-type>VARCHAR(250)</sql-type>
</cmp-field>
<!-- cmp-field>
<field-name>account_accountid</field-name>
<jdbc-type>INTEGER</jdbc-type>
<sql-type>INTEGER(4)</sql-type>
</cmp-field>
<cmp-field>
<field-name>quote_symbol</field-name>
<jdbc-type>VARCHAR</jdbc-type>
<sql-type>VARCHAR(250)</sql-type>
</cmp-field>
<cmp-field>
<field-name>holding_holdingid</field-name>
<jdbc-type>INTEGER</jdbc-type>
<sql-type>INTEGER(4)</sql-type>
</cmp-field> -->
</entity>
</enterprise-beans>
<relationships>
<ejb-relation>
<ejb-relation-name>Student - Course</ejb-relation-name>
<foreign-key-mapping/>
<ejb-relationship-role>
<ejb-relationship-role-name>Student may have one Course</ejb-relationship-role-name>
<key-fields>
<key-field>
<field-name>id</field-name>
<column-name>CourseID</column-name>
</key-field>
</key-fields>
</ejb-relationship-role>
<ejb-relationship-role>
<ejb-relationship-role-name>Course</ejb-relationship-role-name>
<key-fields></key-fields>
</ejb-relationship-role>
</ejb-relation>
</relationships>
</jbosscmp-jdbc>
EJB
public interface CourseLocalHome extends EJBLocalHome
{
CourseLocal create() throws CreateException;
CourseLocal findByPrimaryKey(Long primaryKey) throws FinderException;
Collection findAll() throws FinderException;
CourseLocal create(Long courseId) throws CreateException;
}
sun-ejb-jar
ejb-jar.xml
<?xml version = '1.0' encoding = 'windows-1252'?>
<ejb-jar>
<enterprise-beans>
<session>
<description>Session Bean ( Stateless )</description>
<display-name>StudentCourseEJB</display-name>
<ejb-name>StudentCourseEJB</ejb-name>
<home>com.jdevbook.chap6.ejbapp.StudentCourseEJBHome</home>
<remote>com.jdevbook.chap6.ejbapp.StudentCourseEJB</remote>
<ejb-class>com.jdevbook.chap6.ejbapp.StudentCourseEJBBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Container</transaction-type>
<ejb-local-ref>
<ejb-ref-name>ejb/local/Course</ejb-ref-name>
<ejb-ref-type>Entity</ejb-ref-type>
<local-home>com.jdevbook.chap6.ejbapp.CourseLocalHome</local-home>
<local>com.jdevbook.chap6.ejbapp.CourseLocal</local>
<ejb-link>Course</ejb-link>
</ejb-local-ref>
<ejb-local-ref>
<ejb-ref-name>ejb/local/Student</ejb-ref-name>
<ejb-ref-type>Entity</ejb-ref-type>
<local-home>com.jdevbook.chap6.ejbapp.StudentLocalHome</local-home>
<local>com.jdevbook.chap6.ejbapp.StudentLocal</local>
<ejb-link>Student</ejb-link>
</ejb-local-ref>
</session>
<entity>
<description>Entity Bean ( CMP )</description>
<display-name>Course</display-name>
<ejb-name>Course</ejb-name>
<local-home>com.jdevbook.chap6.ejbapp.CourseLocalHome</local-home>
<local>com.jdevbook.chap6.ejbapp.CourseLocal</local>
<ejb-class>com.jdevbook.chap6.ejbapp.CourseBean</ejb-class>
<persistence-type>Container</persistence-type>
<prim-key-class>java.lang.Long</prim-key-class>
<reentrant>False</reentrant>
<cmp-version>2.x</cmp-version>
<abstract-schema-name>Course</abstract-schema-name>
<cmp-field>
<field-name>courseId</field-name>
</cmp-field>
<cmp-field>
<field-name>courseName</field-name>
</cmp-field>
<primkey-field>courseId</primkey-field>
<query>
<query-method>
<method-name>findAll</method-name>
<method-params/>
</query-method>
<ejb-ql>select object(o) from Course o</ejb-ql>
</query>
</entity>
<entity>
<description>Entity Bean ( CMP )</description>
<display-name>Student</display-name>
<ejb-name>Student</ejb-name>
<local-home>com.jdevbook.chap6.ejbapp.StudentLocalHome</local-home>
<local>com.jdevbook.chap6.ejbapp.StudentLocal</local>
<ejb-class>com.jdevbook.chap6.ejbapp.StudentBean</ejb-class>
<persistence-type>Container</persistence-type>
<prim-key-class>java.lang.Long</prim-key-class>
<reentrant>False</reentrant>
<cmp-version>2.x</cmp-version>
<abstract-schema-name>Student</abstract-schema-name>
<cmp-field>
<field-name>studentId</field-name>
</cmp-field>
<cmp-field>
<field-name>studentName</field-name>
</cmp-field>
<primkey-field>studentId</primkey-field>
<query>
<query-method>
<method-name>findAll</method-name>
<method-params/>
</query-method>
<ejb-ql>select object(o) from Student o</ejb-ql>
</query>
</entity>
</enterprise-beans>
<relationships>
<ejb-relation>
<ejb-relation-name>Student - Course</ejb-relation-name>
<ejb-relationship-role>
<ejb-relationship-role-name>Student may have one Course</ejb-relationship-role-name>
<multiplicity>Many</multiplicity>
<relationship-role-source>
<ejb-name>Student</ejb-name>
</relationship-role-source>
<cmr-field>
<cmr-field-name>course_courseId</cmr-field-name>
</cmr-field>
</ejb-relationship-role>
<ejb-relationship-role>
<ejb-relationship-role-name>Course may have many Student</ejb-relationship-role-name>
<multiplicity>One</multiplicity>
<relationship-role-source>
<ejb-name>Course</ejb-name>
</relationship-role-source>
<cmr-field>
<cmr-field-name>student_courseId</cmr-field-name>
<cmr-field-type>java.util.Collection</cmr-field-type>
</cmr-field>
</ejb-relationship-role>
</ejb-relation>
</relationships>
<assembly-descriptor>
<container-transaction>
<method>
<ejb-name>Course</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>Supports</trans-attribute>
</container-transaction>
<container-transaction>
<method>
<ejb-name>Student</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>Supports</trans-attribute>
</container-transaction>
<container-transaction>
<method>
<ejb-name>StudentCourseEJB</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>Required</trans-attribute>
</container-transaction>
</assembly-descriptor>
</ejb-jar>
sun-cmp-mappings.xml
<?xml version="1.0" encoding="UTF-8"?>
<sun-cmp-mappings>
<sun-cmp-mapping>
<entity-mapping>
<ejb-name>Student</ejb-name>
<table-name>Student</table-name>
<cmp-field-mapping>
<field-name>studentId</field-name>
<column-name>STUDENT_ID</column-name>
<fetched-with>
<default/>
</fetched-with>
</cmp-field-mapping>
<cmp-field-mapping>
<field-name>studentName</field-name>
<column-name>STUDENT_NAME</column-name>
<fetched-with>
<default/>
</fetched-with>
</cmp-field-mapping>
</entity-mapping>
<entity-mapping>
<ejb-name>Course</ejb-name>
<table-name>Courses</table-name>
<cmp-field-mapping>
<field-name>courseId</field-name>
<column-name>COURSE_ID</column-name>
<fetched-with>
<default/>
</fetched-with>
</cmp-field-mapping>
<cmp-field-mapping>
<field-name>courseName</field-name>
<column-name>COURSE_NAME</column-name>
<fetched-with>
<default/>
</fetched-with>
</cmp-field-mapping>
</entity-mapping>
</sun-cmp-mapping>
</sun-cmp-mappings>
EJB
public interface CourseLocalHome extends EJBLocalHome
{
CourseLocal create() throws CreateException;
CourseLocal findByPrimaryKey(Long primaryKey) throws FinderException;
Collection findAll() throws FinderException;
CourseLocal create(Long courseId) throws CreateException;
}
open-ejb-jar
ejb-jar.xml
<?xml version = '1.0' encoding = 'windows-1252'?>
<ejb-jar>
<enterprise-beans>
<session>
<description>Session Bean ( Stateless )</description>
<display-name>StudentCourseEJB</display-name>
<ejb-name>StudentCourseEJB</ejb-name>
<home>com.jdevbook.chap6.ejbapp.StudentCourseEJBHome</home>
<remote>com.jdevbook.chap6.ejbapp.StudentCourseEJB</remote>
<ejb-class>com.jdevbook.chap6.ejbapp.StudentCourseEJBBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Container</transaction-type>
<ejb-local-ref>
<ejb-ref-name>ejb/local/Course</ejb-ref-name>
<ejb-ref-type>Entity</ejb-ref-type>
<local-home>com.jdevbook.chap6.ejbapp.CourseLocalHome</local-home>
<local>com.jdevbook.chap6.ejbapp.CourseLocal</local>
<ejb-link>Course</ejb-link>
</ejb-local-ref>
<ejb-local-ref>
<ejb-ref-name>ejb/local/Student</ejb-ref-name>
<ejb-ref-type>Entity</ejb-ref-type>
<local-home>com.jdevbook.chap6.ejbapp.StudentLocalHome</local-home>
<local>com.jdevbook.chap6.ejbapp.StudentLocal</local>
<ejb-link>Student</ejb-link>
</ejb-local-ref>
</session>
<entity>
<description>Entity Bean ( CMP )</description>
<display-name>Course</display-name>
<ejb-name>Course</ejb-name>
<local-home>com.jdevbook.chap6.ejbapp.CourseLocalHome</local-home>
<local>com.jdevbook.chap6.ejbapp.CourseLocal</local>
<ejb-class>com.jdevbook.chap6.ejbapp.CourseBean</ejb-class>
<persistence-type>Container</persistence-type>
<prim-key-class>java.lang.Long</prim-key-class>
<reentrant>False</reentrant>
<cmp-version>2.x</cmp-version>
<abstract-schema-name>Course</abstract-schema-name>
<cmp-field>
<field-name>courseId</field-name>
</cmp-field>
<cmp-field>
<field-name>courseName</field-name>
</cmp-field>
<primkey-field>courseId</primkey-field>
<query>
<query-method>
<method-name>findAll</method-name>
<method-params/>
</query-method>
<ejb-ql>select object(o) from Course o</ejb-ql>
</query>
</entity>
<entity>
<description>Entity Bean ( CMP )</description>
<display-name>Student</display-name>
<ejb-name>Student</ejb-name>
<local-home>com.jdevbook.chap6.ejbapp.StudentLocalHome</local-home>
<local>com.jdevbook.chap6.ejbapp.StudentLocal</local>
<ejb-class>com.jdevbook.chap6.ejbapp.StudentBean</ejb-class>
<persistence-type>Container</persistence-type>
<prim-key-class>java.lang.Long</prim-key-class>
<reentrant>False</reentrant>
<cmp-version>2.x</cmp-version>
<abstract-schema-name>Student</abstract-schema-name>
<cmp-field>
<field-name>studentId</field-name>
</cmp-field>
<cmp-field>
<field-name>studentName</field-name>
</cmp-field>
<primkey-field>studentId</primkey-field>
<query>
<query-method>
<method-name>findAll</method-name>
<method-params/>
</query-method>
<ejb-ql>select object(o) from Student o</ejb-ql>
</query>
</entity>
</enterprise-beans>
<relationships>
<ejb-relation>
<ejb-relation-name>Student - Course</ejb-relation-name>
<ejb-relationship-role>
<ejb-relationship-role-name>Student may have one Course</ejb-relationship-role-name>
<multiplicity>Many</multiplicity>
<relationship-role-source>
<ejb-name>Student</ejb-name>
</relationship-role-source>
<cmr-field>
<cmr-field-name>course_courseId</cmr-field-name>
</cmr-field>
</ejb-relationship-role>
<ejb-relationship-role>
<ejb-relationship-role-name>Course may have many Student</ejb-relationship-role-name>
<multiplicity>One</multiplicity>
<relationship-role-source>
<ejb-name>Course</ejb-name>
</relationship-role-source>
<cmr-field>
<cmr-field-name>student_courseId</cmr-field-name>
<cmr-field-type>java.util.Collection</cmr-field-type>
</cmr-field>
</ejb-relationship-role>
</ejb-relation>
</relationships>
<assembly-descriptor>
<container-transaction>
<method>
<ejb-name>Course</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>Supports</trans-attribute>
</container-transaction>
<container-transaction>
<method>
<ejb-name>Student</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>Supports</trans-attribute>
</container-transaction>
<container-transaction>
<method>
<ejb-name>StudentCourseEJB</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>Required</trans-attribute>
</container-transaction>
</assembly-descriptor>
</ejb-jar>
openejb-jar.xml
<?xml version="1.0" encoding="UTF-8"?>
<openejb-jar xmlns="http://www.openejb.org/xml/ns/openejb-jar-2.1">
<dep:environment xmlns:dep="http://geronimo.apache.org/xml/ns/deployment-1.1">
<dep:moduleId>
<dep:groupId>default</dep:groupId>
<dep:artifactId>StudentCourseEJB</dep:artifactId>
<dep:version>1.0</dep:version>
<dep:type>car</dep:type>
</dep:moduleId>
</dep:environment>
<cmp-connection-factory>
<resource-link>StudentCourse</resource-link>
</cmp-connection-factory>
<enterprise-beans>
<session>
<ejb-name>StudentCourseEJB</ejb-name>
<jndi-name>StudentCourseEJB</jndi-name>
<ejb-ref>
<ref-name>ejb/Student</ref-name>
<ejb-link>Student</ejb-link>
</ejb-ref>
<ejb-ref>
<ref-name>ejb/Course</ref-name>
<ejb-link>Course</ejb-link>
</ejb-ref>
</session>
<entity>
<ejb-name>Course</ejb-name>
<local-jndi-name>Course</local-jndi-name>
<table-name>Courses</table-name>
<cmp-field-mapping>
<cmp-field-name>courseId</cmp-field-name>
<table-column>COURSE_ID</table-column>
</cmp-field-mapping>
<cmp-field-mapping>
<cmp-field-name>courseName</cmp-field-name>
<table-column>COURSE_NAME</table-column>
</cmp-field-mapping>
<resource-ref>
<ref-name>jdbc/StudentCourse</ref-name>
<resource-link>StudentCourse</resource-link>
</resource-ref>
</entity>
<entity>
<ejb-name>Student</ejb-name>
<local-jndi-name>Student</local-jndi-name>
<table-name>Student</table-name>
<cmp-field-mapping>
<cmp-field-name>studentId</cmp-field-name>
<table-column>STUDENT_ID</table-column>
</cmp-field-mapping>
<cmp-field-mapping>
<cmp-field-name>studentName</cmp-field-name>
<table-column>STUDENT_NAME</table-column>
</cmp-field-mapping>
<resource-ref>
<ref-name>jdbc/StudentCourse</ref-name>
<resource-link>StudentCourse</resource-link>
</resource-ref>
</entity>
</enterprise-beans>
<relationships>
<ejb-relation>
<ejb-relation-name>Student - Course</ejb-relation-name>
<ejb-relationship-role>
<ejb-relationship-role-name>Student may have one Course</ejb-relationship-role-name>
<relationship-role-source>
<ejb-name>Student</ejb-name>
</relationship-role-source>
<cmr-field>
<cmr-field-name>course_courseId</cmr-field-name>
</cmr-field>
<foreign-key-column-on-source/>
<role-mapping>
<cmr-field-mapping>
<key-column>COURSE_ID</key-column>
<foreign-key-column>COURSE_ID_FK</foreign-key-column>
</cmr-field-mapping>
</role-mapping>
</ejb-relationship-role>
</ejb-relation>
</relationships>
</openejb-jar>
EJB
public interface CourseLocalHome extends EJBLocalHome
{
CourseLocal create() throws CreateException;
CourseLocal findByPrimaryKey(Long primaryKey) throws FinderException;
Collection findAll() throws FinderException;
CourseLocal create(Long courseId) throws CreateException;
}
weblogic-ejb-jar
ejb-jar.xml
<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar>
<enterprise-beans>
<session>
<description>![CDATA[Gestionnaire du compteur d'ID]]</description>
<ejb-name>CounterGate</ejb-name>
<home>com.acme.aps.foundation.ejb.counter.CounterGateHome</home>
<remote>com.acme.aps.foundation.ejb.counter.CounterGate</remote>
<ejb-class>com.acme.aps.foundation.ejb.counter.CounterGateBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Container</transaction-type>
<env-entry>
<env-entry-name>CounterHome</env-entry-name>
<env-entry-type>java.lang.String</env-entry-type>
<env-entry-value>CounterHome</env-entry-value>
</env-entry>
</session>
<session>
<description>![CDATA[Gestionnaire des preferences des utilisateurs]]</description>
<ejb-name>PreferenceGate</ejb-name>
<home>com.acme.aps.foundation.ejb.preferences.PreferenceGateHome</home>
<remote>com.acme.aps.foundation.ejb.preferences.PreferenceGate</remote>
<ejb-class>com.acme.aps.foundation.ejb.preferences.PreferenceGateBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Container</transaction-type>
<env-entry>
<env-entry-name>com.acme.aps.foundation.ejb.preferences.Preference</env-entry-name>
<env-entry-type>java.lang.String</env-entry-type>
<env-entry-value>PreferenceHome</env-entry-value>
</env-entry>
</session>
<entity>
<description>![CDATA[Gestion des champs dynamiques. Depuis la version G2R0C7 du generateur cette description n'est plus genere]]</description>
<ejb-name>DynamicField</ejb-name>
<local-home>com.acme.aps.foundation.ejb.dynamic.DynamicFieldEntityHome</local-home>
<local>com.acme.aps.foundation.ejb.dynamic.DynamicFieldEntity</local>
<ejb-class>com.acme.aps.foundation.ejb.dynamic.DynamicFieldEntityBean</ejb-class>
<persistence-type>Container</persistence-type>
<prim-key-class>com.acme.aps.foundation.ejb.BaseEntityBeanPK</prim-key-class>
<reentrant>False</reentrant>
<cmp-version>2.x</cmp-version>
<abstract-schema-name>DynamicField</abstract-schema-name>
<cmp-field>
<field-name>id</field-name>
</cmp-field>
<cmp-field>
<field-name>timestamp</field-name>
</cmp-field>
<cmp-field>
<field-name>entityId</field-name>
</cmp-field>
<cmp-field>
<field-name>label</field-name>
</cmp-field>
<cmp-field>
<field-name>type</field-name>
</cmp-field>
<cmp-field>
<field-name>value</field-name>
</cmp-field>
<query>
<query-method>
<method-name>findByEntityId</method-name>
<method-params>
<method-param>java.lang.String</method-param>
</method-params>
</query-method>
<ejb-ql>SELECT OBJECT(o) FROM DynamicField AS o WHERE o.entityId = ?1
</ejb-ql>
</query>
</entity>
<entity>
<description>![CDATA[Gestion des tables dynamiques. Depuis la version G2R0C7 du generateur cette description n'est plus genere]]</description>
<ejb-name>DynamicEntity</ejb-name>
<local-home>com.acme.aps.foundation.ejb.dynamic.DynamicEntityHome</local-home>
<local>com.acme.aps.foundation.ejb.dynamic.DynamicEntity</local>
<ejb-class>com.acme.aps.foundation.ejb.dynamic.DynamicEntityBean</ejb-class>
<persistence-type>Bean</persistence-type>
<prim-key-class>com.acme.aps.foundation.ejb.BaseEntityBeanPK</prim-key-class>
<reentrant>False</reentrant>
<env-entry>
<env-entry-name>JndiFieldHomeName</env-entry-name>
<env-entry-type>java.lang.String</env-entry-type>
<env-entry-value>DynamicFieldHome</env-entry-value>
</env-entry>
</entity>
<entity>
<description>![CDATA[Memorise les compteurs des ID]]</description>
<ejb-name>Counter</ejb-name>
<local-home>com.acme.aps.foundation.ejb.counter.CounterHome</local-home>
<local>com.acme.aps.foundation.ejb.counter.Counter</local>
<ejb-class>com.acme.aps.foundation.ejb.counter.CounterBean</ejb-class>
<persistence-type>Container</persistence-type>
<prim-key-class>com.acme.aps.foundation.ejb.counter.CounterPK</prim-key-class>
<reentrant>False</reentrant>
<cmp-version>2.x</cmp-version>
<abstract-schema-name>Counter</abstract-schema-name>
<cmp-field>
<field-name>name</field-name>
</cmp-field>
<cmp-field>
<field-name>count</field-name>
</cmp-field>
</entity>
<entity>
<description>![CDATA[Memorise les preferences des utilisateurs]]</description>
<ejb-name>Preference</ejb-name>
<local-home>com.acme.aps.foundation.ejb.preferences.PreferenceHome</local-home>
<local>com.acme.aps.foundation.ejb.preferences.Preference</local>
<ejb-class>com.acme.aps.foundation.ejb.preferences.PreferenceBean</ejb-class>
<persistence-type>Container</persistence-type>
<prim-key-class>com.acme.aps.foundation.ejb.BaseEntityBeanPK</prim-key-class>
<reentrant>False</reentrant>
<cmp-version>2.x</cmp-version>
<abstract-schema-name>Preference</abstract-schema-name>
<cmp-field>
<field-name>id</field-name>
</cmp-field>
<cmp-field>
<field-name>timestamp</field-name>
</cmp-field>
<cmp-field>
<field-name>owner</field-name>
</cmp-field>
<cmp-field>
<field-name>domain</field-name>
</cmp-field>
<cmp-field>
<field-name>key</field-name>
</cmp-field>
<cmp-field>
<field-name>content</field-name>
</cmp-field>
<query>
<query-method>
<method-name>findByDomainAndOwner</method-name>
<method-params>
<method-param>java.lang.String</method-param>
<method-param>java.lang.String</method-param>
</method-params>
</query-method>
<ejb-ql>SELECT OBJECT(o) FROM Preference AS o WHERE o.domain = ?1 AND o.owner = ?2
</ejb-ql>
</query>
</entity>
</enterprise-beans>
<assembly-descriptor>
<container-transaction>
<method>
<ejb-name>DynamicField</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>Required</trans-attribute>
</container-transaction>
<container-transaction>
<method>
<ejb-name>DynamicEntity</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>Required</trans-attribute>
</container-transaction>
<container-transaction>
<method>
<ejb-name>CounterGate</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>RequiresNew</trans-attribute>
</container-transaction>
<container-transaction>
<method>
<ejb-name>PreferenceGate</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>Required</trans-attribute>
</container-transaction>
<container-transaction>
<method>
<ejb-name>Counter</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>Required</trans-attribute>
</container-transaction>
<container-transaction>
<method>
<ejb-name>Preference</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>Required</trans-attribute>
</container-transaction>
</assembly-descriptor>
</ejb-jar>
weblogic-rdbms-jar.xml
<?xml version="1.0" encoding="UTF-8"?>
<weblogic-rdbms-jar xmlns="http://www.bea.com/ns/weblogic/90"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.bea.com/ns/weblogic/90 http://www.bea.com/ns/weblogic/90/weblogic-rdbms20-persistence.xsd">
<weblogic-rdbms-bean>
<ejb-name>Counter</ejb-name>
<data-source-jndi-name>apsDS</data-source-jndi-name>
<table-map>
<table-name>F_counter</table-name>
<field-map>
<cmp-field>name</cmp-field>
<dbms-column>F_name</dbms-column>
</field-map>
<field-map>
<cmp-field>count</cmp-field>
<dbms-column>F_count</dbms-column>
</field-map>
</table-map>
</weblogic-rdbms-bean>
<weblogic-rdbms-bean>
<ejb-name>Preference</ejb-name>
<data-source-jndi-name>apsDS</data-source-jndi-name>
<table-map>
<table-name>F_preference</table-name>
<field-map>
<cmp-field>timestamp</cmp-field>
<dbms-column>F_timestamp</dbms-column>
</field-map>
<field-map>
<cmp-field>owner</cmp-field>
<dbms-column>F_owner</dbms-column>
</field-map>
<field-map>
<cmp-field>domain</cmp-field>
<dbms-column>F_domain</dbms-column>
</field-map>
<field-map>
<cmp-field>key</cmp-field>
<dbms-column>F_key</dbms-column>
</field-map>
<field-map>
<cmp-field>content</cmp-field>
<dbms-column>F_content</dbms-column>
</field-map>
<field-map>
<cmp-field>id</cmp-field>
<dbms-column>F_id</dbms-column>
</field-map>
</table-map>
</weblogic-rdbms-bean>
<weblogic-rdbms-bean>
<ejb-name>DynamicField</ejb-name>
<data-source-jndi-name>apsDS</data-source-jndi-name>
<table-map>
<table-name>F_dynamic</table-name>
<field-map>
<cmp-field>id</cmp-field>
<dbms-column>F_id</dbms-column>
</field-map>
<field-map>
<cmp-field>timestamp</cmp-field>
<dbms-column>F_timestamp</dbms-column>
</field-map>
<field-map>
<cmp-field>entityId</cmp-field>
<dbms-column>F_entityId</dbms-column>
</field-map>
<field-map>
<cmp-field>label</cmp-field>
<dbms-column>F_label</dbms-column>
</field-map>
<field-map>
<cmp-field>type</cmp-field>
<dbms-column>F_type</dbms-column>
</field-map>
<field-map>
<cmp-field>value</cmp-field>
<dbms-column>F_value</dbms-column>
</field-map>
</table-map>
</weblogic-rdbms-bean>
</weblogic-rdbms-jar>
EJB
public interface PreferenceHome
extends EJBLocalHome
{
public Preference create(String a_id, java.util.HashMap a_values)
throws CreateException;
public Preference findByPrimaryKey(BaseEntityBeanPK primaryKey)
throws FinderException;
public java.util.Collection findByDomainAndOwner(
String a_domain,
String a_owner)
throws FinderException;
}
ibm-ejb-jar
ejb-jar.xml
<ejb-jar id="ejb-jar_ID">
<enterprise-beans>
<entity id="ContainerManagedEntity_1">
<ejb-name>PersonEJB</ejb-name>
<home>com.ibm.demo.ejbs.PersonHome</home>
<remote>com.ibm.demo.ejbs.Person</remote>
<local-home>com.ibm.demo.ejbs.PersonLocalHome</local-home>
<ejb-class>com.ibm.demo.ejbs.PersonBean</ejb-class>
<persistence-type>Container</persistence-type>
<prim-key-class>java.lang.Integer</prim-key-class>
<reentrant>False</reentrant>
<cmp-field id="CMPAttribute_1">
<field-name>id</field-name>
</cmp-field>
<cmp-field id="CMPAttribute_2">
<field-name>name</field-name>
</cmp-field>
<cmp-field id="CMPAttribute_3">
<field-name>age</field-name>
</cmp-field>
<cmp-field id="CMPAttribute_4">
<field-name>educationLevel</field-name>
</cmp-field>
<primkey-field>id</primkey-field>
<query>
<query-method>
<method-name>findAll</method-name>
<method-params/>
</query-method>
<ejb-ql>select * from PersonEJB</ejb-ql>
</query>
</entity>
</enterprise-beans>
<assembly-descriptor>
<security-role>
<description>Everyone can gain access to this EJB.</description>
<role-name>everyone</role-name>
</security-role>
<method-permission>
<role-name>everyone</role-name>
<method>
<ejb-name>PersonEJB</ejb-name>
<method-name>*</method-name>
</method>
</method-permission>
<container-transaction>
<method>
<ejb-name>PersonEJB</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>Required</trans-attribute>
</container-transaction>
</assembly-descriptor>
</ejb-jar>
Map.mapxmi
<?xml version="1.0" encoding="UTF-8"?>
<ejbrdbmapping:EjbRdbDocumentRoot
xmlns:ejbrdbmapping="ejbrdbmapping.xmi"
xmlns:Mapping="Mapping.xmi"
xmlns:RDBSchema="RDBSchema.xmi"
xmlns:ejb="ejb.xmi"
xmlns:xmi="http://www.omg.org/XMI"
xmi:version="2.0"
xmi:id="EjbRdbDocumentRoot_1"
outputReadOnly="false"
topToBottom="true"
>
<helper xmi:type="ejbrdbmapping:RdbSchemaProperies" xmi:id="RdbSchemaProperies_1" primitivesDocument="DB2UDBNT_V71">
<vendorConfiguration href="RdbVendorConfigurations.xmi#DB2UDBNT_V71_Config" />
</helper>
<inputs xmi:type="ejb:EJBJar" href="META-INF/ejb-jar.xml#ejb-jar_ID" />
<outputs xmi:type="RDBSchema:RDBDatabase" href="META-INF/Schema/Schema.dbxmi#RDBDatabase_1" />
<nested xmi:type="ejbrdbmapping:RDBEjbMapper" xmi:id="RDBEjbMapper_1">
<helper xmi:type="ejbrdbmapping:PrimaryTableStrategy" xmi:id="PrimaryTableStrategy_1">
<table href="META-INF/Schema/Schema.dbxmi#RDBTable_1" />
</helper>
<inputs xmi:type="ejb:ContainerManagedEntity" href="META-INF/ejb-jar.xml#ContainerManagedEntity_1" />
<outputs xmi:type="RDBSchema:RDBTable" href="META-INF/Schema/Schema.dbxmi#RDBTable_1" />
<nested xmi:id="PersonEJB_id---PERSONEJB_ID">
<inputs xmi:type="ejb:CMPAttribute" href="META-INF/ejb-jar.xml#CMPAttribute_1" />
<outputs xmi:type="RDBSchema:RDBColumn" href="META-INF/Schema/Schema.dbxmi#RDBColumn_1" />
<typeMapping href="JavatoDB2UDBNT_V71TypeMaps.xmi#Integer-INTEGER" />
</nested>
<nested xmi:id="PersonEJB_name---PERSONEJB_NAME">
<inputs xmi:type="ejb:CMPAttribute" href="META-INF/ejb-jar.xml#CMPAttribute_2" />
<outputs xmi:type="RDBSchema:RDBColumn" href="META-INF/Schema/Schema.dbxmi#RDBColumn_2" />
<typeMapping href="JavatoDB2UDBNT_V71TypeMaps.xmi#String-VARCHAR" />
</nested>
<nested xmi:id="PersonEJB_age---PERSONEJB_AGE">
<inputs xmi:type="ejb:CMPAttribute" href="META-INF/ejb-jar.xml#CMPAttribute_3" />
<outputs xmi:type="RDBSchema:RDBColumn" href="META-INF/Schema/Schema.dbxmi#RDBColumn_3" />
<typeMapping href="JavatoDB2UDBNT_V71TypeMaps.xmi#int-INTEGER" />
</nested>
<nested xmi:id="PersonEJB_educationLevel---PERSONEJB_EDUCATIONLEVEL">
<inputs xmi:type="ejb:CMPAttribute" href="META-INF/ejb-jar.xml#CMPAttribute_4" />
<outputs xmi:type="RDBSchema:RDBColumn" href="META-INF/Schema/Schema.dbxmi#RDBColumn_4" />
<typeMapping href="JavatoDB2UDBNT_V71TypeMaps.xmi#int-INTEGER" />
</nested>
</nested>
<typeMapping xmi:type="Mapping:MappingRoot" href="JavatoDB2UDBNT_V71TypeMaps.xmi#Java_to_DB2UDBNT_V71_TypeMaps" />
</ejbrdbmapping:EjbRdbDocumentRoot>
Schema.dbxmi
<?xml version="1.0" encoding="UTF-8"?>
<xmi:XMI xmlns:xmi="http://www.omg.org/XMI" xmlns:RDBSchema="RDBSchema.xmi" xmi:version="2.0">
<RDBSchema:RDBDatabase xmi:id="RDBDatabase_1" name="TopDownDB" tableGroup="RDBTable_1">
<dataTypeSet href="UDBV7_Primitives.xmi#SQLPrimitives_1" />
</RDBSchema:RDBDatabase>
<RDBSchema:RDBTable xmi:id="RDBTable_1" name="PERSON" primaryKey="SQLReference_1" database="RDBDatabase_1">
<columns xmi:id="RDBColumn_1" name="ID" allowNull="false" group="SQLReference_1">
<type xmi:type="RDBSchema:SQLExactNumeric" xmi:id="SQLExactNumeric_1">
<originatingType xmi:type="RDBSchema:SQLExactNumeric" href="UDBV7_Primitives.xmi#SQLExactNumeric_1" />
</type>
</columns>
<columns xmi:id="RDBColumn_2" name="NAME">
<type xmi:type="RDBSchema:SQLCharacterStringType" xmi:id="SQLCharacterStringType_1" length="250">
<originatingType xmi:type="RDBSchema:SQLCharacterStringType" href="JavatoDB2UDBNT_V71TypeMaps.xmi#SQLCharacterStringType_250" />
</type>
</columns>
<columns xmi:id="RDBColumn_3" name="AGE">
<type xmi:type="RDBSchema:SQLExactNumeric" xmi:id="SQLExactNumeric_2">
<originatingType xmi:type="RDBSchema:SQLExactNumeric" href="UDBV7_Primitives.xmi#SQLExactNumeric_1" />
</type>
</columns>
<columns xmi:id="RDBColumn_4" name="EDUCATIONLEVEL">
<type xmi:type="RDBSchema:SQLExactNumeric" xmi:id="SQLExactNumeric_3">
<originatingType xmi:type="RDBSchema:SQLExactNumeric" href="UDBV7_Primitives.xmi#SQLExactNumeric_1" />
</type>
</columns>
<namedGroup xmi:type="RDBSchema:SQLReference" xmi:id="SQLReference_1" name="PERSONEJBPK" members="RDBColumn_1" table="RDBTable_1" constraint="Constraint_PERSONEJBPK" />
<constraints xmi:id="Constraint_PERSONEJBPK" name="PERSONEJBPK" type="PRIMARYKEY" primaryKey="SQLReference_1" />
</RDBSchema:RDBTable>
</xmi:XMI>
EJB
public interface PersonLocalHome extends EJBLocalHome
{
PersonLocal create() throws CreateException;
PersonLocal findByPrimaryKey(Long primaryKey) throws FinderException;
Collection findAll() throws FinderException;
PersonLocal create(Long courseId) throws CreateException;
}
Spring APIs
Spring
@Entity
@Table(name = "role")
@NamedQueries({
@NamedQuery(
name = "findRoleByName",
query = "select r from Role r where r.name = :name "
)
})
public class Role extends BaseObject implements Serializable, GrantedAuthority {
private static final long serialVersionUID = 3690197650654049848L;
private Long id;
private String name;
private String description;
@Repository
public class RoleDaoHibernate extends GenericDaoHibernate<Role, Long> implements RoleDao {
/
* Constructor to create a Generics-based version using Role as the entity
*/
public RoleDaoHibernate() {
super(Role.class);
}
/
* {@inheritDoc}
*/
public Role getRoleByName(String rolename) {
List roles = getHibernateTemplate().find("from Role where name=?", rolename);
if (roles.isEmpty()) {
return null;
} else {
return (Role) roles.get(0);
}
}
public List<Role> getRoleList() {
List<Role> states = new ArrayList<Role>();
roles = (List<Role>) getHibernateTemplate().findByNamedQuery("findRoleByName");
return roles;
}
/
* {@inheritDoc}
*/
public void removeRole(String rolename) {
Object role = getRoleByName(rolename);
getHibernateTemplate().delete(role);
}
}
Hibernate 2.x APIs
Hibernate 2.x
package com.javatpoint.mypackage;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Session;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.Transaction;
import net.sf.hibernate.cfg.Configuration;
import net.sf.hibernate.Query;
import org.hibernate.query.Query;
import javax.persistence.EntityManager;
import org.hibernate.engine.spi.SessionImplementor;
public class StoreData {
public static void main(String[] args) {
StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build();
SessionFactory factory = meta.getSessionFactoryBuilder().build();
Session session = factory.openSession();
Transaction t = session.beginTransaction();
Employee e1=new Employee();
e1.setId(101);
e1.setFirstName("Gaurav");
e1.setLastName("Chawla");
session.save(e1);
t.commit();
System.out.println("successfully saved");
factory.close();
session.close();
}
Hibernate 6.x APIs
Hibernate 6.x
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import org.hibernate.query.sqm.internal.QuerySqmImpl;
public class SqlResultSetMappingUnitTest {
private static EntityManager em;
private static EntityManagerFactory emFactory;
@BeforeAll
public static void setup() {
emFactory = Persistence.createEntityManagerFactory("java-jpa-scheduled-day");
em = emFactory.createEntityManager();
}
public void whenNamedQuery_thenMultipleEntityResult() {
final QuerySqmImpl query = em.createNativeQuery("SELECT e.id, e.name, d.id, d.employeeId, d.dayOfWeek "
+ " FROM employee e, schedule_days d "
+ " WHERE e.id = d.employeeId", "EmployeeScheduleResults");
List<Object[]> results = query.list();
assertEquals(4, results.size());
assertTrue(results.get(0).length == 2);
Employee emp = (Employee) results.get(1)[0];
ScheduledDay day = (ScheduledDay) results.get(1)[1];
assertTrue(day.getEmployeeId() == emp.getId());
}
}
EclipseLink APIs
EclipseLink Query
import org.eclipse.persistence.queries.ReadAllQuery;
import org.eclipse.persistence.internal.sessions.AbstractSession;
import org.eclipse.persistence.queries.DatabaseQuery;
import org.eclipse.persistence.queries.ValueReadQuery;
import org.eclipse.persistence.jpa.JpaHelper;
import org.eclipse.persistence.sessions.Session;
public class DBQueries {
JpaEntityManager jpaEntityManager;
Session session;
private void queryCount() {
Session session = jpaEntityManager.getActiveSession();
// JpaEntityManager jpaEntityManager = (JpaEntityManager) getEntityManager();
// Session session = jpaEntityManager.getActiveSession();
final ValueReadQuery countQry = new ValueReadQuery();
countQry.setSQLString( "select * from PCDN_STEP_EXECUTION" );
// Number result = session.executeQuery( countQry );
session.executeQuery( countQry );
// return result;
}
}
JPA SQL DML Annotations
SQLInsert
@Entity
@SQLInsert(sql = "UPDATE Person SET name = ? WHERE id = ? ")
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Long id;
String name;
}
@RestController
public class PersonController {
private Session session;
private DataSourceFactory dataSourceFactory;
private static EntityManagerFactory factory = null;
private static EntityManager entityManager = null;
@BeforeClass
public static void init() {
factory = Persistence.createEntityManagerFactory("jpa-db");
entityManager = factory.createEntityManager();
}
@Override
public boolean save(Person thePerson) {
try {
session = dataSourceFactory.getSessionFactory().openSession();
beginTransactionIfAllowed(session);
session.save(thePerson);
session.getTransaction().commit();
logging.setMessage("PersonDaoImpl -> person saved successfully : "+thePerson.getFirstName());
return true;
} catch (HibernateException e) {
session.getTransaction().rollback();
logging.setMessage("PersonDaoImpl -> save person error -> "+e.getLocalizedMessage());
return false;
} finally {
session.close();
}
}
}
SQLDelete
@Entity
@SQLDelete(sql = "INSERT INTO Person (name, id) VALUES (?, ?)", check = ResultCheckStyle.COUNT)
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Long id;
String name;
}
@RestController
public class PersonController {
private Session session;
private DataSourceFactory dataSourceFactory;
private static EntityManagerFactory factory = null;
private static EntityManager entityManager = null;
@BeforeClass
public static void init() {
factory = Persistence.createEntityManagerFactory("jpa-db");
entityManager = factory.createEntityManager();
}
@Override
public void deleteByName(String selectedCompanyName) {
try {
session = dataSourceFactory.getSessionFactory().openSession();
beginTransactionIfAllowed(session);
Query<Person> query = session.createQuery("delete from Person where title = :name", Person.class);
query.setParameter("name", name);
query.setMaxResults(1);
session.delete(query.getSingleResult());
session.getTransaction().commit();
logging.setMessage("PersonImpl -> deleting person...");
} catch (HibernateException ex) {
session.getTransaction().rollback();
logging.setMessage("PersonImpl Error -> "+ex.getLocalizedMessage());
} finally {
if(session.isOpen()){session.close();}
}
}
}
SQLUpdate
@SQLUpdate(sql = "{call FIND_PERSON_BY_NAME(?)}", callable = true)
@NamedStoredProcedureQueries({@NamedStoredProcedureQuery(name = "findByNameProcedure", procedureName = "FIND_PERSON_BY_NAME", resultClasses = { Person.class }, parameters = { @StoredProcedureParameter(name = "p_name", type = Integer.class, mode = ParameterMode.IN) }) })
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Long id;
String name;
}
@RestController
public class PersonController {
private Session session;
private DataSourceFactory dataSourceFactory;
private static EntityManagerFactory factory = null;
private static EntityManager entityManager = null;
@BeforeClass
public static void init() {
factory = Persistence.createEntityManagerFactory("jpa-db");
entityManager = factory.createEntityManager();
}
@Override
public void findPersonsByName() {
final StoredProcedureQuery storedProcedure = entityManager.createStoredProcedureQuery("FIND_PERSON_BY_NAME", Person.class);
storedProcedure.registerStoredProcedureParameter(1, Integer.class, ParameterMode.IN)
.setParameter(1, 2015);
storedProcedure.getResultList()
.forEach(c -> Assert.assertEquals(new Integer(2015), ((Car) c).getYear()));
}
}
JPA Lifecycle Annotations
PrePersist
@Entity
public class User {
private static Log log = LogFactory.getLog(User.class);
@PrePersist
public void logNewUserAttempt() {
log.info("Attempting to add new user with username: " + userName);
}
}
JPA ORM.XML
orm.xml
<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings
xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_2_0.xsd"
version="2.0">
<named-query name="Todo.findBySearchTermNamedOrmXml">
<query>SELECT t FROM Todo t WHERE LOWER(t.title) LIKE LOWER(CONCAT('%', :searchTerm, '%')) OR LOWER(t.description) LIKE LOWER(CONCAT('%', :searchTerm, '%')) ORDER BY t.title ASC</query>
</named-query>
<named-native-query name="Todo.findBySearchTermNamedNativeOrmXml"
result-class="net.petrikainulainen.springdata.jpa.todo.Todo">
<query>SELECT * FROM todos t WHERE LOWER(t.title) LIKE LOWER(CONCAT('%',:searchTerm, '%')) OR LOWER(t.description) LIKE LOWER(CONCAT('%',:searchTerm, '%')) ORDER BY t.title ASC</query>
</named-native-query>
</entity-mappings>
@Entity
@EntityListeners(AuditingEntityListener.class)
@Table(name = "todos")
final class Todo {
static final int MAX_LENGTH_DESCRIPTION = 500;
static final int MAX_LENGTH_TITLE = 100;
}
Dynamic Entity with hbm xml
hbm.xml File
<hibernate-mapping package="org.hibernate.test.onetoone.nopojo">
<class entity-name="Person" table="personDetails">
<id name="id" type="long">
<generator class="foreign">
<param name="property">address</param>
</generator>
</id>
<property name="name" type="string"/>
<one-to-one name="address" cascade="all" entity-name="Address" constrained="true"/>
</class>
</hibernate-mapping>
Hibernate CRUD
public void testOneToOneOnSubclass() {
Map person = new HashMap();
person.put( "name", "Steve" );
Map address = new HashMap();
address.put( "zip", "12345" );
address.put( "state", "TX" );
address.put( "street", "123 Main St" );
person.put( "address", address );
address.put( "owner", person );
Transaction transaction = null;
Session s = null;
s = HibernateUtil.getSessionFactory().openSession();
transaction = s.beginTransaction();
s.save( "Person", person );
transaction.commit();
s.close();
}
Unknown SQL Query
public Collection listAllByCritere(Object p_objetCritere)
{
Collection result = null;
try {
Session session = HibernateUtilLegacy.getSession();
Criteria crit =
session.createCriteria(p_objetCritere.getClass())
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
CpCommune rechercheCritere = (CpCommune)p_objetCritere;
if ( rechercheCritere.getCodCommune() != null ) {
crit = crit.add(Restrictions.eq("codCommune",rechercheCritere.getCodCommune()));
}
if ( rechercheCritere.getAuteur() != null ) {
crit =crit.add(Restrictions.eq("auteur",rechercheCritere.getAuteur()));
}
result = crit.list();
}
return result;
}
Unknown Entity CRUD
public void saveStudent(Student student){
Transaction transaction = null;
Session session = null;
try{
session = HibernateUtil.getSessionFactory().openSession();
transaction = session.beginTransaction();
session.save(studen);
transaction.commit();
}catch (Exception e){
try{
transaction.rollback();
}catch(RuntimeException re){
re.getMessage();
}
throw e;
}finally {
if(session != null){
session.close();
}
}
}
Unknown Entity JPQL
public List<Student> getStudents(){
try(Session session = HibernateUtil.getSessionFactory().openSession()){
Query qry = session.createQuery("from Studen");
return qry.list();
}
}
Quality Rules
The following quality rules related to the use of a Java persistence framework are calculated.
Rule id | Rule name |
---|---|
1045002 | Avoid Hibernate Entity with ‘select-before-update’ set to true if not associated to table that fires an UPDATE trigger. |
1045000 | Lazy fetching should be used for Hibernate collection |
1045006 | Never use an array to map Hibernate collection |
1045010 | Prefer using version number instead of timestamp for Hibernate Entity |
1045004 | Avoid UPDATE trigger firing when not necessary |
1045008 | Avoid non serializable Entity beans |
1045012 | Avoid public/protected setter for the generated identifier field |
7722 | Avoid using persistent class’s identifier in equals() method |
7724 | Overriden equals() methods in persistent subclasses should only reference properties from the persistent base class |
7494 | Persistent class method’s equals() and hashCode() must access its fields through getter methods |
7504 | Persistent classes should Implement hashCode() and equals() |
7506 | equals() and hashCode() should be defined for Hibernate/JPA component |
Known Limitations
- Lifecycle annotation for only one class is supported when there are multiple values in EntityListener annotation.