Friday 5 July 2019

JPA: @Column: customize the column name


@Column annotation is used to specify the column name of a table. If you do not specify the column name, then the property name is considered as column name by default.

For example,
@Entity(name = "MY_EMPLOYEE")
public class Employee {

         private int id;
         private String firstName;
         private String lastName;

                  .....
                  .....
}

Above snippet creates a table with name ‘MY_EMPLOYEE’ and column names are equal to the property names (id, firstName, lastName).



You can specify the column names like below.

@Entity(name = "MY_EMPLOYEE")
public class Employee {

         @Id
         @Column(name = "EMPLOYEE_ID")
         private int id;

         @Column(name = "EMPLOYEE_FIRST_NAME")
         private String firstName;

         @Column(name = "EMPLOYEE_LAST_NAME")
         private String lastName;
        
         ....
         ....
}

In the above example, I mapped the
Property id to column name ‘EMPLOYEE_ID’,
Property firstName to ‘EMPLOYEE_FIRST_NAME’,
Property lastname to ‘EMPLOYEE_LAST_NAME’

Find the below working application.

Employee.java
package com.sample.myApp.entities;

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

@Entity(name = "MY_EMPLOYEE")
public class Employee {

 @Id
 @Column(name = "EMPLOYEE_ID")
 private int id;

 @Column(name = "EMPLOYEE_FIRST_NAME")
 private String firstName;

 @Column(name = "EMPLOYEE_LAST_NAME")
 private String lastName;

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 @Override
 public String toString() {
  return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]";
 }

}


persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
 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_2_0.xsd">
 <persistence-unit name="myPersistenceUnit"
  transaction-type="RESOURCE_LOCAL">
  <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>

  <class>com.sample.myApp.entities.Employee</class>

  <properties>
   <property name="eclipselink.target-database" value="Derby" />
   <property name="javax.persistence.jdbc.driver"
    value="org.apache.derby.jdbc.ClientDriver" />
   <property name="javax.persistence.jdbc.url"
    value="jdbc:derby://localhost:1527/demoDatabase;create=true" />
   <property name="javax.persistence.jdbc.user" value="APP" />
   <property name="javax.persistence.jdbc.password" value="APP" />
   <property name="eclipselink.logging.level" value="ALL" />
   

   <property name="eclipselink.ddl-generation"
    value="drop-and-create-tables" />

   <property name="eclipselink.ddl-generation.output-mode"
    value="database" />
  </properties>

 </persistence-unit>
</persistence>


TestApp.java
package com.sample.myApp;

import java.util.List;

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

import com.sample.myApp.entities.Employee;

public class TestApp {

 public static void main(String args[]) {
  EntityManagerFactory emf = null;
  EntityManager em = null;

  try {
   emf = Persistence.createEntityManagerFactory("myPersistenceUnit");

   em = emf.createEntityManager();

   Employee emp = new Employee();
   emp.setFirstName("Krishna");
   emp.setLastName("Gurram");
   
   em.getTransaction().begin();
   em.persist(emp);
   em.getTransaction().commit();

   Query q = em.createQuery("select e from MY_EMPLOYEE e",
     Employee.class);
   List<Employee> emps = q.getResultList();
   for (Employee emp1 : emps) {
    System.out.println(emp1);
   }
  } finally {
   if (em != null && em.isOpen()) {
    em.close();
   }

   if (emf != null && emf.isOpen()) {
    emf.close();
   }
  }

 }

}


When you ran TestApp.java, you can able to see below messages in console.

[EL Finest]: query: 2018-06-26 21:03:29.667--ServerSession(575335780)--Thread(Thread[main,5,main])--Execute query DataModifyQuery(sql="krishna TABLE MY_EMPLOYEE (EMPLOYEE_ID INTEGER NOT NULL, EMPLOYEE_FIRST_NAME VARCHAR(255), EMPLOYEE_LAST_NAME VARCHAR(255), PRIMARY KEY (EMPLOYEE_ID))")

[EL Fine]: sql: 2018-06-26 21:03:29.759--ClientSession(1497845528)--Connection(1984990929)--Thread(Thread[main,5,main])--INSERT INTO MY_EMPLOYEE (EMPLOYEE_ID, EMPLOYEE_FIRST_NAME, EMPLOYEE_LAST_NAME) VALUES (?, ?, ?)
 bind => [0, Krishna, Gurram]
 
[EL Finest]: query: 2018-06-26 21:03:29.994--UnitOfWork(728885526)--Thread(Thread[main,5,main])--Execute query ReadAllQuery(referenceClass=Employee sql="SELECT EMPLOYEE_ID, EMPLOYEE_FIRST_NAME, EMPLOYEE_LAST_NAME FROM MY_EMPLOYEE")

[EL Fine]: sql: 2018-06-26 21:03:29.995--ServerSession(575335780)--Connection(1984990929)--Thread(Thread[main,5,main])--SELECT EMPLOYEE_ID, EMPLOYEE_FIRST_NAME, EMPLOYEE_LAST_NAME FROM MY_EMPLOYEE

[EL Finest]: connection: 2018-06-26 21:03:30.017--ServerSession(575335780)--Connection(1984990929)--Thread(Thread[main,5,main])--Connection released to connection pool [default].
Employee [id=0, firstName=Krishna, lastName=Gurram]


You can confirm the same using DBVisualizer.

Note
You can run query with WHERE clause like below.

Query q = em.createQuery("SELECT e from MY_EMPLOYEE e WHERE e.firstName='Krishna' AND e.lastName='Gurram' ", Employee.class);

Previous                                                    Next                                                    Home

No comments:

Post a Comment