Hibernate 入门1

Related

  • cst.zju Java-OOP course week 2
  • connect java code with mysql database
  • Design Pattern -- Factory pattern
  • Service and Dao
  • the usage of Junit,Maven
    Materials
    my code on github
    Youtube Course on Hibernate

Overview

简单地说,hibernate 完成了一种映射操作,就是将关系型数据库中表映射成为了一个java对象,这样就为代码操作实际的数据库提供了很多方便.
hibernate是对JDBC的进一步封装,完成从对象(Object)到关系(Relation)的映射(Mapping),也就是一个ORM框架.

Hibernate 入门1_第1张图片
copied

这里一个图很清楚表达了hibernate的组件构成.在配置文件中写的xml被Configure实例对象读取之后可以创建sessionFactory对象,用这个工厂对象可以进一步创建Session,创建连接,操作数据库.
配置文件(默认为hibernate.cfg.xml)中申明了一些必要的配置信息,如数据库的地址,端口号,数据库用户名,密码,映射类等等信息.

Code

Dao层用来操作数据库(增删改查)的基本操作,这几乎是web应用程序所默认的,使用课堂上的例子,来完成一个对user(有三个字段,自增的id,name(char(30)), 和address(char(50))表的操作.
我们建立了一个User类,这个User类的字段和user表中的字段一致,并且有getter/setter方法

package cst.zju.edu.alexsun.model;

import javax.persistence.*;

@Entity
@Table(name = "user")
public class User {
    @Id
    @Column(name="id")
    @GeneratedValue
    private int id;

    @Column(name="name")
    private String name;

    @Column(name="address")
    private String address;

    public User(){
        this.id = 6666;
        this.name = "6666";
        this.address = "6666";
    }
    public User(int id, String name, String address){
        this.name = name;
        this.id = id;
        this.address = address;
    }

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

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

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

    @Id
    @GeneratedValue
    public int getId(){
        return id;
    }

    public String getName(){
        return this.name;
    }

    public String getAddress(){
        return this.address;
    }

    @Override
    public String toString() {
        return "student id: " + id + " name: "+name+" address in " + address;
    }
}

用注解的方法标注对应数据库表中的字段.
用UserDao设计增删改操作

package cst.zju.edu.alexsun.Dao;
import cst.zju.edu.alexsun.model.User;
import cst.zju.edu.alexsun.util.HibernateUtil;
import org.hibernate.Session;

public class UserDao implements IUserDao {
    public void addUser(User user) {
        Session session = null;
        try {
            session = HibernateUtil.openSession();
            session.beginTransaction();
            session.save(user);
            session.getTransaction().commit();
        } catch (Exception e) {
            // handle the exception
            throw new RuntimeException(e);
        } finally {
            HibernateUtil.close(session);

        }
    }

    public User getUserByName(String userName) {
        Session session = null;
        User user = null;
        try {
            session = HibernateUtil.openSession();
            user = (User) session.createQuery("from User where name = ?")
                    .setParameter(0, userName).uniqueResult();

        } catch (Exception e) {
            // handle the exception
            throw new RuntimeException(e);
        } finally {
            HibernateUtil.close(session);
        }
        return user;
    }

    public void delete(User user) {
        Session session = null;
        try {
            session = HibernateUtil.openSession();

            session.beginTransaction();

            session.delete(user);

            session.getTransaction().commit();
        } catch (Exception e) {
            // handle the exception
            throw new RuntimeException(e);
        } finally {
            HibernateUtil.close(session);

        }
    }
}

用HibernateUtil进行连接,设置配置属性.

package cst.zju.edu.alexsun.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtil {
    private final static SessionFactory FACTORY = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        Configuration cfg = new Configuration().configure();
        ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
                .applySettings(cfg.getProperties()).buildServiceRegistry();
        SessionFactory factory = cfg.buildSessionFactory(serviceRegistry);
        return factory;
    }

    public static SessionFactory getSessionFactory() {
        return FACTORY;
    }

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

    public static void close(Session session) {
        if (session != null)
            session.close();
    }
}

你可能感兴趣的:(Hibernate 入门1)