美文网首页
2018-09-27:框架之Hibernate初步

2018-09-27:框架之Hibernate初步

作者: 神坛下的我 | 来源:发表于2018-09-27 22:00 被阅读0次

框架

框指的是范围 别人定义好的XML(可扩展的标记语言)
架指的是支撑(主体结构) 别人定义好的JAR中类和方法
XML和html一样都是SGML的子集,xml更为严格:

  1. 标签必须成对出现,必须要有结束符
  2. 如果嵌套不正确,无法执行
  3. 除了可以显示数据,还可以存储数据
    dtd :数据定义 规定数据的结构(元素之间的顺序 数量 上下结构)
    规定了元素的顺序(,)
    规定了元素的数量:必须出现1次 标签名;
    0-1次 标签名?;
    0-n次 标签名*;
    xsd

xstl xpath xlink

Hibernate

冬眠,希望程序员不关心具体的数据库的构成与实现,而只关心业务逻辑需要的
数据或者对应的类,也不关心sql语句的拼写


path 操作系统知道java程序在哪里
buildpath 项目知道需要的java类在哪里
classpath 运行的程序知道需要的java类(class文件)


驱动:标准行为和非标准行为之间的转换准则
JDBC驱动完成sql语句在非数据库环境下进行操作的工作。

项目Hibernate配置

切换到Hibernate视图
添加add configuration
选择classpath标签的jar包
选择main标签的配置,包括project-本次支持的项目,database connection-
new新建一个 填好jdbc相关url,name,password
切换回java视图选择项目- run- 生成hibernate code
新建configuration
选择hibernate连接配置
output 选择项目src
package生成代码所在的包名
reveng.xml 生成过程的配置文件,取消四个勾,因为生成的set不如list好用
勾选exporters 勾选 domain code,hibernate xml,ejb3 annotation

  • hibernateSessionFactory的运行原理
    读取配置文件hibernate.cfg.xml文件中的内容,通过特定config类加载成对象。
    java的反射机制:如何从字符串到对象,名称关联 容器(环境)帮你生成对象。

  • Hibernate的运转原理

  1. JVM将所有的jar装载
  2. HibernateSessionFactory.getSession
    1.configuration.configure(configFile);将主配置文件加载,将主配置文件的
    类的对象全部实例化(告知名字即可new)。
    2.产生了session连接对象。
    3.通过session发送查询要求。
    4.通过查询的返回值获得已经被封装好的对象,对象再封装成集合。

show_sql ->true

session.close();


dao.HibernateSessionFactory.java

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

/**
 * Configures and provides access to Hibernate sessions, tied to the
 * current thread of execution.  Follows the Thread Local Session
 * pattern, see {@link http://hibernate.org/42.html }.
 */
public class HibernateSessionFactory {

    /** 
     * Location of hibernate.cfg.xml file.
     * Location should be on the classpath as Hibernate uses  
     * #resourceAsStream style lookup for its configuration file. 
     * The default classpath location of the hibernate config file is 
     * in the default package. Use #setConfigFile() to update 
     * the location of the configuration file for the current session.   
     */
    //指定配置文件
    private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
     //线程安全,由一个线程容器 带同步 1.只new出了容器,容器是空的没有session
    private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    //构造配置类
    private  static Configuration configuration = new Configuration();
    //声明连接工厂
    private static org.hibernate.SessionFactory sessionFactory;
    private static String configFile = CONFIG_FILE_LOCATION;

    private HibernateSessionFactory() {
    }
    
    /**
     * Returns the ThreadLocal Session instance.  Lazy initialize
     * the <code>SessionFactory</code> if needed.
     *
     *  @return Session
     *  @throws HibernateException
     */
    //用户执行首先以静态的方式访问getSession方法,由于是静态,所以这个类静态的成员变量已经执行过了,所以已经有一些对象生成了
    public static Session getSession() throws HibernateException {
        //2.容器中有session吗?
        Session session = (Session) threadLocal.get();
//如果session为空或者没有打开,检查sessionFactory是否存在,不存在就重建,保证sessionFactory存在的前提下,用sessionFactory打开连接
        if (session == null || !session.isOpen()) {
            if (sessionFactory == null) {
                rebuildSessionFactory();
            }
            session = (sessionFactory != null) ? sessionFactory.openSession()
                    : null;
            //把session放到线程安全容器中
            threadLocal.set(session);
        }

        return session;
    }

    /**
     *  Rebuild hibernate session factory
     *
     */
    //读取配置文件,如果sessionFactory build成功 由于sessionFactory为成员变量,其它方法就可以访问了
    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;
    }

}

entity.Student.java

import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.UniqueConstraint;

/**
 * Student generated by hbm2java
 */
