LZ最近在学习Java Web的三大框架之一的Hibernate,可能很多人觉得Hibernate过时了,其实这个针对数据的轻量级的框架还是很好用的,可以帮我们在不同的数据库表之间建立联系,方便我们能够完成牵一发而动全身的功能。那么下面是我从《Java Web王者归来》这本书的第一个Hibernate的样例而完成。
这是一个有Cat类的数据表,其中这个数据表里的数据列有id,主键;name,表示猫的名字;description,表示关于这只猫的描述;还有就是Date,表示时间;另外还有一个Cat类,表示这只猫的母亲,而且用这个母亲的id是个外连接,而且是多对一的外连接。另外这个表示数据表的是用@方式来表示的,具体的代码如下,Cat.java类:
package domain;
import java.util.Date;
import javax.persistence.*;
@NamedQueries(value={@NamedQuery(name="all cat",query="select c from Cat c"),
@NamedQuery(name = "cat by name", query = " select c from Cat c where c.name = :name ", hints = { @QueryHint(name = "org.hibernate.callable", value = "true") }),
@NamedQuery(name = "cat by mother", query = " select c from Cat c ")})
@Entity
@Table(name = "tb_cat")
public class Cat
{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column(name = "name")
private String name;
@Column(name="description")
private String description;
@ManyToOne
@JoinColumn(name = "mother_id")
private Cat Mother;
@Temporal(TemporalType.TIMESTAMP)
@Column(name="createDate")
private Date createDate;
public Integer getId()
{
return id;
}
public void setId(Integer id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getDescription()
{
return description;
}
public void setDescription(String description)
{
this.description = description;
}
public Cat getMother()
{
return Mother;
}
public void setMother(Cat mother)
{
Mother = mother;
}
public Date getCreateDate()
{
return createDate;
}
public void setCreateDate(Date createDate)
{
this.createDate = createDate;
}
}
当然因为是用@方式,所以在hibernate.cfg.xml中需要使用mapping class的标签,而不是mapping resource标签,这个是用于.hbm.xml的方式。具体的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.MySQLDialect</property>
<property name="connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="connection.username">root</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- 指定在控制台打印生成的sql语句 -->
<property name="show_sql">true</property>
<!-- 指定Hibernate启动的时候自动创建表结构 -->
<property name="hbm2ddl.auto">create</property>
<property name="current_session_context_class">thread</property>
<mapping class="domain.Cat"></mapping>
</session-factory>
</hibernate-configuration>
其中在这个文件里的配置中有一个关于自动创建数据表的一行,用了hbm2ddl.auto这个标签中的create。
这些配置完后,就是最重要的用来向数据表中插入数据。具体的代码如下CatTest.java:
package test;
import domain.*;
import java.awt.Font;
import java.util.Date;
import java.util.List;
import javax.swing.JOptionPane;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
class CatTest
{
public static void main(String args[])
{
Cat mother = new Cat();
mother.setName("Mary White");
mother.setDescription("The Mama cat.");
mother.setCreateDate(new Date());
Cat kitty = new Cat();
kitty.setMother(mother);
kitty.setName("kitty");
kitty.setDescription("Hello Kitty");
kitty.setCreateDate(new Date());
Cat mimmy = new Cat();
mimmy.setMother(mother);
mimmy.setName("Mimmy");
mimmy.setDescription("Kitty's little twin sister.");
mimmy.setCreateDate(new Date());
AnnotationConfiguration conf = new AnnotationConfiguration();
SessionFactory sf = conf.configure().buildSessionFactory();
Session sess = sf.openSession();
Transaction tx = sess.beginTransaction();
sess.persist(mother);
sess.persist(kitty);
sess.persist(mimmy);
@SuppressWarnings("all")
List<Cat> catList = sess.createQuery(" from Cat ").list(); //注意这里用了HQL的语句
StringBuffer result = new StringBuffer();
result.append("数据库的猫:\r\n\r\n");
for(Cat cc : catList)
{
result.append("猫:" + cc.getName() + ", ");
result.append("猫妈妈: " + (cc.getMother() == null ? "没有记录" : cc.getMother().getName()));
result.append("\r\n");
}
tx.commit();
sess.close();
JOptionPane.getRootFrame().setFont(new Font("Arial",Font.BOLD,14));
JOptionPane.showMessageDialog(null, result.toString());
}
}
这样完成后就可以执行java代码,就可以发现已经在数据库中生成了数据表tb_cat,而且又向数据表中插入了相关的猫的数据。但是在配置中我也遇到了很多问题,关于那些个.jar包的问题。因为我用的是Hibernate3.x,所以需要引入的是Hibernate3.x的.jar包,一开始我用的是Hibernate3.1来新建工程,但是发现myeclipse中没有一些相关的.jar包,所以后来我引入的是Hibernate3.3.2的.jar包,然后就是需要另外配置一些.jar包,缺少这些个.jar包,会出现一些错误,这些错误会在console中出现。所以可以针对这个错误来进行改进。