java hibernate用注解 mysql例子_[Hibernate] 注解映射例子

Hibernate 注解(Hibernate Annotation) 是一种比较新的方式,通过在 java 简单类增加注解,来声明 java 类和数据库表的映射,作用和 xml 文件相似。hibernate 注解可以用来增强,或者替换 xml 的映射声明方式。

hibernate 注解功能需要使用下面三个 jar 文件

hibernate-annotations.jar

ejb3-persistence.jar

hibernate-commons-annotations.jar

代码的目录结构如下:

e895db488956fc24fcd694e9e5677d86.png

hibernate.cfg.xml 存储数据库信息,如数据库类型,账号密码,数据库名称。

Employee.java Employee 实体类,包含注解,声明 java 类和数据库表结构的映射关系。

ManageEmployee.java 管理 Employee,并对外提供操作 Employee 对象数据的接口。

App.java,演示本例子。

代码详情

在数据库中,创建 EMPLOYEE 表结构

create tableEMPLOYEE (

idINT NOT NULLauto_increment,

first_nameVARCHAR(20) default NULL,

last_nameVARCHAR(20) default NULL,

salaryINT default NULL,PRIMARY KEY(id)

);

创建 java 简单类,含有注解。

@Entity 表明 Employee 类似一个实体类( Entity Bean ),并且有一个无参构造函数

@Table 声明用于持久化当前类( Employee ) 的数据库表名。

@Id,每一个实体类都有一个主键,用 @Id 声明

@Column,表明当前变量所映射的数据库表的字段

packagetony.hibernateAnnotation;import javax.persistence.*;

@Entity

@Table(name="EMPLOYEE")public classEmployee {

@Id @GeneratedValue(strategy=GenerationType.IDENTITY)

@Column(name= "id")private intid;

@Column(name= "first_name")privateString firstName;

@Column(name= "last_name")privateString lastName;

@Column(name= "salary")private intsalary;publicEmployee() {}public intgetId() {returnid;

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

}publicString getFirstName() {returnfirstName;

}public voidsetFirstName( String first_name ) {this.firstName =first_name;

}publicString getLastName() {returnlastName;

}public voidsetLastName( String last_name ) {this.lastName =last_name;

}public intgetSalary() {returnsalary;

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

}

}

ManageEmployee.java Employee 的操作工具类。对业务层提供操作 Employee 的接口。

packagetony.hibernateAnnotation;importjava.util.List;importorg.hibernate.HibernateException;importorg.hibernate.Session;importorg.hibernate.SessionFactory;importorg.hibernate.Transaction;importorg.hibernate.cfg.Configuration;public classManageEmployee {private staticSessionFactory factory;

{

factory= newConfiguration().configure()

.addPackage("tony.hibernateAnnotation")

.addAnnotatedClass(Employee.class)

.buildSessionFactory();

}public int addEmployee(String fname, String lname, intsalary){

Session session=factory.openSession();

Transaction tx= null;

Integer employeeID= null;try{

tx=session.beginTransaction();

Employee employee= newEmployee();

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();

}returnemployeeID;

}public voidlistEmployees(){

Session session=factory.openSession();

Transaction tx= null;

tx=session.beginTransaction();

List employees = session.createQuery("FROM Employee").list();for(Employee emp : employees){

System.out.println(emp.getId()+ ", " + emp.getFirstName() + ", " + emp.getLastName() + ", " +emp.getSalary());;

}

tx.commit();

session.close();

}public ListgetAllEmployees(){

Session session=factory.openSession();

Transaction tx= null;

tx=session.beginTransaction();

List employees = session.createQuery("FROM Employee").list();

tx.commit();

session.close();returnemployees;

}public void updateEmployee(int employeeId, intsalary){

Session session=factory.openSession();

Transaction tx= null;

tx=session.beginTransaction();

Employee emp= session.get(Employee.class, employeeId);

emp.setSalary(salary);

session.update(emp);

tx.commit();

session.close();

}public void deleteEmployee(intemployeeId){

Session session=factory.openSession();

Transaction tx= null;

tx=session.beginTransaction();

Employee emp= session.get(Employee.class, employeeId);

session.delete(emp);

tx.commit();

session.close();

}

}

pom.xml 本例子所依赖的包

org.hibernate

hibernate-core

5.2.3.Final

mysql

mysql-connector-java

5.1.6

org.hibernate

hibernate-annotations

3.5.6-Final

org.hibernate

ejb3-persistence

3.3.2.Beta1

org.hibernate

hibernate-commons-annotations

3.2.0.Final

说明

根据 tutorialspoint 例子的代码,无法运行成功,可能与 hibernate 使用版本有关,修正下面错误后,运作正常。

运行错误 1

java.lang.NoClassDefFoundError: org/hibernate/cfg/Mappings

在ManageEmployee.java 中,创建 SessionFactory 对象时,应该使用 org.hibernate.cfg.Configuration,而不是用org.hibernate.cfg.AnnotationConfiguration。参考 java.lang.NoClassDefFoundError, stackOverflow

运行错误2

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'hibernatetest.hibernate_sequence' doesn't exist

这应该和 hibernate 版本有关,在 hibernate 5 及以上版本,在 java 文件中定义主键字段时,使用 @GeneratedValue(strategy = GenerationType.IDENTITY) 代替 @GeneratedValue。参考 Hibernate-sequence doesn't exist, stackOverflow

参考资料

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值