Add Employee.java file
package com.akt;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
@NamedQueries(
@NamedQuery(
name="findEmployeeByName",
query="from Employee e where e.name=:name"
)
)
@Entity
@Table(name="employee")
public class Employee {
@Id
@GeneratedValue
@Column(name="empId")
private int empId;
@Column(name="name")
private String name;
@Column(name="username")
private String username;
@Column(name="email")
private String email;
@Column(name="salary")
private int salary;
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String toString(){return empId+" "+name+" "+salary+" "+username;}
}
MainClass.java
package com.akt;
import java.util.Iterator;
import java.util.List;
import javax.persistence.TypedQuery;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class MainClass {
public static void main(String[] args) {
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
SessionFactory sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
/*Transaction transaction = session.getTransaction();
transaction.begin();
Employee employee =new Employee();
employee.setUsername("abc");
employee.setEmail("abc@gmail.com");
employee.setSalary(5000);
employee.setName("abc");
session.persist(employee);
transaction.commit();*/
@SuppressWarnings("unchecked")
TypedQuery<Employee> query =session.getNamedQuery("findEmployeeByName");
query.setParameter("name", "anil");
List<Employee> employees=query.getResultList();
Iterator<Employee> itr=employees.iterator();
while(itr.hasNext()){
Employee e=itr.next();
System.out.println(e);
}
session.close();
sessionFactory.close();
}
}
No comments:
Post a Comment