Hibernate+Oracle注解式完整实例

时间:2023-03-09 01:27:58
Hibernate+Oracle注解式完整实例

MyEclipse10,新建Web Project,取名hibernate,

Hibernate+Oracle注解式完整实例

jar包

Hibernate+Oracle注解式完整实例

1、Cat.java (实体类)

package com.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
@Table(name="tb_cat")
public class Cat {
@Id  //指定该列为主键
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id; @Column(name="name")  //指定属性对应数据库的列名为name
private String name; @Column(name="description")
private String description; @ManyToOne //指定实体类之间的映射关系,多对一
@JoinColumn(name="mother_id") //该属性对应的列,Cat类型,所以mother_id也在同一个Table表里
private Cat mother; @Temporal(TemporalType.TIMESTAMP) //日期类型
@Column(name="createDate")
private Date createDate; //setter、getter方法
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) {
this.mother = mother;
} public Date getCreateDate() {
return createDate;
} public void setCreateDate(Date createDate) {
this.createDate = createDate;
} }

主键尽量使用可以为null值的类型,例如Integer、Long、String等,而不要使用int,long等,因为如果主键为null,则表示该实体类还没有保存到数据库,是一个临时状态,而int、long等原始类型则不具备该功能 。

注解中的@Column,如果属性名与列名一致,column属性可省略。

2、hibernate.cfg.xml(src目录下)

<?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"> <hibernate-configuration> <session-factory>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:@192.168.1.2::orcl</property>
<property name="connection.username">daym2</property>
<property name="connection.password">daym2</property>
<property name="connection.isolation"></property>
<property name="hbm2ddl.auto">create</property> <!-- SQL方言,这边设定的是Oracle -->
<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property> <property name="current_session_context">thread</property>
<mapping class="com.hibernate.bean.Cat" />
</session-factory>
</hibernate-configuration>

hbm2ddl.auto设为create,会自动在数据库中建表,根据前面实体类各个属性的注解,自动建好字段,不需要自己建表

(如果是MySQL数据库,需要自己建一个名为hibernate的数据库,数据表不需要自己建)

3、HibernateUtil.java

package com.hibernate.bean;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration; public class HibernateUtil { private static final SessionFactory sessionFactory; static{
try{
sessionFactory=new AnnotationConfiguration().configure("hibernate.cfg.xml").buildSessionFactory();
}catch(Throwable ex){
throw new ExceptionInInitializerError(ex);
} } public static SessionFactory getSessionFactory(){
return sessionFactory;
} }

4、CatTest.java (Main方法)

package com.hibernate.bean;

import java.awt.Font;
import java.util.Date;
import java.util.List; import javax.swing.JOptionPane; import org.hibernate.Session;
import org.hibernate.Transaction; 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.setMother(mother); //设置与mother母女关系
kitty.setName("Kitty");
kitty.setDescription("Hello Kitty..");
kitty.setCreateDate(new Date()); Cat mimmy=new Cat();
mimmy.setMother(mother);
mimmy.setName("mimmy");
mimmy.setDescription("Hello mimmy..");
mimmy.setCreateDate(new Date()); //开启一个Hibernate对话
Session session=HibernateUtil.getSessionFactory().openSession();
//开启一个事务
Transaction trans=session.beginTransaction(); session.persist(mother);//将mother保存进数据库
session.persist(kitty);
session.persist(mimmy); //查询数据库中的所有猫
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.getMother()==null?"没有记录":cc.getMother().getName()));
result.append("\r\n");
}
trans.commit();
session.close(); //用Swing显示查询结果
JOptionPane.getRootFrame().setFont(new Font("Arial",Font.BOLD,));
JOptionPane.showMessageDialog(null, result.toString()); } }

session.createQuery("from Cat").list();是HQL语言,类似于SQL,不同的是,HQL里使用的是实体类名(Cat类),而Cat实体类再去对应数据表tb_cat

5、log4j.properties (src目录下)

log4j.rootLogger=INFO,stdout
log4j.category.org.hibernate.tool.hbn2ddl=DEBUG
log4j.category.org.hibernate.SQL=DEBUG
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-d{yyyy-MM-dd HH\:mm\:ss,SSS} [%c]-[%p] %m%n

运行CatTest类,效果如下:

Hibernate+Oracle注解式完整实例

看到数据库中也自动生成了表TB_CAT(不区分大小写),数据也插进来了

Hibernate+Oracle注解式完整实例