TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
在Hibernate中使用Annotation,还需要下载Annotation库。Hibernate的Core类库与Annotation类库默认是分开的,需要下载ejb3-persistence.jar,hibernate-annotations.jar,hibernate-commons-annotations.jar等添加到项目ClassPath中。
1,配置Cat实体类
package com.zhangjie.hibernate.bean;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity //@Entity表示该类能被Hibernate持久化
@Table(name="tb_cat") //指定该Entity对应的数据表名
public class Cat {
@Id //指定该列为主键
@GeneratedValue(strategy = GenerationType.AUTO) //主键类型,auto为自增长类型
private Integer id;
@Column(name = "name") //指定属性对应的数据库表的列为name
private String name;
@Column(name = "description") //同上。@Column与name均可省略
private String description;
@ManyToOne //指定实体类之间的关系,本例为多对一的关系
@JoinColumn(name = "mother_id") //该属性对应的列
private Cat mather;
@Temporal(TemporalType.DATE) //日期类型(DATE,TIME还是TIMESTEMP)
@Column(name = "createDate")
private Date createDate;
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Cat getMather() {
return mather;
}
public void setMather(Cat mather) {
this.mather = mather;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
2,修改Hibernate配置文件
<?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="connection.username">sa</property>
<property name="connection.url">
jdbc:sqlserver://localhost:1433;databaseName=hibernate
</property>
<property name="dialect">
org.hibernate.dialect.SQLServerDialect
</property>
<property name="myeclipse.connection.profile">hibernate</property>
<property name="connection.password">zhangjie</property>
<property name="connection.driver_class">
com.microsoft.sqlserver.jdbc.SQLServerDriver
</property>
<!-- 指定在控制台打印生成的SQL语句 -->
<property name="show_sql">true</property>
<!-- 指定Hibernate启动的时候自动创建结构 -->
<property name="hbm2ddl.auto">create</property>
<!-- 要加这一句,否则可能会遇到异常 -->
<property name="current_session_context_class">thread</property>
<!-- 指定Cat类为Hibernate实体类 -->
<mapping class="com.zhangjie.hibernate.bean.Cat" />
</session-factory>
</hibernate-configuration>
3,使用HIbernate工具类
[color=#9900cc,strength=3);]HibernateUtil.java
package com.zhangjie.hibernate.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
/**
* Hibernate官方提供的HibernateUtil类实现同样的功能,代码简洁的多
*
*/
public class HibernateUtil {
private static final SessionFactory sessionFactory;
//单态模式的SesstionFactory
static{
try{
//从hibernate.cfg.xml中加载配置
sessionFactory = new AnnotationConfiguration()
.configure("hibernate.cfg.xml").buildSessionFactory();
}catch(Throwable ex){
System.out.println("Initial SessionFactory creation failed."+ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory(){
return sessionFactory;
}
}
4,执行Hibernate程序
[color=#9900cc,strength=3);]CatTest.java
package com.zhangjie.hibernate.test;
import java.awt.Font;
import java.util.Date;
import java.util.List;
import javax.swing.JOptionPane;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.zhangjie.hibernate.bean.Cat;
import com.zhangjie.hibernate.util.HibernateUtil;
public class CatTest {
public static void main(String[] args) {
Cat mother = new Cat(); //mother猫
mother.setName("Mary White"); //设置名字
mother.setDescription("The Mama Cat.");
mother.setCreateDate(new Date());//设置创建日期
Cat kitty = new Cat(); //kitty猫
kitty.setMather(mother);//设置与mother的母女关系
kitty.setName("Kitty"); //设置名字
kitty.setDescription("Hello Kitty.");//设置描述
kitty.setCreateDate(new Date()); //设置创建日期
Cat mimmy = new Cat(); //mimmy猫
mimmy.setMather(mother);
mimmy.setName("Mimmy");//设置名字
mimmy.setDescription("Kitty's little twin sister");//设置描述
mimmy.setCreateDate(new Date()); //设置创建日期
//开启一个Hibernate对话
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction trans = session.beginTransaction(); //开启一个事务
session.persist(mother); //将mother保存进数据库
session.persist(kitty); //将kitty保存进数据库
session.persist(mimmy); //将mimmy保存进数据库
@SuppressWarnings("all")
List<Cat> catList = session.createQuery(" from Cat ").list(); //查询数据库中的所有的数据
StringBuffer result = new StringBuffer(); //输出查询结果
result.append("数据库里的所有的猫:\r\n\r\n");
for(Cat cc : catList){
result.append("猫:"+cc.getName()+","); //输出猫的名字
result.append("猫妈妈:"+(cc.getMather() == null? "没有记录" : cc.getMather().getName()));
result.append("\r\n");
}
trans.commit(); //提交事务
session.close(); //关闭Hibernate对话
//用Swing显示查询结果
JOptionPane.getRootFrame().setFont(new Font("Arial",Font.BOLD,14));
JOptionPane.showMessageDialog(null, result.toString());
}
}
运行结果:
|
|