JavaWeb 第20章 hibernate入门

来源:互联网 发布:淘宝哪家手机壳质量好 编辑:程序博客网 时间:2024/06/03 16:18

1.hibernate概述

orm:把java对象与关系数据库之间建立某种映射关系,实现直接存取java对象

2.第一个hibernate程序

1.添加hibernate特性
2.添加hibernatejar包
3.配置Cat实体类

package hibernate.bean;import java.util.Date;import javax.persistence.*;//配置Cat实体类//实体类是指与数据库有映射关系的java类@Entity//表示该类可以被hibernate持久化@Table(name="tb_cat")//指定该entity对应的数据库表名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="method_id")//该属性对于的列    private Cat mother;    @Temporal(TemporalType.TIMESTAMP)//日期类型    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) {        this.mother = mother;    }    public Date getCreateDate() {        return createDate;    }    public void setCreateDate(Date createDate) {        this.createDate = createDate;    }}

4.修改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>    <!-- jdbc配置代码 -->        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>        <property name="connection.url">jdbc:mysql://localhost:3306/hibernate?characterEncoding=UTF-8</property>        <property name="connection.username">root</property>        <property name="connection.password">123456</property>        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>        <!-- 指定使用MYSQL数据库格式的SQL语句 -->        <property name="dialet">org.hibernate.dialect.MySQLDialect</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="hibernate.bean.Cat"/>    </session-factory></hibernate-configuration>

5.修改hibernate工具类
HibernateSessionFactory

package hibernate.util;import org.hibernate.HibernateException;import org.hibernate.Session;import org.hibernate.cfg.Configuration;import org.hibernate.cfg.AnnotationConfiguration;public class HibernateSessionFactory {    private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";    private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();     //XML配置时候使用    private  static Configuration configuration = new Configuration();    //@配置时候使用    //private static Configuration configuration2=new AnnotationConfiguration();    private static org.hibernate.SessionFactory sessionFactory;    private static String configFile = CONFIG_FILE_LOCATION;    static {        try {            configuration.configure(configFile);            sessionFactory = configuration.buildSessionFactory();        } catch (Exception e) {            System.err                    .println("%%%% Error Creating SessionFactory %%%%");            e.printStackTrace();        }    }    private HibernateSessionFactory() {    }    public static Session getSession() throws HibernateException {        Session session = (Session) threadLocal.get();        if (session == null || !session.isOpen()) {            if (sessionFactory == null) {                rebuildSessionFactory();            }            session = (sessionFactory != null) ? sessionFactory.openSession()                    : null;            threadLocal.set(session);        }        return session;    }    /**     *  Rebuild hibernate session factory     *     */    public static void rebuildSessionFactory() {        try {            configuration.configure(configFile);            sessionFactory = configuration.buildSessionFactory();        } catch (Exception e) {            System.err                    .println("%%%% Error Creating SessionFactory %%%%");            e.printStackTrace();        }    }    /**     *  Close the single hibernate session instance.     *     *  @throws HibernateException     */    public static void closeSession() throws HibernateException {        Session session = (Session) threadLocal.get();        threadLocal.set(null);        if (session != null) {            session.close();        }    }    /**     *  return session factory     *     */    public static org.hibernate.SessionFactory getSessionFactory() {        return sessionFactory;    }    /**     *  return session factory     *     *  session factory will be rebuilded in the next call     */    public static void setConfigFile(String configFile) {        HibernateSessionFactory.configFile = configFile;        sessionFactory = null;    }    /**     *  return hibernate configuration     *     */    public static Configuration getConfiguration() {        return configuration;    }}

hibernateUtil.java

package hibernate.util;import org.hibernate.SessionFactory;import org.hibernate.cfg.AnnotationConfiguration;public class HibernateUtil {    private static final SessionFactory sessionFactory;//单例模式的sessionFactory    static{        try{            sessionFactory=new AnnotationConfiguration().configure("hiernate.cfg.xml").buildSessionFactory;        }catch (Throwable e) {            System.err.println("Initial SessionFactory create failed");            throw new ExceptionInInitializerError(e);        }    }    public static SessionFactory getSessionFactory(){        return sessionFactory;    }}

6.初始化mysql数据库

hbm2ddl.auto取值create加载sessionFactory时候创建表 原表存在则删除create-drop 加载sessionFactory时候创建表结构,卸载sessionFactory删除表结构update 加载sessionFactory检查表结构 与entity不一致则更新validate 加载sessionFactory时候检查表结构

7.配置log4j,输出日志
log4j.properties

log4j.rootLogger=INFO, stdout #日志级别为INFO,输出到stdoutlog4j.category.org.hibernate.tool.hbm2ddl=DEBUG#设置hbm2ddl级别为debuglog4j.category.org.hibernate.SQL=DEBUG#设置sql级别为debuglog4j.appender.stdout=org.appache.log4j.ConsoleAppender#设置stdoutlog4j.appender.stdout.layout=org.apache.log4j.PatternLayout#设置stdout的布局log4j.appender.stdout.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} [%c]-[%p] %m%n

8.执行hibernate程序

import java.awt.Font;import java.util.Date;import java.util.List;import javax.swing.JOptionPane;import org.hibernate.Hibernate;import org.hibernate.Session;import org.hibernate.Transaction;import hibernate.bean.Cat;import hibernate.util.HibernateUtil;public 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());        Session session=HibernateUtil.getSessionFactory().openSession();//开启一个hibernate对话        Transaction trans=session.beginTransaction();//开启一个事务        session.persist(mother);//将mother保存到数据库        session.persist(kitty);        session.persist(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.getMother()==null?"没有记录":cc.getMother().getName()));            result.append("\r\n");        }        trans.commit();//提交事务        session.close();        JOptionPane.getRootFrame().setFont(new Font("Arial",Font.BOLD,14));        JOptionPane.showMessageDialog(null, result.toString());    }}
0 0
原创粉丝点击