@Entity
@Table(name = "student", catalog = "gxa", uniqueConstraints = @UniqueConstraint(columnNames = "bedno"))
public class Student implements java.io.Serializable {

    private String sno;
    private String name;
    private String sex;
    private Integer high;
    private Date birthday;
    private Date jointime;
    private String homephone;
    private String bedno;
    private String address;
    private Float avgscore;
    private String area;
    private String cno;
    private String imgsrc;
    private String pwd;

    public Student() {
    }

    public Student(String sno) {
        this.sno = sno;
    }

    public Student(String sno, String name, String sex, Integer high, Date birthday, Date jointime, String homephone,
            String bedno, String address, Float avgscore, String area, String cno, String imgsrc, String pwd) {
        this.sno = sno;
        this.name = name;
        this.sex = sex;
        this.high = high;
        this.birthday = birthday;
        this.jointime = jointime;
        this.homephone = homephone;
        this.bedno = bedno;
        this.address = address;
        this.avgscore = avgscore;
        this.area = area;
        this.cno = cno;
        this.imgsrc = imgsrc;
        this.pwd = pwd;
    }

    @Id

    @Column(name = "sno", unique = true, nullable = false, length = 8)
    public String getSno() {
        return this.sno;
    }

    public void setSno(String sno) {
        this.sno = sno;
    }

    @Column(name = "name", length = 20)
    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Column(name = "sex", length = 4)
    public String getSex() {
        return this.sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    @Column(name = "high")
    public Integer getHigh() {
        return this.high;
    }

    public void setHigh(Integer high) {
        this.high = high;
    }

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "birthday", length = 19)
    public Date getBirthday() {
        return this.birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "jointime", length = 19)
    public Date getJointime() {
        return this.jointime;
    }

    public void setJointime(Date jointime) {
        this.jointime = jointime;
    }

    @Column(name = "homephone", length = 12)
    public String getHomephone() {
        return this.homephone;
    }

    public void setHomephone(String homephone) {
        this.homephone = homephone;
    }

    @Column(name = "bedno", unique = true, length = 6)
    public String getBedno() {
        return this.bedno;
    }

    public void setBedno(String bedno) {
        this.bedno = bedno;
    }

    @Column(name = "address", length = 50)
    public String getAddress() {
        return this.address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Column(name = "avgscore", precision = 12, scale = 0)
    public Float getAvgscore() {
        return this.avgscore;
    }

    public void setAvgscore(Float avgscore) {
        this.avgscore = avgscore;
    }

    @Column(name = "area", length = 10)
    public String getArea() {
        return this.area;
    }

    public void setArea(String area) {
        this.area = area;
    }

    @Column(name = "cno", length = 6)
    public String getCno() {
        return this.cno;
    }

    public void setCno(String cno) {
        this.cno = cno;
    }

    @Column(name = "imgsrc", length = 50)
    public String getImgsrc() {
        return this.imgsrc;
    }

    public void setImgsrc(String imgsrc) {
        this.imgsrc = imgsrc;
    }

    @Column(name = "pwd", length = 10)
    public String getPwd() {
        return this.pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

}
...还有n多个POJO类...

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
                                         "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
 <session-factory name="">
  <property name="hibernate.bytecode.use_reflection_optimizer">false</property>
  <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="hibernate.connection.password">123456</property>
  <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/gxa</property>
  <property name="hibernate.connection.username">root</property>
  <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
  <property name="hibernate.search.autoregister_listeners">true</property>
  <property name="hibernate.validator.apply_to_ddl">false</property>
  <property name="hibernate.cache.use_query_cache">false</property>
  <property name="show_sql">true</property>
  <mapping class="gxa.entity.Student"/>
  <mapping class="gxa.entity.Teacher"/>
 </session-factory>
</hibernate-configuration>

hibernate.reveng.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd" >

<hibernate-reverse-engineering>
  <table-filter match-catalog="gxa" match-name="student"/>
</hibernate-reverse-engineering>

Test.java

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.Restrictions;

import gxa.dao.HibernateSessionFactory;
import gxa.entity.Student;
import gxa.entity.Teacher;

public class Test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //session 数据库连接会话 由hibernateSessionFactory 提供
        Session session = HibernateSessionFactory.getSession();
//      List<Teacher> teachers = session.createQuery("From Teacher").list();
//      for(Teacher teacher : teachers){
//          System.out.println(teacher.getTname());
//      }
        
        //1.hql条件查询
//      Query query = session.createQuery
//              ("From Teacher where tno=? and sex = ?");
//      query.setString(0, "0001");
//      query.setString(1, "男");
//      Teacher teacher = (Teacher)query.uniqueResult();
//      System.out.println(teacher.getTname());
        
        //找出和陈涛老师是同乡的学生名单,多对象查询 使用对象名指定属性名
        
//      Query query = session.createQuery(
//              "FROM Student s "
//              + "WHERE s.area  = "
//              + "(SELECT t.area FROM Teacher t WHERE tname = '陈涛')"
//              );
//      List<Student> students =query.list();
//      for(Student student:students){
//          System.out.println(student.getName());
//      }
        
        //2 .qc条件查询
//      Criteria ca = session.createCriteria(Student.class);
//      ca.add(Restrictions.eq("sex","男")).
//      add(Restrictions.gt("high",172));
//      List<Student> students =ca.list();
//      for(Student student:students){
//          System.out.println(student.getName()+ " "+student.getHigh());
//      }
        
        //3.qbe example  叫李斯的学生其它字段值是多少
//      Student student = new Student();
//      student.setName("李斯");
//      //根据李斯这个学生创建一个查询例子
//      Example example = Example.create(student);
//      Criteria ca = session.createCriteria(Student.class);//按student类查询
//      ca.add(example);
//      Student student1 = (Student)ca.uniqueResult();
//      System.out.println(student1.getSex());
        
//      4.按主键查询 get load
        //1. 单独的get 和 load 如果只执行了get 要查询数据库  只执行load不查询数据库,只有load之后访问load得到的结果中的具体属性时才发送
        //2. get 和 load 连续执行  只发送一次,但如果中间 清除了session 第二次查询会重新发送
        Transaction tran2 = session.beginTransaction();
        Student student1 = session.load(Student.class, "09010101");
        System.out.println(student1.getName());
        System.out.println("tt");
        tran2.commit();
        session.clear();

        
        Transaction tran1 = session.beginTransaction();
        Student student2 = session.load(Student.class, "09010101");
        System.out.println(student2.getName());
        tran1.commit();
        
        session.close();
        
        

//      

        
        
    }

}


