Like statement: Wild Card Escape : EJB Query Language « JPA « Java Tutorial






File: Address.java

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Address {
    @Id
    private int id;
    private String street;
    private String city;
    private String state;
    private String zip;
    
    public int getId() {
        return id;
    }
    
    public void setId(int id) {
        this.id = id;
    }
    
    public String getStreet() {
        return street;
    }
    
    public void setStreet(String address) {
        this.street = address;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public String getZip() {
        return zip;
    }

    public void setZip(String zip) {
        this.zip = zip;
    }
    public String toString() {
        return "Address id: " + getId() + 
               ", street: " + getStreet() +
               ", city: " + getCity() +
               ", state: " + getState() +
               ", zip: " + getZip();
    }

}

File: Department.java

import java.util.HashSet;
import java.util.Set;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;

@Entity
public class Department {
    @Id
    private int id;
    private String name;
    @OneToMany(mappedBy="department")
    private Set<Student> students = new HashSet<Student>();

    public int getId() {
        return id;
    }
    
    public void setId(int deptNo) {
        this.id = deptNo;
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(String deptName) {
        this.name = deptName;
    }
    
    public Set<Student> getStudents() {
        return students;
    }

    public String toString() {
        return "Department no: " + getId() + 
               ", name: " + getName();
    }
}

File: Phone.java

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToOne;

@Entity
public class Phone {
    @Id
    private long id;
    private String number;
    private String type;
    @OneToOne Student student;
    
    public long getId() {
        return id;
    }
    
    public void setId(long id) {
        this.id = id;
    }
    
    public String getNumber() {
        return number;
    }
    
    public void setNumber(String phoneNo) {
        this.number = phoneNo;
    }
    
    public String getType() {
        return type;
    }
    
    public void setType(String phoneType) {
        this.type = phoneType;
    }
    
    public Student getStudent() {
        return student;
    }

    public void setStudent(Student student) {
        this.student = student;
    }

    public String toString() {
        return "Phone id: " + getId() + 
               ", no: " + getNumber() +
               ", type: " + getType();
    }
}

File: Project.java

import java.util.ArrayList;
import java.util.Collection;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.ManyToMany;

@Entity
public class Project {
    @Id
    protected int id;
    protected String name;
    @ManyToMany
    protected Collection<Student> students = new ArrayList<Student>();
    
    public int getId() {
        return id;
    }
    
    public void setId(int projectNo) {
        this.id = projectNo;
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(String projectName) {
        this.name = projectName;
    }
    
    public Collection<Student> getStudents() {
        return students;
    }
    
    public void addStudent(Student student) {
        if (!getStudents().contains(student)) {
            getStudents().add(student);
        }
        if (!student.getProjects().contains(this)) {
            student.getProjects().add(this);
        }
    }
    
    public String toString() {
        return getClass().getName().substring(getClass().getName().lastIndexOf('.')+1) + 
                " no: " + getId() + 
                ", name: " + getName();
    }
}

File: Student.java

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity
public class Student {
    @Id
    private int id;
    private String name;
    private long salary;
    @Temporal(TemporalType.DATE)
    private Date startDate;
    
    @OneToOne
    private Address address;
    
    @OneToMany(mappedBy="student")
    private Collection<Phone> phones = new ArrayList<Phone>();
    
    @ManyToOne
    private Department department;
    
    @ManyToOne
    private Student manager;
    
    @OneToMany(mappedBy="manager")
    private Collection<Student> directs = new ArrayList<Student>();
    
    @ManyToMany(mappedBy="students")
    private Collection<Project> projects = new ArrayList<Project>();

    public int getId() {
        return id;
    }
    
    public void setId(int empNo) {
        this.id = empNo;
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }

    public long getSalary() {
        return salary;
    }

    public void setSalary(long salary) {
        this.salary = salary;
    }

    public Date getStartDate() {
        return startDate;
    }

    public void setStartDate(Date startDate) {
        this.startDate = startDate;
    }
    
    public Collection<Phone> getPhones() {
        return phones;
    }
    
    public void addPhone(Phone phone) {
        if (!getPhones().contains(phone)) {
            getPhones().add(phone);
            if (phone.getStudent() != null) {
                phone.getStudent().getPhones().remove(phone);
            }
            phone.setStudent(this);
        }
    }
    
    public Department getDepartment() {
        return department;
    }
    
    public void setDepartment(Department department) {
        if (this.department != null) {
            this.department.getStudents().remove(this);
        }
        this.department = department;
        this.department.getStudents().add(this);
    }
    
    public Collection<Student> getDirects() {
        return directs;
    }
    
    public void addDirect(Student student) {
        if (!getDirects().contains(student)) {
            getDirects().add(student);
            if (student.getManager() != null) {
                student.getManager().getDirects().remove(student);
            }
            student.setManager(this);
        }
    }
    
    public Student getManager() {
        return manager;
    }
    
    public void setManager(Student manager) {
        this.manager = manager;
    }

    public Collection<Project> getProjects() {
        return projects;
    }
    
    public void addProject(Project project) {
        if (!getProjects().contains(project)) {
            getProjects().add(project);
        }
        if (!project.getStudents().contains(this)) {
            project.getStudents().add(this);
        }
    }
    
    public Address getAddress() {
        return address;
    }
    
    public void setAddress(Address address) {
        this.address = address; 
    }
    
    public String toString() {
        return "Student " + getId() + 
               ": name: " + getName() +
               ", salary: " + getSalary() +
               ", phones: " + getPhones() +
               ", managerNo: " + ((getManager() == null) ? null : getManager().getId()) +
               ", deptNo: " + ((getDepartment() == null) ? null : getDepartment().getId());
    }

}

File: Helper.java

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;

public class Helper {
  public static void checkData() throws Exception {
    Class.forName("org.hsqldb.jdbcDriver");
    Connection conn = DriverManager.getConnection("jdbc:hsqldb:data/tutorial", "sa", "");
    Statement st = conn.createStatement();

    ResultSet mrs = conn.getMetaData().getTables(null, null, null, new String[] { "TABLE" });
    while (mrs.next()) {
      String tableName = mrs.getString(3);
      System.out.println("\n\n\n\nTable Name: "+ tableName);

      ResultSet rs = st.executeQuery("select * from " + tableName);
      ResultSetMetaData metadata = rs.getMetaData();
      while (rs.next()) {
        System.out.println(" Row:");
        for (int i = 0; i < metadata.getColumnCount(); i++) {
          System.out.println("    Column Name: "+ metadata.getColumnLabel(i + 1)+ ",  ");
          System.out.println("    Column Type: "+ metadata.getColumnTypeName(i + 1)+ ":  ");
          Object value = rs.getObject(i + 1);
          System.out.println("    Column Value: "+value+"\n");
        }
      }
    }
  }
}

File: Main.java

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.FlushModeType;
import javax.persistence.Persistence;
import javax.persistence.Query;

public class Main {
  static EntityManagerFactory emf = Persistence.createEntityManagerFactory("JPAService");

  static EntityManager em = emf.createEntityManager();

  public static void main(String[] a) throws Exception {
    em.getTransaction().begin();

    Query query = em.createQuery("SELECT d FROM Department d WHERE d.name LIKE 'CHEM\\_%' ESCAPE '\\'");
    System.out.println(query.getResultList());

    em.getTransaction().commit();
    em.close();
    emf.close();

    Helper.checkData();
  }
}

File: persistence.xml

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence" version="1.0">
  <persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
    <properties>
      <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
      <property name="hibernate.hbm2ddl.auto" value="update"/>
      <property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
      <property name="hibernate.connection.username" value="sa"/>
      <property name="hibernate.connection.password" value=""/>
      <property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
    </properties>
  </persistence-unit>
</persistence>
  Download:  JPA-EJBQLWildCardEscape.zip( 5,295 k)








22.25.EJB Query Language
22.25.1.EJB QL Get Two Properties From Entity
22.25.2.EJB QL Get Single result
22.25.3.EJB QL Get Field From Entity
22.25.4.EJB QL Get Entity From Entity
22.25.5.EJB QL Get Distinct Entity
22.25.6.Query an Entity as Query a Table
22.25.7.Return List Of Entities From Query
22.25.8.Query Flush Mode
22.25.9.EJB SQL Count Function
22.25.10.Like statement: Wild Card Escape
22.25.11.Like statement and Wild Card
22.25.12.Where Clause With SubQuery
22.25.13.Use Between To check Salary Range
22.25.14.Two Aggregate Functions
22.25.15.Three Level Field Reference
22.25.16.Using SubQuery in EJB Query Langauge
22.25.17.Size function
22.25.18.Range Check With Comparison Operator
22.25.19.Query Field Of Field
22.25.20.EJB QL Pass Entity As Parameter
22.25.21.Query with Parameters
22.25.22.EJB QL Order By Two Fields
22.25.23.Query One To Many Collection
22.25.24.Order Descending
22.25.25.Use Object Function
22.25.26.Not In function
22.25.27.EJB Query Language: Not Exist
22.25.28.EJB QL Max With Date Type
22.25.29.EJB QL Left Join One To Many Map
22.25.30.EJB QL Join Two Entities
22.25.31.EJB QL Join Three Entities
22.25.32.EJB QL Join One To One Return Two Entities
22.25.33.EJB QL Join One To One
22.25.34.EJB QL Join One To Many Map
22.25.35.EJB QL Join One to Many Left Join Fetch
22.25.36.EJB QL Join Many To Many
22.25.37.EJB QL Join Entity And Its Field
22.25.38.EJB QL is Field empty
22.25.39.EJB QL In With Subquery
22.25.40.EJB QL In Function With One To Many
22.25.41.EJB QL In Function
22.25.42.EJB QL Having Clause
22.25.43.EJB QL Exist And Subquery
22.25.44.EJB QL Create new Object In Select Statement
22.25.45.EJB QL Count Entity
22.25.46.EJB QL Count distinct
22.25.47.EJB QL Concat Function Substring
22.25.48.EJB QL Between With Date Type Value
22.25.49.Aggregate function: AVG