Question

What would be the correct way writing JPA native queries with joins and with Eclipselink JPA2.0 entities?

Can some one tell me to execute the following SQL query using Eclipselink JPA native queries or JPQL?

SQL query is: Select e.EmployeeName,e.EmpId, d.DeptId from Employee e, Department d join e.DeptId on d.DeptId where e.DeptId=d.DeptId

JPA Entity bean code snippet

@Entity
@Table(name = "employee")

@JoinColumn(name = "DeptId", referencedColumnName = "DeptId")
@ManyToOne
    private Department DeptId;

@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Employee.findAll", query = "SELECT e FROM Employee e")})

    //more auto generated named queries using NetBeans

The JPA entity class "Employee" implements java.io.Serializable and the default constructor contains all mandatory fields.

What is the correct way to map jpa entity with My-SQL tables

Many to one relation: Employee.DeptId --> Department.DeptId Employee.RoleId --> JobRoles.RoleId

Employee.RoleId --> Skills.SkillId After succeeded with two tables I want to join three tables.

I was going thru the Ecipselink user-guide but could not get it. Would some one provide me code snippets or direct me to correct resource.

I have gone through EclipseLink JPA online guide:

http://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Querying http://wiki.eclipse.org/EclipseLink/UserGuide/JPA

I am using native query because Eclipse link JPA supports it and JPQL does not give complete portability. I wrote and developed a sample jsf-jpa application with jpa entities mapped to single table. With Netbeans IDE, it did not take much time generate and execute JPQL queries.

I want to use native queries and/or stored procedures execute JPA entities. It would be more productive if I could use my existing skills in SQL queries and stored procedures provided the JPA implementation does not give much issues with the same.

Update: Native SQL queries can be used according to Section 3.8.15 SQL Queries of JSR 317: [JavaTM Persistence API, Version 2.0][1] http://download.oracle.com/otndocs/jcp/persistence-2.0-fr-oth-JSpec/

The SQL query facility is intended to provide support for those cases where it is necessary to use the native SQL of the target database in use (and/or where the Java Persistence query language cannot be used). Native SQL queries are not expected to be portable across databases

Hence I believe it is nothing wrong to use native query, because portability is not required for me.

Was it helpful?

Solution

The native query executed successfully, The Section 3.8.15 of JSR 317 specification is helpful to understand the syntax, besides hit and trials with my code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top