• Hibernate的入门使用


    数据在各个层次之间流转,在流转过程中会发生数据类型转换等一系列的交互问题。java与html的交互解决方案是struts2提供的OGNL(对象导航图语言),而java与数据库之间的技术解决方案是ORM(对象关系映射)。

    什么是ORM

    对象关系映射:Object relation mapping
    1.对象:指的是java对象,是实体bean
    2.关系:关系只是数据库,sqlserver,mysql,oracle属于关系型数据库,操作关系型数据库用的是sql语言,但是sql有着明显的缺点,一次只能执行一条语句,没有什么基本的逻辑判断
    3.映射:java中对象的属性与数据库中的表字段之间一一对应(包含一对一,一对多,多对一,多对多)。

    ORM需要满足的条件

    有类属性和·表字段一一映射的关系
    将关系模型(数据库)的操作转化成对对象模型(pojo)的操作
    hibernate的优缺点

    好处:不要程序自己编写sql,简化了开发,提高了开发速度,hibernate入门门槛低,上手快。
    缺点:由hibernate自动生成的sql是标准的sql,优化难度大,失去了灵活性,对程序员要求较高,要懂一定的O/R映射。
    快速入手hibernate案列(maven)

    在pom.xml中导入相关的jar’包
    <dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>3.6.5.Final</version>
    </dependency>

    1
    2
    3
    4
    5
    6
    如果不能正常创建则需要导入其他包
    1
    <--hibenate核心包-->
    <dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>3.6.8.Final</version>
    </dependency>
    <--单元测试包(可不导入)-->
    <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.7</version>
    <scope>test</scope>
    </dependency>
    <-- Javassit其实就是一个二方包,提供了运行时操作Java字节码的方法-->
    <dependency>
    <groupId>org.javassist</groupId>
    <artifactId>javassist</artifactId>
    <version>3.13.0-GA</version>
    </dependency>
    <-- 并发访问处理端口的工具包。-->
    <dependency>
    <groupId>backport-util-concurrent</groupId>
    <artifactId>backport-util-concurrent</artifactId>
    <version>2.2</version>
    </dependency>
    <-- 日志文件包-->
    <dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging</artifactId>
    <version>1.1.1</version>
    </dependency>
    <--纯Java的进程内缓存框架-->
    <dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
    <version>1.2.3</version>
    </dependency>
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    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>

    <!--Database connection settings -->
    <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
    <property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
    <property name="connection.username">scott</property>
    <property name="connection.password">tiger</property>


    <property name="javax.persistence.validation.mode">none</property>
    <!-- sql dialect方言 -->
    <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
    <!--如果不存在该表,hibernate将自动生成该表 -->
    <property name="current_session_context_class">thread</property>
    <!--打印sql语句 -->
    <property name="show_sql">true</property>
    <mapping resource="com/it/bean/Student.hbm.xml"/>

    </session-factory>
    </hibernate-configuration>

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    3.*.xml映射文件

    先写一个实体bean
    package com.it.bean;

    public class Student {
    private String stu_id;
    private String stu_name;
    private String stu_sex;
    private String stu_birth;
    private String stu_addr;
    public String getStu_id() {
    return stu_id;
    }
    public void setStu_id(String stu_id) {
    this.stu_id = stu_id;
    }
    public String getStu_name() {
    return stu_name;
    }
    public void setStu_name(String stu_name) {
    this.stu_name = stu_name;
    }
    public String getStu_sex() {
    return stu_sex;
    }
    public void setStu_sex(String stu_sex) {
    this.stu_sex = stu_sex;
    }
    public String getStu_birth() {
    return stu_birth;
    }
    public void setStu_birth(String stu_birth) {
    this.stu_birth = stu_birth;
    }
    public String getStu_addr() {
    return stu_addr;
    }
    public void setStu_addr(String stu_addr) {
    this.stu_addr = stu_addr;
    }
    public Student(String stu_id, String stu_name, String stu_sex, String stu_birth, String stu_addr) {
    super();
    this.stu_id = stu_id;
    this.stu_name = stu_name;
    this.stu_sex = stu_sex;
    this.stu_birth = stu_birth;
    this.stu_addr = stu_addr;
    }
    public Student() {
    super();
    // TODO Auto-generated constructor stub
    }
    public Student(String stu_id, String stu_name) {
    super();
    this.stu_id = stu_id;
    this.stu_name = stu_name;
    }

    }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    与之对应的映射文件
    <?xml version="1.0"?>
    <!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
    <hibernate-mapping package="com.it.bean">
    <class name="Student" table="stuinfo">
    <id name="stu_id" column="stu_id">
    <!-- 主键生成策略 -->
    <generator class="assigned"></generator>
    </id>
    <property name="stu_name" column="stu_name"></property>
    <property name="stu_sex" column="stu_sex"></property>
    <property name="stu_birth" column="stu_birth"></property>
    <property name="stu_addr" column="stu_addr"></property>
    </class>
    </hibernate-mapping>

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    dao层的书写
    BaseDao
    package com.it.dao;

    import java.util.List;

    import org.hibernate.Query;
    import org.hibernate.Session;


    public class BaseDao<E>{
    private Session session;
    public BaseDao(Session session){
    this.session=session;
    }
    public void add(E e){
    session.save(e);
    }
    public void delete(E e){
    session.delete(e);
    }
    public void update(E e){
    session.update(e);
    }
    public List<E> finbBySplit(int currentPage,int currentSize,String hql,String...params){
    Query query=session.createQuery(hql);
    //给问号占位符赋值
    for (int i = 0; i < params.length; i++) {
    query.setString(i, params[i]);
    }
    //分页参数
    int first=(currentPage-1)*currentSize;
    query.setFirstResult(first);
    query.setMaxResults(currentSize);
    //查询
    return query.list();
    }
    }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    StudentDao层的书写
    package com.it.dao;

    import java.util.List;

    import org.hibernate.Session;

    import com.it.bean.Student;

    public class StudentDao extends BaseDao<Student>{

    public StudentDao(Session session) {
    super(session);
    // TODO Auto-generated constructor stub
    }
    public void add(Student stu){
    super.add(stu);
    }
    public void delete(Student stu){
    super.delete(stu);
    }
    public void update(Student stu){
    super.update(stu);
    }
    public List<Student> find(int currentPage,int currentSize,Student stu){
    String hql="from Student stu where stu.stu_id like ? and stu.stu_name like ? and stu.stu_sex like ? and stu.stu_birth like ? and stu.stu_addr like ? ";
    String []params={"%"+stu.getStu_id()+"%","%"+stu.getStu_name()+"%","%"+stu.getStu_sex()+"%","%"+stu.getStu_birth()+"%","%"+stu.getStu_addr()+"%"};
    return super.finbBySplit(currentPage, currentSize, hql, params);
    }

    }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    此时便可测试了
    @Test
    public void add(){
    SessionFactory sessionFactory=null;
    Session session=null;
    Transaction tx=null;
    try {
    //创建sessionfactory
    sessionFactory=new Configuration().configure().buildSessionFactory();
    //创建session回话---得到线程本身的回话
    session=sessionFactory.getCurrentSession();
    //开启事务
    tx=session.beginTransaction();
    //添加数据
    Student stu=new Student("0000","沈浪","男","87","北京");
    // session.save(stu);
    //修改数据
    // stu.setStu_name("沈万三");
    // session.update(stu);
    //删除数据
    // session.delete(stu);
    //提交事务
    //按照id查询一条数据
    // Student stu1=(Student)session.get(Student.class, "0000");
    // System.out.println(stu1.getStu_name());

    //hql的使用
    //查询所有信息
    /*String hql="from Student where stu_id like '%2%'";
    Query query=session.createQuery(hql);
    List<Student> list=query.list();
    for (Student student : list) {
    System.out.println(student.getStu_name());
    }*/

    //返回vo对象
    /*String hql="select new Student(stu_id,stu_name) from Student where stu_id like '%2%'";
    Query query=session.createQuery(hql);
    List<Student> list=query.list();
    for (Student student : list) {
    System.out.println(student.getStu_name());
    }*/

    //返回map类型的参数
    /*String hql="select new map(count(*) as ct,max(stu_id) as maxid) from Student";
    Query query=session.createQuery(hql);
    Map<String,Object> map=(Map<String,Object>)query.uniqueResult();
    System.out.println(map.get("ct"));*/

    //占位符? :
    /*String hql="from Student where stu_id like ?";
    Query query=session.createQuery(hql);
    query.setString(0, "%2%");
    List<Student> list=query.list();
    for (Student student : list) {
    System.out.println(student.getStu_name()+"=========");
    }*/

    //:占位符
    /*String hql="from Student where stu_sex=:uid";
    Map<String,String> params=new HashMap<String,String>();
    params.put("uid","1");
    Query query=session.createQuery(hql);
    //为参数赋值
    for(String key:params.keySet()){
    System.out.println(key+"==========");
    query.setString(key,params.get(key));
    }
    List<Student> list=query.list();
    for (Student student : list) {
    System.out.println(student.getStu_name()+"+++++++");
    }*/

    //返回number类型的参数
    /*String hql="select count(*) from Student";
    Query query=session.createQuery(hql);
    Number ct=(Number)query.uniqueResult();
    System.out.println(ct.intValue());*/

    //模糊搜素
    /*Student stu1=new Student("1","武");
    String[] params={"%"+stu1.getStu_id()+"%","%"+stu1.getStu_name()+"%"};
    String hql="from Student where stu_id like ? and stu_name like ?";
    // String hql="from Student where stu_id like '%1%' and stu_name like '%武%'";
    Query query=session.createQuery(hql);
    //为?号赋值
    for (int i = 0; i < params.length; i++) {
    query.setString(i,params[i]);
    System.out.println(params[i]);
    }
    System.out.println(hql);
    System.out.println(query.list().size());*/


    //hibernate分页
    String hql="from Student where stu_id like '%2%'";
    Query query=session.createQuery(hql);
    int currentPage=1;
    int pageSize=4;
    int startPage=(currentPage-1)*pageSize;
    query.setFirstResult(startPage); //开始显示的位置
    query.setMaxResults(pageSize); //显示最大数据数
    System.out.println(query.list().size());

    tx.commit();
    } catch (Exception e) {
    // TODO: handle exception
    e.printStackTrace();
    //事务回滚
    tx.rollback();
    }
    }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    此刻一个简单的demo变创建成功了
    --------------------- 

  • 相关阅读:
    vue异步组件
    vue-awesome-swiper的使用
    自定义button组件时slot的使用
    axios拦截器的简单使用
    vue静态类名和动态类名绑定的几种方式
    快速知道所有元素的边框
    【转】CICD工具
    mocha学习(四)为项目开发一个BDD测试
    mocha学习(三)hook 机制 和 测试技巧
    mocha学习(二)mocha接口
  • 原文地址:https://www.cnblogs.com/hyhy904/p/10971045.html
Copyright © 2020-2023  润新知