美文网首页走进Hibernate
第一个Hibernate应用

第一个Hibernate应用

作者: 通俗易懂r | 来源:发表于2017-09-15 18:03 被阅读4次

    本章为实战应用,本来是想跟这书籍上的东西走的。但之前试了下,有些地方走不通,不知道是版本问题还是自己水平不够找不到问题所在。唉不管它了。就按自己的来。不过核心知识流程基本没多大变化,如此这般说来···开始吧

    Hibernate 是java应用和关系型数据库的桥梁,它能进行java 对象和关系数据之间的映射。Hibernate内部封装了通过JDBC访问数据库的操作,向上层应用提供了面向对象的数据访问API。在java应用中使用Hibernate包含以下步骤。

    • (1) 创建Hibernate的配置文件 (这个文件有两种方式 XMl和 java属性文件 键=值形式)
    • (2) 创建持久化类
    • (3) 创建对象-关系映射
    • (4) 通过hibernate APi 访问操作数据库

    下面将通过一个简单例子开始我们本章的捣鼓啦。
    不多说先上图:

    Paste_Image.png

    3.1 创建Hibernate配置文件

    java环境啥的这里就不再说明。 我是使用的Eclipse

    1. 新建工程取名 helloapp 并新建好结构
      简单应用我就不是用web工程了,就用控制台就可以了
    Paste_Image.png

    如图,工程开始就这样。
    解释一下:

    • A 处 entity用于放实体类的(也就是持续化类的) service 用于存放具体和数据打交道的类。类比三层架构的数据访问层
      hibernate.properties 和Hibernate.cfg.xml 文件则是Hibernate的主配置文件。

    两种方式都可以(也可同时使用,一般在属性文件hibernate.properties中存放数据库连接相关的操作数据,在hibernate.cfg.xml文件中存放映射配置)
    properties形式的配置文件和XML格式的配置文件可以同时使用。当同时使用两种类型的配置文件时,XML配置文件中的设置会覆盖properties配置文件的相同的属性。
    这里有两篇可以参考下
    http://www.cnblogs.com/HardWorkinggoup/p/3392033.html
    http://www.cnblogs.com/klguang/p/4769085.html#autoid-0-0-1

    • B 处是lib文件里面存放需要导入的包
    • C 处导入的包(具体导入哪些,去网上搜索一下大把教程这里不细说)
    • D 包导入后需要引入一下

    下面正式开始:
    1.首先在src 根目录下新建 hibernate.properties 文件并写入一下代码

    hibernate.connection.driver_class=com.mysql.jdbc.Driver
    hibernate.connection.url=jdbc:mysql://localhost:3306/yxh?useSSL=true
    hibernate.connection.username=root
    hibernate.connection.password=root
    hibernate.dialect=org.hibernate.dialect.MySQLDialect
    hibernate.show_sql=true
    

    2.然后在创建 hibernate.cfg.xml 文件写入如下内容:

    <?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>    
            <!-- Database connection settings 数据库连接配置 这里注释了,将使用 hibernate.properties属性文件-->
            <!-- <property name="connection.driver_class">com.mysql.jdbc.Driver</property>-->
            <!-- <property name="connection.url">jdbc:mysql://localhost:3306/yxh?useSSL=true</property>-->
            <!-- <property name="connection.username">root</property>-->
            <!-- <property name="connection.password">root</property>-->
              
            <!-- JDBC connection pool (use the built-in) -->
            <!-- <property name="connection.pool_size">1</property> -->
                 
            <!-- SQL dialect SQL 方言-->
            <!--<property name="dialect">org.hibernate.dialect.MySQLDialect</property>-->
                 
            <!-- Echo all executed SQL to stdout SQL语句打印-->
            <!--<property name="show_sql">true</property>-->
                 
            <!-- Enable Hibernate's automatic session context management -->
            <!--<property name="current_session_context_class">thread</property>-->
                 
            <!-- Drop and re-create the database schema on startup -->
            <!-- <property name="hbm2ddl.auto">create</property> -->
                 
            <!-- Disable the second-level cache 禁用二级缓存-->       
            <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
              
            <!-- 映射文件  -->
            <mapping resource="hello/entity/User.hbm.xml"/>
        
        </session-factory>
    </hibernate-configuration> 
    

    为了全面一点,本例子将两种配置文件都使用上,其中 hibernate.properties 负责配置基本的连接信息。而xml文件则配置映射文件 ,在这xml中将连接配置注释了,如果想只使用xml配置可选择打开。

    1. 创建持久化类 User
      该文件放在 hello.entity 包下,内容如下:
    package hello.entity;
    
    public class User {
        private Long id;
        private String name;
        private char sex;
        private int age;
        private String email;
        private String phone;
        private String address;
        
        public User(){}
    
        public Long getId() {
            return id;
        }
    
        public void setId(Long id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public char getSex() {
            return sex;
        }
    
        public void setSex(char sex) {
            this.sex = sex;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        public String getEmail() {
            return email;
        }
    
        public void setEmail(String email) {
            this.email = email;
        }
    
        public String getPhone() {
            return phone;
        }
    
        public void setPhone(String phone) {
            this.phone = phone;
        }
    
        public String getAddress() {
            return address;
        }
    
        public void setAddress(String address) {
            this.address = address;
        }
        
    }
    
    1. 创建数据表
      不多说,我使用的mysql。代码如下
    create table user(
        id      bigint(10) NOT NULL,
        name    varchar(16) NOT NULL,
        sex     char(1) NOT NULL,
        age     int NOT NULL DEFAULT 10,
        email   varchar(256),
        phone   varchar(64),
        address varchar(256),
        primary key(id)
    );
    
    1. 创建对象-关系映射文件
      同样在 hello.entity新建 **User.hbm.xml **
    <?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>
        <class name="hello.entity.User" table="user">
            <id name="id" column="id">
                <generator class="increment"/>
            </id>   
            
            <property name="name" column="name" not-null="true"/>
            <property name="sex" column="sex" type="character" not-null="true"/>
            <property name="age" column="age" type="int" not-null="true"/>
            <property name="email" column="email" type="string"/>       
            <property name="phone" column="phone" type="string"/>
            <property name="address" column="address" type="string"/>
                
        </class>
    </hibernate-mapping>
    
    1. Hibernate API 的使用
      在hello.service 目录下新建 UserService类
    package hello.service;
    
    import java.util.List;
    
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.Transaction;
    import org.hibernate.cfg.Configuration;
    import org.hibernate.query.Query;
    
    import hello.entity.User;
    
    public class UserService {
        public static SessionFactory sessionFactoty;
        static{
            try {           
                //创建Configuration实例 
                Configuration config = new Configuration();
                //加载对象-关系映射文件
                //第一种方式 不采用任何配置文件,直接将连接配置的参数通过Configuration配置
                /*
                config.addClass(hello.entity.User.class)
                .setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver")
                .setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/yxh?useSSL=true")
                .setProperty("hibernate.connection.username", "root")
                .setProperty("hibernate.connection.password", "root")
                .setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect")
                .setProperty("hibernate.show_sql", "true");
                */
                
                //采用hibernate.properties 需要指定映射文件 如:hello.entity.User.class
                //config.addClass(hello.entity.User.class);
                
                
                //采用XML配置文件的形式 不需要指定映射文件,因为在XML文件中就可以直接指定了
                //config.configure("hibernate.cfg.xml");//可以写上,但默认就是加载src下的hibernate.cfg.xml文件
                config.configure();
            
                //创建SessionFactoty实例            
                sessionFactoty = config.buildSessionFactory();
            } catch (RuntimeException e) {
                e.printStackTrace();
                throw e;
            }
        }
        
        //持久化一个对象
        public void saveUser(User user){
            try {
                Session session = sessionFactoty.openSession();
                Transaction tx = session.beginTransaction();
                session.save(user);
                tx.commit();
                session.close();
            } catch (Exception e) {
                // TODO: handle exception
            }
        }
        
        //del
        public void delete(Long id){
            Session session = sessionFactoty.openSession();
            Transaction tx = null;
            try {
                tx = session.beginTransaction();
                session.delete(session.get(User.class, id));
                tx.commit();
            } catch (Exception e) {
                tx.rollback();  
                throw new RuntimeException(e); 
            } finally {
                session.close();  
            }
        }   
        
        public void updateUser(User user){
            Session session = sessionFactoty.openSession();
            Transaction tx = null;
            try {
                tx = session.beginTransaction();
                session.update(user);
                tx.commit();
            } catch (Exception e) {
                tx.rollback();  
                throw new RuntimeException(e); 
            } finally {  
                session.close();  
            }   
        }
        
        public User getById(Long id){
            Session session = sessionFactoty.openSession();
            Transaction tx = null;
            try {
                tx = session.beginTransaction();
                User user = (User) session.get(User.class,id);
                tx.commit();
                return user;
            } catch (Exception e) {
                tx.rollback();  
                throw new RuntimeException(e); 
            } finally {  
                session.close();  
            } 
        }
        
        public List<User> findAll(){
            Session session = sessionFactoty.openSession();
            Transaction tx = null;
            try {
                tx = session.beginTransaction();
                Query query = session.createQuery("from User");
                List<User> list = query.list();
                tx.commit();
                return list;            
            } catch (Exception e) {  
                tx.rollback();  
                throw new RuntimeException(e);  
            } finally{  
                session.close();  
            }
        }
        
        /** 
         * 分页,返回一页的数据列表 
         * @param firstResult 从结果列表中的那个索引开始取数据 
         * @param maxResults 最多取多少条数据 
         * @return  list+count返回的条数 
         */
        public List<User> findAll(int firstResult, int maxResults){
            Session session = sessionFactoty.openSession();
            Transaction tx = null;
            try {
                tx = session.beginTransaction();
                
                Query query = session.createQuery("FROM User");
                query.setFirstResult(firstResult);
                query.setMaxResults(maxResults);
                List<User> list = query.list();
                return list;
            } catch (Exception e) {
                tx.rollback();  
                throw new RuntimeException(e);
            } finally{  
                session.close();  
            }
        }
    }
    
    1. 使用
      在hello.controller包下新建UserTest类
    package hello.controller;
    
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.List;
    
    import hello.entity.User;
    import hello.service.UserService;
    
    public class UserTest {
    
        public static void main(String[] args) {
            UserService bus = new UserService();
            /*
            User user = new User();
            user.setName("肖飞");
            user.setSex('男');
            user.setAge(21);
            user.setEmail("xiaofei@qq.com");
            user.setPhone("15623120863");
            user.setAddress("山海虹桥");
            bus.saveUser(user);
            */
            
            /*
            bus.delete(new Long((long)2));
            */
            
            /*
            DateFormat df = new SimpleDateFormat("HH:mm:ss");
            System.out.println(df.format(new Date()));
            
            User user1 = bus.getById(new Long((long)1));
            user1.setName("凉凉");
            bus.updateUser(user1);
            */
            
            List<User> list = bus.findAll(0,2);
            for(User row:list){
                System.out.println("姓名:" + row.getName() + "\t 年龄:" + row.getAge());
            }
            
        }
    
    }
    

    编码到这里暂时就结束了运行下UserTest,贴张图看看(🙂)

    Paste_Image.png

    打印的获取所有的记录列表。其他的添加、删除啥的就不贴了
    最后贴张完整的目录结构

    Paste_Image.png

    今天就到这儿了,后面在做一些重点知识的讲解 😄

    相关文章

      网友评论

        本文标题:第一个Hibernate应用

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