hibernate入门(-)

1.struts2的支持

在web.xml中配置struts2的支持

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>
            org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

2.struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
    
    <struts>
    
        <package name="hibernate" extends="struts-default">
        
            <action name="save" class="com.test.action.PersonAction" method="save">
                <result name="success">/listAll.jsp</result>
            </action>
        
        
        </package>
    
    </struts>

3.action

package com.test.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.hibernate.model.Person;
import com.hibernate.persistence.DBPerson;
import com.opensymphony.xwork2.ActionSupport;

public class PersonAction extends ActionSupport
{
    private int id;

    private String username;

    private String password;

    private int age;

    public int getId()
    {
        return id;
    }

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

    public String getUsername()
    {
        return username;
    }

    public void setUsername(String username)
    {
        this.username = username;
    }

    public String getPassword()
    {
        return password;
    }

    public void setPassword(String password)
    {
        this.password = password;
    }

    public int getAge()
    {
        return age;
    }

    public void setAge(int age)
    {
        this.age = age;
    }

    // 完成用户增加的操作
    public String save() throws Exception
    {
        Person person = new Person();

        person.setUsername(username);
        person.setPassword(password);
        person.setAge(age);

        java.sql.Date registerDate = new java.sql.Date(new java.util.Date()
                .getTime());
        
        person.setRegisterdate(registerDate);
        
        DBPerson.save(person); //将person对象存到数据库中
        
        List<Person> list = DBPerson.listAll();
        
        HttpServletRequest request = ServletActionContext.getRequest();
        
        request.setAttribute("list", list);
        
        return SUCCESS;

    }
}

4.hibernate.cfg.xml(hibernate的主配置文件,数据库连接)

<?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">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

    <session-factory>
    
        <property name="show_sql">true</property>
    
        <property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
        <property name="connection.username">root</property>
        <property name="connection.password">123456</property>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    
        <mapping resource="Person.hbm.xml"/>
    
    </session-factory>

</hibernate-configuration>

5.实体类配置文件(Person.hbm.xml)

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

    <class name="com.hibernate.model.Person" table="person">
        
        <id name="id" column="id" type="int">
            <generator class="increment"> <!-- 主键id的生成方式为自增 -->
            </generator>
        </id>
        
        <property name="username" column="username" type="string"></property>
        <property name="password" column="password" type="string"></property>
        <property name="age" column="age" type="int"></property>
        <property name="registerdate" column="registerdate" type="date"></property>

    </class>

</hibernate-mapping>

6.创建实体类对象

package com.hibernate.model;

import java.sql.Date;

public class Person
{
    private Integer id;
    
    private String username;
    
    private String password;
    
    private Integer age;
    
    private Date registerdate;

    public Integer getId()
    {
        return id;
    }

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

    public String getUsername()
    {
        return username;
    }

    public void setUsername(String username)
    {
        this.username = username;
    }

    public String getPassword()
    {
        return password;
    }

    public void setPassword(String password)
    {
        this.password = password;
    }

    public Integer getAge()
    {
        return age;
    }

    public void setAge(Integer age)
    {
        this.age = age;
    }

    public Date getRegisterdate()
    {
        return registerdate;
    }

    public void setRegisterdate(Date registerdate)
    {
        this.registerdate = registerdate;
    }
}

7.读取hibernate的配置文件

package com.hibernate.util;

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

public class HibernateUtil
{
    private static SessionFactory sessionFactory;

    static
    {
        try
        {
            sessionFactory = new Configuration().configure()
                    .buildSessionFactory();
        }
        catch (Exception ex)
        {
            System.err.println("构造SessionFactory异常发生: " + ex.getMessage());
        }

    }

    public static Session currentSession()
    {
        Session session = sessionFactory.openSession();

        return session;
    }

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

8.完成数据库ddl的操作

package com.hibernate.persistence;

import java.util.List;

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

import com.hibernate.model.Person;
import com.hibernate.util.HibernateUtil;

public class DBPerson
{
    /**
     * 创建新的用户
     */
    
    public static void save(Person person)
    {
        Session session = HibernateUtil.currentSession();
        Transaction tx = session.beginTransaction(); //开启事务
        
        try
        {
            session.save(person);
            tx.commit();
        }
        catch(Exception ex)
        {
            System.out.println("增加用户异常发生!");
            if(null != tx)
            {
                tx.rollback();
            }
        }
        finally
        {
            HibernateUtil.closeSession(session);
        }
        
    }
    
    /**
     * 查询出所有用户
     */
    
    @SuppressWarnings("unchecked")
    public static List<Person> listAll()
    {
        Session session = HibernateUtil.currentSession();
        Transaction tx = session.beginTransaction(); //开启事务
        
        List<Person> list = null;
        
        try
        {
            Query query = session.createQuery("from Person"); //hql语句,Hibernate查询语句
            
            list = (List<Person>)query.list();
            
            tx.commit();
        }
        catch(Exception ex)
        {
            System.out.println("增加用户异常发生!");
            if(null != tx)
            {
                tx.rollback();
            }
        }
        finally
        {
            HibernateUtil.closeSession(session);
        }
        
        return list;
    }
    
    
    
}

所需要的jar包

好了 这只是一个例子,直接将例子复制到工程中即可使用。

下章将要写它的具体内容。

 

hibernate入门(-),古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。