反射测试:
TestReflect.java

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import gxa.entity.Teacher;

public class TestReflect {
    public static void main(String[] args) {
        try {
            //class.forName 通过名字找已认识类中有没有 匹配
            Class clazz = Class.forName("gxa.entity.Teacher");
            //为什么有类 就可以知道 类的成员变量和成员方法呢 ,因为jvm加载类的时候就知道了
            Field[] fds = clazz.getDeclaredFields();
            for(Field fd :fds){
                System.out.println(fd.getName());
            }
            Method[] methods = clazz.getDeclaredMethods();
            for(Method method :methods){
                System.out.println(method.getName());
            }
            Teacher teacher = new Teacher();
            teacher.setTname("张三");//有一个对象叫张三,这句修改值 申请虚拟机修改变量值
            //通过这个对象知道 他是什么类
            Class clazzTeacher = teacher.getClass();
            //通过类找指定的 字段
            Field fdName = clazzTeacher.getDeclaredField("tname");
            //对象的设置被修改是允许的,因为类只是对象生成的模板,对象只是参照类的定义初始生成
            fdName.setAccessible(true);
            fdName.set(teacher, "李四");//虚拟机直接修改值
            System.out.println(teacher.getTname());
            
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        

        
        

    }
}

TestReflect2.java

import java.lang.reflect.Field;

import gxa.entity.Teacher;

public class TestReflect2 {
    public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
        String[] strs = {"tno:0001","tname:zhangsan","area:成都","sex:女"};
        
        Teacher teacher = new Teacher();
        Class clazzTeacher = teacher.getClass();
        for(String str:strs){
            String[] keyAndvalue = str.split(":");
            String fdname = keyAndvalue[0];
            String fdvalue = keyAndvalue[1];
        
           //如果要输入的字段名和  对象的字段名匹配就赋值
           for(Field fd : clazzTeacher.getDeclaredFields()){
             if(fd.getName().equals(fdname)){
                 fd.setAccessible(true);
                 fd.set(teacher, fdvalue);
                 break;
             }
           }
        
        }
        
        System.out.println(teacher.getTname() +"   "
        + teacher.getArea()+ "  "+ teacher.getSex());
        
    }
}

静态测试:
TestStatic.java

public class TestStatic {
     static String x = test();
     static{
         System.out.println("1静态区域");
     }
     static String  test(){
         System.out.println("2静态方法");
         return "aa";
     }
     
    public TestStatic() {
        super();
        System.out.println("3构造方法");
    }

    public static void main(String[] args) {
        //静态方法需要显示调用,但静态变量和静态区域 类出现就需要初始化,对象是构造方法初始化,静态变量静态区域先于构造执行
         new TestStatic();
        
    }

}

相关文章

网友评论

      本文标题:2018-09-27:框架之Hibernate初步

      本文链接:https://www.haomeiwen.com/subject/navyoftx.html