Hibernate

What is the difference between primary key and foreign key?
Primary Key and Foreign Key
A foreign key is a set of one or more columns in a table that refers to the primary key in another table.

如何把mysql import到Eclipse里面?

  • Connector Java下载 mysql connector
  • 右键点击project -> Build Path -> Add External Archives..
  • 然后选择 mysql-connector-java-x.y.z-bin.jar 文件

How to map POJO class into Main class?
Suppose we have a Emplyee POJO class. then we could use two ways to finish mapping.

  1. Write mapping into hibernate.cfg.xml:

    <mapping class="com.xyz.hibernate.Student_Info"/>
    
  2. Write mapping into the Main method:

    SessionFactory factory = new Configuration().
                             configure().
                             //Mapping POJO class using this method
                             addAnnotatedClass(Employee.class).
                             buildSessionFactory();
    

How to use hbm2ddl.auto property?
Most common Annotations
@Entity
@Id
@Column
@Transient
@Temporal(TemporalType.<选择一个类型>)
@GeneratedValue
@GeneratedValue(strategy=GenerationType.<选择一个类型>)

One to one mapping in hibernate annotation
one to one mapping
@OneToOne(cascade=CascadeType.All)
@JoinColumn(name="<选择一个column name>")

public class EmployeeDetail {

    @Id
    @Column(name="employee_id", unique=true, nullable=false)
    @GeneratedValue(generator="gen")
    @GenericGenerator(name="gen", strategy="foreign", parameters=@Parameter(name="property", value="employee")
    private Long employeeId;
    ...
}

//Note that in EmployeeDetail class we have used @GenericGenerator to specify primary key. This will ensure that the primary key from Employee table is used instead of generating a new one.