Hibernate环境搭建与简单实例

来源:互联网 发布:java中final和static 编辑:程序博客网 时间:2024/05/16 05:23

一、Hibernate 下载

官网下载 地址:http://hibernate.org/orm/downloads/

二、环境搭建

1.在eclipse 中使用,新建项目以后,将hibernate lib/required 目录下所有.jar 包导入到项目中。这里写图片描述
2.导入JDBC驱动的jar包,根据项目使用的数据库选择对应的驱动包,本例中使用Mysql。
3.在hibernate 中找一个hibernate.cfg.xml 作为模版复制项目的src目录下:并进行相应配置:<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/day12</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">1234</property>
<!--配置数据库方言-->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="show_sql">true</property>
<!--配置由当前线程获取session-->
<property name="current_session_context_class">thread</property>

到这里hibernate 的环境基本就搭建完成了,接下来是简单的应用例子,通过这个例子来学习Hibernate 的注解 和如何进行CRUD操作。

三、应用Hibernate

1.定义实体类:本例中使用了 dept 和emp 两个实体类:`@Entity(name=”tb_department”)
public class Department {

@Id@GeneratedValue(strategy=GenerationType.IDENTITY)private Integer dept_id;@Column(length=150)private String dept_name;@OneToMany(cascade=CascadeType.ALL,mappedBy="dept")private List<Employee> emps;public List<Employee> getEmps() {    return emps;}public void setEmps(List<Employee> emps) {    this.emps = emps;}public Integer getDept_id() {    return dept_id;}public void setDept_id(Integer dept_id) {    this.dept_id = dept_id;}public String getDept_name() {    return dept_name;}public void setDept_name(String dept_name) {    this.dept_name = dept_name;}@Overridepublic String toString() {    return "Department [dept_id=" + dept_id + ", dept_name=" + dept_name + "]";}

}`

@Entity(name="tb_employee")public class Employee {    @Id    @GeneratedValue(strategy=GenerationType.IDENTITY)    private Integer emp_id;    @Column(length=150)    private String emp_name;    @ManyToOne(cascade=CascadeType.ALL)    @JoinColumn(name="dept_id",foreignKey=@ForeignKey(name="epm_dept"))    private Department dept;    public Integer getEmp_id() {        return emp_id;    }    public void setEmp_id(Integer emp_id) {        this.emp_id = emp_id;    }    public String getEmp_name() {        return emp_name;    }    public void setEmp_name(String emp_name) {        this.emp_name = emp_name;    }    @Override    public String toString() {        return "Employee [emp_id=" + emp_id + ", emp_name=" + emp_name + ", dept=" + dept.getDept_name() + "]";    }    public Department getDept() {        return dept;    }    public void setDept(Department dept) {        this.dept = dept;    }}

实体类中用到的注解:
@Entity(name=”tb_name”) 用来于数据库中的表对应,name 属性指定了实体类在数据库中的表名

@Id 用来指定属性在表中作为主键
@Column 用来注解列 该注解有以下属性:
1. name 表中的列名
2. nullable 能否为空
3. length 长度,只对String类型的属性有效,对应数据库中的varchar
4. unique 是否唯一
5. 等等
@ManyToOne 多对一关系 cascade属性用于指定级联
@JoinColumn(name=”col_name” foreginkey=@Foreginkey)用于将一的一方的主键作为多的一方的外键

@OneTOMany(cascade=CascadeType.ALL,mappedBy=”dept”)

实体类定义完成后,需要在hibernate.cfg.xml 中配置

<mapping class="domain.Employee"/><mapping class="domain.Department"/>

下面是获取session的方法,定义了一个HUtil 类来获取session

public class HUtil {    private static SessionFactory sf=null;    static {        final StandardServiceRegistry ssr = new StandardServiceRegistryBuilder()                .configure()                .build();        sf = new MetadataSources(ssr).buildMetadata().buildSessionFactory();    }    public static Session getSession() {        return sf.getCurrentSession();    }}

接下来是dao类的定义:
`public class EmployeeDao {
private Session session;

public EmployeeDao() {    super();    session = HUtil.getSession();    session.beginTransaction();}public void addEmp(Employee emp) {    session.save(emp);} public Employee get(Integer id) {    Employee emp = session.get(Employee.class, id);    return emp;}public List<Employee> findAll() {    List<Employee> list = session.createQuery("from tb_employee", Employee.class).list();     return list;}

}`
测试类:

public class EmpDaoTest {    public static void main(String[] args) {        EmployeeDao ed = new EmployeeDao();        /*Department dept = new Department();        dept.setDept_name("财务部");        String[] names = {"张三","李四","王五","赵六","周七"};        for (int i = 0; i < 5; i++) {            Employee emp = new Employee();            emp.setDept(dept);            emp.setEmp_name(names[i]);            ed.addEmp(emp);        }*/    }}
原创粉丝点击