Hibernate环境搭建

1.导入Hibernate必要jar和mysqljar

2.在bookshop数据库下建立一张users表

这里写图片描述

CREATE TABLE `users` ( `Id` int(11) NOT NULL AUTO_INCREMENT, `LoginName` varchar(50) DEFAULT NULL, `LoginPwd` varchar(16) DEFAULT NULL, `Name` varchar(20) DEFAULT NULL, `Address` varchar(16) DEFAULT NULL, `Phone` varchar(16) DEFAULT NULL, `Mail` varchar(16) DEFAULT NULL, PRIMARY KEY (`Id`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8

3.创建Users类, 与数据库字段对应

public class Users implements Serializable{
    Integer id;
    String LoginName;
    String LoginPwd;
    String Name;
    String Address;
    String Phone;
    String Mail;

    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getLoginName() {
        return LoginName;
    }
    public void setLoginName(String loginName) {
        LoginName = loginName;
    }
    public String getLoginPwd() {
        return LoginPwd;
    }
    public void setLoginPwd(String loginPwd) {
        LoginPwd = loginPwd;
    }
    public String getName() {
        return Name;
    }
    public void setName(String name) {
        Name = name;
    }
    public String getAddress() {
        return Address;
    }
    public void setAddress(String address) {
        Address = address;
    }
    public String getPhone() {
        return Phone;
    }
    public void setPhone(String phone) {
        Phone = phone;
    }
    public String getMail() {
        return Mail;
    }
    public void setMail(String mail) {
        Mail = mail;
    }

}

4.在Users类的同目录下创建Users.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="com.hib.entity.Users" table="users" catalog="bookshop">
        <id name="id" type="java.lang.Integer"> <!-- 对应主键 -->
            <column name="Id"></column>
            <generator class="native"></generator>
        </id>
        <property name="loginName" type="java.lang.String"><!-- 属性和字段的对应, 不能有generator标签 -->
            <column name="LoginName" length="50"></column>
        </property>
        <property name="LoginPwd" type="java.lang.String">
            <column name="LoginPwd" length="16"></column>
        </property>
        <property name="Name" type="java.lang.String">
            <column name="Name" length="20"></column>
        </property>
        <property name="Address" type="java.lang.String">
            <column name="Address" length="16"></column>
        </property>
        <property name="Phone" type="java.lang.String">
            <column name="Phone" length="16"></column>
        </property>
        <property name="Mail" type="java.lang.String">
            <column name="Mail" length="16"></column>
        </property>
    </class>
</hibernate-mapping>

5.在src目录下创建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>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3307/bookshop</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">1234</property>


        <!-- 显示SQL -->
        <property name="hibernate.show_sql">true</property>
        <!-- 格式化SQL -->
        <property name="hibernate.format_sql">true</property>
        <!-- 自动建表 -->
        <property name="hibernate.hbm2ddl.auto">update</property>
        <!-- 数据库的方言 ,识别某种数据库特定的语句-->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>


        <property name="javax.persistence.validation.mode">none</property>

        <!-- 注册映射文件 -->
        <mapping resource="com/hib/entity/Users.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

6.编写HibernateUtils类

package com.hib2;
import java.io.Serializable;  

import org.hibernate.Session;  
import org.hibernate.SessionFactory;  
import org.hibernate.Transaction;  
import org.hibernate.cfg.AnnotationConfiguration;  

public class HibernateUtils {  
    private static SessionFactory sessionFactory;  

    private HibernateUtils() {  
    }  

    static {  
        sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();  
    }  

    public static SessionFactory getSessionFactory() {  
        return sessionFactory;  
    }  


    public static Session getCurrentSession() {  
        return sessionFactory.getCurrentSession();  
    }  
    public static Session getNewSession() {  
        return sessionFactory.openSession();  
    }  
    public static void add(Object entity) {  
        Session s = null;  
        Transaction tx = null;  
        try {  
            s = HibernateUtils.getNewSession();  
            tx = s.beginTransaction();  
            s.save(entity);  
            tx.commit();  
        } finally {  
            if (s != null)  
                s.close();  
        }  
    }  

    public static void update(Object entity) {  
        Session s = null;  
        Transaction tx = null;  
        try {  
            s = HibernateUtils.getNewSession();  
            tx = s.beginTransaction();  
            s.update(entity);  
            tx.commit();  
        } finally {  
            if (s != null)  
                s.close();  
        }  
    }  

    public static void delete(Object entity) {  
        Session s = null;  
        Transaction tx = null;  
        try {  
            s = HibernateUtils.getNewSession();  
            tx = s.beginTransaction();  
            s.delete(entity);  
            tx.commit();  
        } finally {  
            if (s != null)  
                s.close();  
        }  
    }

    public static Object get(Class clazz, Serializable id) {  
        Session s = null;
        try {  
            s = HibernateUtils.getNewSession();  
            Object obj = s.get(clazz, id);  
            return obj;  
        } finally {  
            if (s != null)
                s.close();  
        }  
    }  
}

最后编写crud类进行测试

package com.hib2;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.hib.entity.Users;

public class Test {



    public static void main(String[] args) {
        //new Test().add();
        //new Test().getObject(3);
        new Test().update(3);
        //new Test().delete(3);
    }

    private void add() {
        Users user = new Users();
        //添加
        user.setLoginName("lisi");
        user.setLoginPwd("1234");
        user.setName("李四");
        user.setAddress("安徽");
        user.setPhone("02112345678");
        user.setMail("12@qq.com");
        HibernateUtils.add(user);
    }

    private void delete(Integer i){
        Users user = (Users) HibernateUtils.get(Users.class, i);
        //删除
        HibernateUtils.delete(user);
    }

    private void getObject(Integer i){
        //获取
        Users u = (Users) HibernateUtils.get(Users.class, i);
        System.out.println(u);
    }

    /** * */
    private void update(Integer i){
        Users user = (Users) HibernateUtils.get(Users.class, i);
        user.setName("李思思");
        //修改
        HibernateUtils.update(user);
    }
}
相关文章

相关标签/搜索