详解Java的Hibernate框架中的注解与缓存
|
注解 Hibernate的注解是强大的方式来提供元数据对象和关系表的映射。所有的元数据被杵到一起的代码POJO java文件这可以帮助用户在开发过程中同时要了解表的结构和POJO。 如果打算让应用程序移植到其他EJB3规范的ORM应用程序,必须使用注解来表示映射信息,但仍然如果想要更大的灵活性,那么应该使用基于XML的映射去。 环境设置Hibernate注释 其次,需要安装Hibernate的3.x注解分发包,可从SourceForge上: (Download Hibernate Annotation) 并拷贝 hibernate-annotations.jar,lib/hibernate-comons-annotations.jar 和 lib/ejb3-persistence.jar 从Hibernate注解分配到CLASSPATH 注释的类实例: 考虑到将要使用下面的EMPLOYEE表来存储的对象: create table EMPLOYEE ( id INT NOT NULL auto_increment,first_name VARCHAR(20) default NULL,last_name VARCHAR(20) default NULL,salary INT default NULL,PRIMARY KEY (id) ); 下面是用注解来映射与定义的EMPLOYEE表的对象Employee类的映射:
import javax.persistence.*;
@Entity
@Table(name = "EMPLOYEE")
public class Employee {
@Id @GeneratedValue
@Column(name = "id")
private int id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "salary")
private int salary;
public Employee() {}
public int getId() {
return id;
}
public void setId( int id ) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName( String first_name ) {
this.firstName = first_name;
}
public String getLastName() {
return lastName;
}
public void setLastName( String last_name ) {
this.lastName = last_name;
}
public int getSalary() {
return salary;
}
public void setSalary( int salary ) {
this.salary = salary;
}
}
Hibernate检测@Id注释是对一个字段,并假设它应该直接通过在运行时域访问一个对象的属性。如果将@Id注释getId()方法,将通过getter和setter方法默认情况下允许访问属性。因此,所有其他注释也被放置在任一字段或getter方法,以下所选择的策略。下面的部分将解释在上面的类中使用的注释。 @Entity 注解: @Table 注解: @Table注释提供了四个属性,允许覆盖表的名称,它的目录,它的架构,并执行对列的唯一约束在表中。现在,我们使用的是刚刚是EMPLOYEE表的名称。 @Id 和 @GeneratedValue 注解: 默认情况下,@Id注解会自动确定要使用的最合适的主键生成策略,但可以通过应用@GeneratedValue注释,它接受两个参数,strategy和generator,不打算在这里讨论,只使用默认的默认键生成策略。让Hibernate确定要使用的generator类型使不同数据库之间代码的可移植性。 @Column 注解: name属性允许将显式指定列的名称。 length 属性允许用于映射一个value尤其是对一个字符串值的列的大小。 nullable 属性允许该列被标记为NOT NULL生成架构时。 unique 属性允许被标记为只包含唯一值的列。 创建应用程序类:
import java.util.List;
import java.util.Date;
import java.util.Iterator;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class ManageEmployee {
private static SessionFactory factory;
public static void main(String[] args) {
try{
factory = new AnnotationConfiguration().
configure().
//addPackage("com.xyz") //add package if used.
addAnnotatedClass(Employee.class).
buildSessionFactory();
}catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
ManageEmployee ME = new ManageEmployee();
/* Add few employee records in database */
Integer empID1 = ME.addEmployee("Zara","Ali",1000);
Integer empID2 = ME.addEmployee("Daisy","Das",5000);
Integer empID3 = ME.addEmployee("John","Paul",10000);
/* List down all the employees */
ME.listEmployees();
/* Update employee's records */
ME.updateEmployee(empID1,5000);
/* Delete an employee from the database */
ME.deleteEmployee(empID2);
/* List down new list of the employees */
ME.listEmployees();
}
/* Method to CREATE an employee in the database */
public Integer addEmployee(String fname,String lname,int salary){
Session session = factory.openSession();
Transaction tx = null;
Integer employeeID = null;
try{
tx = session.beginTransaction();
Employee employee = new Employee();
employee.setFirstName(fname);
employee.setLastName(lname);
employee.setSalary(salary);
employeeID = (Integer) session.save(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
return employeeID;
}
/* Method to READ all the employees */
public void listEmployees( ){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
List employees = session.createQuery("FROM Employee").list();
for (Iterator iterator =
employees.iterator(); iterator.hasNext();){
Employee employee = (Employee) iterator.next();
System.out.print("First Name: " + employee.getFirstName());
System.out.print(" Last Name: " + employee.getLastName());
System.out.println(" Salary: " + employee.getSalary());
}
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
/* Method to UPDATE salary for an employee */
public void updateEmployee(Integer EmployeeID,int salary ){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
Employee employee =
(Employee)session.get(Employee.class,EmployeeID);
employee.setSalary( salary );
session.update(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
/* Method to DELETE an employee from the records */
public void deleteEmployee(Integer EmployeeID){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
Employee employee =
(Employee)session.get(Employee.class,EmployeeID);
session.delete(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
}
数据库配置: <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-configuration SYSTEM "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.dialect"> org.hibernate.dialect.MySQLDialect </property> <property name="hibernate.connection.driver_class"> com.mysql.jdbc.Driver </property> <!-- Assume students is the database name --> <property name="hibernate.connection.url"> jdbc:mysql://localhost/test </property> <property name="hibernate.connection.username"> root </property> <property name="hibernate.connection.password"> cohondob </property> </session-factory> </hibernate-configuration> 编译和执行: 从路径中删除Employee.hbm.xml映射文件。 创建Employee.java源文件,如上图所示,并编译它。 创建ManageEmployee.java源文件,如上图所示,并编译它。 执行ManageEmployee二进制文件来运行程序。 (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
