hibernate 注解——迹忆客-ag捕鱼王app官网
到目前为止,我们已经了解了 hibernate 如何使用 xml 映射文件将数据从 pojo 转换为数据库表,反之亦然。 hibernate 注解是在不使用 xml 文件的情况下定义映射的最新方法。 我们可以使用注解作为 xml 映射元数据的补充或替代。
hibernate 注解是为对象和关系表映射提供元数据的强大方法。 所有的元数据都与代码一起被合并到 pojo java 文件中,这有助于用户在开发过程中同时理解表结构和 pojo。
如果要使我们的应用程序可移植到其他符合 ejb 3 的 orm 应用程序,我们必须使用注解来表示映射信息,但如果仍然想要更大的灵活性,那么应该使用基于 xml 的映射。
hibernate annotation 的环境设置
首先,我们必须确保使用的是 jdk 5.0,否则需要将 jdk 升级到 jdk 5.0 以利用对注解的本机支持。
其次,我们需要安装 hibernate 3.x 注解分发包,可从 sourceforge 获得:(下载 hibernate annotation)并复制 hibernate-annotations.jar
、lib/hibernate-comons-annotations.jar
和 lib/ejb3-persistence.jar
从 hibernate annotations 导入到我们的 classpath。
带注解的类示例
正如我们上面提到的,在使用 hibernate annotation 时,所有元数据都与代码一起被合并到 pojo java 文件中,这有助于用户在开发过程中同时理解表结构和 pojo。
考虑我们将使用以下 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
注解在一个字段上,并假定它应该在运行时直接通过字段访问对象的属性。 如果在 getid()
方法上放置了 @id
注释,则默认情况下我们将启用通过 getter 和 setter 方法访问属性。 因此,所有其他注解也按照所选策略放置在字段或 getter 方法上。
以下部分将解释上述类中使用的注解。
@entity 注解
ejb 3 标准注解包含在 javax.persistence
包中,因此我们首先导入这个包。 其次,我们对 employee 类使用了@entity
注解,它将这个类标记为一个实体 bean,因此它必须有一个至少在受保护范围内可见的无参数构造函数。
@table 注解
@table
注解允许我们指定将用于将实体持久保存在数据库中的表的详细信息。
@table
注解提供了四个属性,允许我们覆盖表的名称、目录和模式,并对表中的列强制执行唯一约束。 目前,我们只使用表名,即 employee。
@id 和 @generatedvalue 注解
每个实体 bean 都有一个主键,我们可以使用 @id
注解在类上对其进行注解。 主键可以是单个字段或多个字段的组合,具体取决于表结构。
默认情况下,@id
注解将自动确定要使用的最合适的主键生成策略,但我们可以通过应用 @generatedvalue
注解来覆盖它,它带有两个参数 strategy 和 generator,我不打算在这里讨论,所以 让我们只使用默认的密钥生成策略。 让 hibernate 确定要使用的生成器类型使我们的代码在不同数据库之间可移植。
@column 注解
@column 注解用于指定字段或属性将映射到的列的详细信息。 我们可以使用具有以下最常用属性的列注解
- name 属性允许明确指定列的名称。
- length 属性允许用于映射值的列的大小,特别是对于 string 值。
- 可空属性允许在生成模式时将该列标记为 not null。
- unique 属性允许将列标记为仅包含唯一值。
创建应用程序类
最后,我们将使用 main()
方法创建我们的应用程序类来运行应用程序。 我们将使用这个应用程序来保存一些员工的记录,然后我们将对这些记录应用 crud 操作。
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") // 如果使用需要添加包。
addannotatedclass(employee.class).
buildsessionfactory();
} catch (throwable ex) {
system.err.println("failed to create sessionfactory object." ex);
throw new exceptionininitializererror(ex);
}
manageemployee me = new manageemployee();
/* 在数据库中添加一些员工记录 */
integer empid1 = me.addemployee("zara", "ali", 1000);
integer empid2 = me.addemployee("daisy", "das", 5000);
integer empid3 = me.addemployee("john", "paul", 10000);
/* 列出所有员工 */
me.listemployees();
/* 更新员工记录 */
me.updateemployee(empid1, 5000);
/* 从数据库中删除员工 */
me.deleteemployee(empid2);
/* 列出新的员工名单 */
me.listemployees();
}
/* 在数据库中创建员工的方法 */
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;
}
/* 读取所有员工的方法 */
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();
}
}
/* 更新员工工资的方法 */
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();
}
}
/* 从记录中删除员工的方法 */
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();
}
}
}
数据库配置
现在让我们创建 hibernate.cfg.xml
配置文件来定义数据库相关参数。
org.hibernate.dialect.mysqldialect
com.mysql.jdbc.driver
jdbc:mysql://localhost/hibernate_demo
root
123456
编译和执行
以下是编译和运行上述应用程序的步骤。 在继续编译和执行之前,请确保我们已正确设置 path
和 classpath
。
- 从路径中删除 employee.hbm.xml 映射文件。
- 如上所示创建 employee.java 源文件并编译它。
- 如上所示创建 manageemployee.java 源文件并编译它。
- 执行 manageemployee 二进制文件来运行程序。
我们将得到以下结果,并且将在 employee 表中创建记录。
$ java manageemployee
.......various log messages will display here........
first name: zara last name: ali salary: 1000
first name: daisy last name: das salary: 5000
first name: john last name: paul salary: 10000
first name: zara last name: ali salary: 5000
first name: john last name: paul salary: 10000
如果你检查你的 employee 表,它应该有以下记录
mysql> select * from employee;
---- ------------ ----------- --------
| id | first_name | last_name | salary |
---- ------------ ----------- --------
| 29 | zara | ali | 5000 |
| 31 | john | paul | 10000 |
---- ------------ ----------- --------
2 rows in set (0.00 sec