hibernate注解方式使我不需要在创建实体类的同时创建*.hbm.xml来映射数据库中对应表格,配置如下代码中所示:

Dept.java

 1 package com.entity;
 2 
 3 import java.util.HashSet;
 4 import java.util.Set;
 5 
 6 import javax.persistence.CascadeType;
 7 import javax.persistence.Column;
 8 import javax.persistence.Entity;
 9 import javax.persistence.GeneratedValue;
10 import javax.persistence.GenerationType;
11 import javax.persistence.Id;
12 import javax.persistence.OneToMany;
13 import javax.persistence.SequenceGenerator;
14 import javax.persistence.Table;
15 import javax.persistence.Transient;
16 
17 @Entity
18 @Table(name="dept")
19 public class Dept implements java.io.Serializable {
20 
21     // Fields
22 
23     private Integer id;
24     private String name;
25     private String location;
26     private Set<Emp> emps = new HashSet<Emp>(0);
27 
28     // Constructors
29 
30     /** default constructor */
31     public Dept() {
32     }
33 
34     /** full constructor */
35     public Dept(String name, String location, Set emps) {
36         this.name = name;
37         this.location = location;
38         this.emps = emps;
39     }
40 
41     // Property accessors
42 
43     @Id
44     @GeneratedValue(strategy=GenerationType.SEQUENCE,generator="seq_dept")
45     @SequenceGenerator(name="seq_dept",sequenceName="seq_dept_id",allocationSize=20,initialValue=1)
46     public Integer getId() {
47         return this.id;
48     }
49 
50     public void setId(Integer id) {
51         this.id = id;
52     }
53 
54     @Column(name="name")
55     public String getName() {
56         return this.name;
57     }
58 
59     public void setName(String name) {
60         this.name = name;
61     }
62 
63     @Transient
64     public String getLocation() {
65         return this.location;
66     }
67 
68     public void setLocation(String location) {
69         this.location = location;
70     }
71     
72     @OneToMany(mappedBy="dept",cascade=CascadeType.ALL)
73     public Set<Emp> getEmps() {
74         return emps;
75     }
76 
77     public void setEmps(Set<Emp> emps) {
78         this.emps = emps;
79     }
80     
81 
82 }

Emp.java

  1 package com.entity;
  2 
  3 import java.util.Date;
  4 
  5 import javax.persistence.Column;
  6 import javax.persistence.Entity;
  7 import javax.persistence.FetchType;
  8 import javax.persistence.GeneratedValue;
  9 import javax.persistence.GenerationType;
 10 import javax.persistence.Id;
 11 import javax.persistence.JoinColumn;
 12 import javax.persistence.ManyToOne;
 13 import javax.persistence.NamedQuery;
 14 import javax.persistence.SequenceGenerator;
 15 import javax.persistence.Table;
 16 import javax.persistence.Transient;
 17 
 18 @Entity
 19 @Table(name="emp")
 20 
 21 public class Emp implements java.io.Serializable {
 22 
 23     
 24 
 25     
 26     private Integer id;
 27     private Dept dept;
 28     private String name;
 29     private String job;
 30     private Double salary;
 31     
 32     private Date hiredate;
 33 
 34     // Constructors
 35 
 36     /** default constructor */
 37     public Emp() {
 38     }
 39 
 40     /** full constructor */
 41     public Emp(Dept dept, String name, String job, Double salary) {
 42         this.dept = dept;
 43         this.name = name;
 44         this.job = job;
 45         this.salary = salary;
 46     }
 47 
 48     
 49     @Id
 50     @GeneratedValue(strategy=GenerationType.SEQUENCE,generator="seq_emp")
 51     @SequenceGenerator(name="seq_emp",sequenceName="seq_emp_eno",allocationSize=20,initialValue=1)
 52     public Integer getId() {
 53         return this.id;
 54     }
 55 
 56     public void setId(Integer id) {
 57         this.id = id;
 58     }
 59 
 60     @ManyToOne(fetch=FetchType.LAZY)
 61     @JoinColumn(name="dept_id")
 62     public Dept getDept() {
 63         return this.dept;
 64     }
 65 
 66     public void setDept(Dept dept) {
 67         this.dept = dept;
 68     }
 69 
 70     @Column(name="name")
 71     public String getName() {
 72         return this.name;
 73     }
 74 
 75     public void setName(String name) {
 76         this.name = name;
 77     }
 78     @Transient
 79     public String getJob() {
 80         return this.job;
 81     }
 82 
 83     public void setJob(String job) {
 84         this.job = job;
 85     }
 86     @Transient
 87     public Double getSalary() {
 88         return this.salary;
 89     }
 90 
 91     public void setSalary(Double salary) {
 92         this.salary = salary;
 93     }
 94     @Column(name="hiredate")
 95     public Date getHiredate() {
 96         return hiredate;
 97     }
 98 
 99     public void setHiredate(Date hiredate) {
100         this.hiredate = hiredate;
101     }
102 }

hibernate.cfg.xml中的配置如下:

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

<session-factory>
    <property name="dialect">org.hibernate.dialect.PointbaseDialect</property>
    <property name="connection.url">
        jdbc:oracle:thin:@192.168.40.128:1521:orcl
    </property>
    <property name="connection.username">thunder</property>
    <property name="connection.password">admin</property>
    <property name="connection.driver_class">
        oracle.jdbc.OracleDriver
    </property>
    <property name="myeclipse.connection.profile">thunder</property>
    <property name="show_sql">true</property>
    <property name="format_sql">true</property>
    <mapping class="com.entity.Dept"/>
    <mapping class="com.entity.Emp"/>
</session-factory>

</hibernate-configuration>
View Code

需要注意<mapping>中class属性值的引用方式,这是和引用*.hbm.xml的不同之处。

测试:

public static void main(String[] args) {
        SessionFactory sf =null;
        Session session=null;
        Transaction tx=null;
        try {
            
            //新的获取sf的方式
            sf=new AnnotationConfiguration().configure().buildSessionFactory();
            //获得session
            session =sf.openSession();
            //获取事务
            tx=session.beginTransaction();
            Emp emp=new Emp();
            emp.setName("神经一枚");
            emp.setHiredate(new Date());
            session.save(emp);
            tx.commit();
            System.out.println("add ok!");
            
            //根据主键去查询信息,根据many-to-one加载部门信息
            Emp emp=(Emp) session.load(Emp.class, new Integer(17));
            System.out.println(emp.getName()+"    "+emp.getDept().getName());
        
            //通过添加部门的同时把员工添加过去
            Emp e1 =new Emp();
            e1.setName("思过");
            e1.setHiredate(new Date());
            
            Dept d=new Dept();
            d.setName("市场部");
            
            d.getEmps().add(e1);
            e1.setDept(d);
            session.save(d);
            tx.commit();
            System.out.println("it is successful");
            
            
        } catch (Exception e) {
            //tx.rollback();
            e.printStackTrace();
        }finally{
            session.close();
            sf.close();
        }
        
    }

需要注意,获取Session工厂的方法与之前的不一样。

以上就是hibernate逐渐的简单使用。

posted on 2015-12-06 14:11  映日残阳  阅读(177)  评论(0编辑  收藏  举报