前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Hibernate文件配置

Hibernate文件配置

作者头像
用户3112896
发布2019-09-26 14:54:41
4130
发布2019-09-26 14:54:41
举报
文章被收录于专栏:安卓圈

ORM : 对象关系映射

映射需要通过XML的配置文件来完成,这个配置文件尽量统一(xxx.hbm.xml) Hibernate核心的配置:必须的配置、可选的配置、映射文件的引入

Configuration的作用:1.加载核心配置文件 2.加载映射文件 SessionFactory:内部维护了Hibernate的连接池和Hibernate的二级缓存,是线程安全的对象,一个项目创建一个对象即可 Session:代表Hibernate和数据库的连接对象,不是线程安全的,所以不能定义成全局的变量 Transaction:Hibernate中管理事务的对象

文件结构

工具类

代码语言:javascript
复制
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtils {
    public static final Configuration cfg;
    public static final SessionFactory sf;

    static {
        cfg = new Configuration().configure();
        sf = cfg.buildSessionFactory();
    }

    public static Session openSession() {
        return sf.openSession();
    }
}

对象类

代码语言:javascript
复制
public class Customer {
    private int id;
    private String name;
    private String source;
    private String industry;
    private String level;
    private String phone;
    private String mobile;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public String getSource() {
        return source;
    }

    public void setSource(String source) {
        this.source = source;
    }

    public String getIndustry() {
        return industry;
    }

    public void setIndustry(String industry) {
        this.industry = industry;
    }

    public String getLevel() {
        return level;
    }

    public void setLevel(String level) {
        this.level = level;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    @Override
    public String toString() {
        return "Customer{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", source='" + source + '\'' +
                ", industry='" + industry + '\'' +
                ", level='" + level + '\'' +
                ", phone='" + phone + '\'' +
                ", mobile='" + mobile + '\'' +
                '}';
    }
}

映射配置文件

代码语言:javascript
复制
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <!--建立类与表的映射-->
    <!--如果类中的属性名和表中的字段名一直,column可以省略-->
    <class name="com.jinke.hibernate.Customer" table="customer">
        <!--建立类中的属性与表中的主键对应-->
        <id name="id" column="id">
            <generator class="native"/>
        </id>

        <!--建立类中的普通属性和标的字段的对应-->
        <property name="name" column="name" length="32" type="string" not-null="true" unique="true"/>
        <property name="source" column="source"/>
        <property name="industry" column="industry"/>
        <property name="level" column="level"/>
        <property name="phone" column="phone"/>
        <property name="mobile" column="mobile"/>
    </class>
</hibernate-mapping>

总配置类

代码语言:javascript
复制
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!--必须配置===============-->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/spring_database?characterEncoding=utf8
        </property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">1234</property>
        <!--配置Hibernate的方言-->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

        <!--可选配置===============-->
        <!--打印sql-->
        <property name="hibernate.show_sql">true</property>
        <!--格式化sql-->
        <property name="hibernate.format_sql">true</property>
        <!--自动创建表-->
        <property name="hibernate.hbm2ddl.auto">update</property>

        <!--映射文件的引用===============-->
        <mapping resource="com/jinke/hibernate/Customer.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

测试类

代码语言:javascript
复制
import com.jinke.hibernate.utils.HibernateUtils;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.NativeQuery;
import org.hibernate.query.Query;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;

public class HibernateDemo1 {

    @Test
    public void demo() {
       /* //1.加载hibernate核心配置文件
        Configuration configuration = new Configuration().configure();
        //2.创建一个sessionfactory对象:类似于jdbc中连接池
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        //3.通过sessionFactory获取到session对象:类似于jdbc中connection
        Session session = sessionFactory.openSession();*/

        Session session = HibernateUtils.openSession();
        //4.手动开启事务
        Transaction transaction = session.beginTransaction();
        //5.编写代码

        Customer customer = new Customer();
        customer.setName("王东");
        //保存
        session.save(customer);


        //6.事务提交
        transaction.commit();
        //7.资源释放
        session.close();
        /*sessionFactory.close();*/
    }

    /**
     * get方法:(一般用这种)
     * 采用立即加载,执行到这行代码的时候,马上发送SQL语句去查询
     * 查询后返回的是真是对象本身
     * 查询一个找不到的对象会返回null
     * <p>
     * load方法:
     * 采用延迟加载(懒加载),执行到这行代码的时候,不会发送SQL语句,当真正使用项目的时候才会发送SQL语句
     * 查询后返回的是代理对象
     * 查询一个找不到的对象会抛出一个异常
     */
    @Test
    //查询
    public void demo2() {
        Session session = HibernateUtils.openSession();
        Transaction tx = session.beginTransaction();
        //使用get方法
        Customer customer = session.get(Customer.class, 1);
        System.out.println(customer);

        //使用load方法
        /*Customer load = session.load(Customer.class, 2);
        System.out.println(load);*/

        tx.commit();
        session.close();
    }

    @Test
    //修改
    public void demo3() {
        Session session = HibernateUtils.openSession();
        Transaction tx = session.beginTransaction();

        //直接创建对象,进行修改
        /*Customer customer = new Customer();
        customer.setId(1);
        customer.setName("李达");
        session.update(customer);*/
        //先查询,再修改(一般用这种)
        Customer customer = session.get(Customer.class, 1);
        customer.setName("张三");
        session.update(customer);

        tx.commit();
        session.close();
    }

    @Test
    //删除
    public void demo4() {
        Session session = HibernateUtils.openSession();
        Transaction tx = session.beginTransaction();

        //直接创建对象,进行删除
        /*Customer customer = new Customer();
        customer.setId(1);
        session.delete(customer);*/
        //先查询,再删除(一般用这种)  级联删除
        Customer customer = session.get(Customer.class, 1);
        session.delete(customer);

        tx.commit();
        session.close();
    }

    @Test
    //保存或更新
    public void demo5() {
        Session session = HibernateUtils.openSession();
        Transaction tx = session.beginTransaction();

        Customer customer = new Customer();
        /*customer.setName("李飞");
        session.saveOrUpdate(customer);*/

        customer.setId(3);
        customer.setName("如花");
        session.saveOrUpdate(customer);

        tx.commit();
        session.close();
    }

    @Test
    //查询所有
    public void demo6() {
        Session session = HibernateUtils.openSession();
        Transaction tx = session.beginTransaction();
        //接收HQL:hibernate query language 面向对象的查询语言
        Query query = session.createQuery("from Customer");
        List<Customer> list = query.list();
        for (Customer customer : list) {
            System.out.println(customer);
        }

        //接收sql:
        NativeQuery sqlQuery = session.createSQLQuery("select * from customer");
        List<Object[]> sqlList = sqlQuery.list();
        for (Object[] objects : sqlList) {
            System.out.println(Arrays.toString(objects));
        }

        tx.commit();
        session.close();
    }
}

结果在MySql Workbench里看

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2019-06-20,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 安卓圈 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档